Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat: integrate the remaining local desktop work after 3.0.0 (#514)
Ruben Lütke161335e14543
diff --git a/NOTICE b/NOTICEindex d230a7952b..94962d2a7a 100644--- a/NOTICE+++ b/NOTICE@@ -20,6 +20,12 @@ contains portions adapted from T3 Code (https://github.com/pingdotgg/t3code),Copyright (c) 2026 T3 Tools Inc., used under the MIT License - seethird_party/t3code/LICENSE.+The Computers settings page (jarvis/ui/web/frontend/src/views/computers/surface.tsx+and ComputerRow.tsx) contains portions adapted from T3 Code under the same MIT+License, Copyright (c) 2026 T3 Tools Inc. So do its connection features: jarvis/computers/+ssh_config.py, tailscale.py, placement.py and github_access.py, and the views RouteList.tsx,+Placement.tsx, GithubAccess.tsx and machineKind.tsx beside it.+The Agentic IDE explorer's file-type icons (jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/fileIconSprite.ts and fileIcon.ts) contain SVG symbolsand file-name rules from @pierre/trees (https://www.npmjs.com/package/@pierre/trees),diff --git a/docs/licensing.md b/docs/licensing.mdindex 0d629c5fda..a821a43c91 100644--- a/docs/licensing.md+++ b/docs/licensing.md@@ -75,6 +75,11 @@ Copyright (c) 2026 T3 Tools Inc. The full text ships in[`third_party/t3code/LICENSE`](../third_party/t3code/LICENSE), and every adaptedfile names its source in a header comment.+The Computers settings page (`jarvis/ui/web/frontend/src/views/computers/surface.tsx`+and `ComputerRow.tsx`) contains portions of the settings layout, environment row,+status dot and empty state adapted from T3 Code @ `12069ee` under the same MIT+license; both files name their source in a header comment. The connection features of the same page — several addresses per computer, the SSH-config and Tailscale suggestions, the on/off switch, automatic placement and GitHub sharing (`jarvis/computers/ssh_config.py`, `tailscale.py`, `placement.py`, `github_access.py`; `views/computers/RouteList.tsx`, `Placement.tsx`, `GithubAccess.tsx`, `machineKind.tsx`) — adapt further portions of T3 Code @ `12069ee`, each credited the same way.+The Agentic IDE explorer's coloured file-type icons(`jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/fileIconSprite.ts`and `fileIcon.ts`) contain SVG symbols and file-name rules copied fromdiff --git a/docs/os-parity.md b/docs/os-parity.mdindex b9bfea286f..e6352344ee 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1385,6 +1385,7 @@ build: the first release with this code needs one live update per OS.| P-41 | Low | CLI install / connect terminal | Pressing **Install** or **Connect** in the CLI section opens a REAL terminal window and runs the command there, because an interactive OAuth login belongs in a shell the user can see and type into. That spawn was Windows-only until 2026-08-28 (`wt` -> `pwsh` -> `powershell`), so on macOS and Linux the two buttons reported "No external terminal available" and no CLI could be installed from the app at all. macOS now goes through `osascript` to Terminal.app, Linux through the first of seven emulators that exists (Debian's `x-terminal-emulator` alternative first, so the user's own default wins), and the window is held open afterwards the way `-NoExit` holds it on Windows. One install click now carries all the way to signed in: the terminal runs the install, refreshes PATH in that same shell, and continues into the CLI's login command, stopping at the first step that fails. The chain operator differs per OS on purpose — Windows PowerShell 5.1 is a possible fallback shell and `&&` is a parser error there, so the Windows spelling nests `if ($?)` instead | `jarvis/clis/external_terminal.py` (`_spawn_windows`, `_spawn_macos`, `_spawn_linux`, `chain_commands`, `path_refresh_command`), `jarvis/ui/web/cli_routes.py::spawn_external`, `tests/unit/clis/test_install_path.py` | Windows: verified live (wt path, composed install+login command). macOS/Linux: same code path, the branch itself unverified from this machine. A box with no screen has no window to open, so there the endpoint falls back to the in-app streaming install job and the UI says so instead of claiming a terminal appeared — a headless server can still install a CLI, it just cannot run an interactive login || P-42 | High | Outbound sockets (every lane) | Every connection borrows an ephemeral port from a pool the OS owns, and a closed one keeps that port through TIME_WAIT. The ceiling and the linger differ per OS, and so does what gives out first: **Windows** 16 384 ports / 120 s — the tightest by far, and the port pool is what empties, which stops EVERY process on the machine from connecting (the desktop appears frozen, then heals itself when TIME_WAIT expires); **Linux** 28 232 ports / 60 s, but `RLIMIT_NOFILE` is normally the tighter of the two (1024 on a stock `python:3.11-slim`), so the backend dies of EMFILE while the desktop around it is fine; **macOS** 16 384 ports / 15 s, so it recovers fastest. BUG-215 was the Windows shape: an unjittered wake storm (one socket per pane, per window, per instance, all on one `visibilitychange`) on top of a standing per-call-client burn. The rule that follows is to cap the burst, never to widen a limit — code that fits the Windows budget fits everywhere | `jarvis/ui/web/frontend/src/lib/connectBudget.ts` (`jitteredDelay`, `spreadDelay`, `requestConnect`), `jarvis/core/http_pool.py` (`HttpClientPool`, `SyncHttpClientPool`, `default_limits`), `jarvis/core/socket_budget.py` (`read_platform_limits`, `take_census`, `SocketBudgetWatchdog`), `jarvis/realtime/local_server/supervisor.py::_port_open` (`SO_LINGER`) | Identical on all three: one shared connect budget in the frontend, pooled keep-alive clients in Python, and a watchdog armed by BOTH entry points (desktop shell and `--headless`) that reads the ceiling per platform — `netsh` on Windows (parsed as integers, because it translates its own field names), `/proc/sys/net/ipv4/ip_local_port_range` plus `RLIMIT_NOFILE` on Linux, `sysctl net.inet.ip.portrange.*` on macOS. A host that answers none of them falls back to the documented default and says the number was assumed; a host with no ceiling at all logs one line and throttles nothing, because a watchdog that cannot see must never be what stops the app working. macOS additionally refuses the system-wide socket table to an unprivileged process, so the census there counts this process only and labels the number a floor. Guards: `tests/contract/test_socket_budget.py` (all three hosts faked, plus a German and a Japanese `netsh`), `tests/unit/core/test_socket_budget_watchdog.py`, `jarvis/ui/web/frontend/src/lib/connectBudget.test.ts` || P-45 | Medium | Hermes / OpenClaw agent runtimes | A society agent can run on Hermes or OpenClaw instead of Jarvis' own loop (docs/agent-runtimes.md), driven over ACP: Hermes as one `hermes acp` process per turn, every agent a profile of one Jarvis-owned Hermes data root (`<runtimes_root>/hermes-home/profiles/<agent>`, one shared dependency environment, prepared by the setup job); OpenClaw through `openclaw acp` against a supervised per-agent Gateway. Setup goes to the pinned `tested` release (`runtime-versions.json`) per OS: Hermes' `install.ps1` / `install.sh` at the pinned commit without browser tools or desktop control; OpenClaw as Jarvis' own copy with a private Node.js — `install.ps1 -NodeOnly` plus that Node's npm on Windows (no winget/UAC), `install-cli.sh --prefix` on macOS/Linux (no sudo). POSIX installer scripts are downloaded first and run under `set -euo pipefail`, so a missing `curl`/`git` or a failed download fails the job with a plain reason. Containment differs per OS exactly as for every CLI seat: a Job Object on Windows; a process group on POSIX plus a descendant tracker that also reaps children started under `setsid` (Hermes runs shell commands that way), found by tree walks and by a per-turn environment mark every descendant inherits, and a `gateway.pid` sweep that stops a Gateway a crashed app left behind (POSIX only — the Job Object already reaps it on Windows). Hermes' Windows home maintenance would register its data root's `bin` on the user's PATH; a `bin` file blocks that, POSIX uses `cli.expose_on_path: false`, and stale entries from older builds are removed once per run. Stop sends ACP `session/cancel` before any kill, and a stall watchdog ends a turn whose runtime stopped responding | `jarvis/agent_runtimes/` (`hermes.py`, `openclaw.py`, `base.py` (`which`, `RuntimeGate`, `HomeFileLock`, `posix_installer`, `windows_installer`), `manager.py`, `versions.py`, `runtime-versions.json`, `path_cleanup.py`), `jarvis/agent_chat/runner_cli.py` (ACP cancel + stall watchdog), `jarvis/core/process_tree.py::DescendantTracker`, `jarvis/core/path_augment.py::refresh_from_persistent_path` | Windows: verified 2026-10-07 with Hermes 0.21.5 and OpenClaw 2026.9.8 through the replay e2e spikes (both model-gateway protocols; Hermes prepare 37–45 s once, first turn 6.8–8.3 s; OpenClaw first turn 31–55 s including the Gateway cold start; the user PATH unchanged, checked against the registry), and through `tests/unit/agent_runtimes/` (fake ACP agent, fake OpenClaw CLI, injected registry). macOS/Linux: the same code paths; the setsid reaping, `flock` locks, `install-cli.sh` and `pipefail` wrapper run only on POSIX CI runners (unit tests, `agent-runtimes-canary.yml`), not verified on a real Mac or Linux desktop from this machine. Headless `python:3.11-slim`: nothing is installed or started unless an agent is switched to a runtime; without `curl`/`git` the setup fails with that reason instead of reporting success. Guards: `tests/unit/agent_runtimes/`, `tests/unit/society/test_agent_runtime_field.py` |+| P-46 | Low | Computers: this PC's SSH hosts and Tailscale | The add dialog lists the servers this PC's own `ssh` already knows and each computer can take a second address from Tailscale. Both read only local files or the local CLI, and both differ per OS only in where those live: `~/.ssh/config` and `~/.ssh/known_hosts` under the home folder (`%USERPROFILE%\.ssh` on Windows, where Git for Windows and the Windows OpenSSH client keep the same files), `Include` globs resolved relative to `~/.ssh` as OpenSSH does; the Tailscale CLI from `PATH`, else `C:\Program Files\Tailscale\tailscale.exe` (Windows) or the app bundle's `/Applications/Tailscale.app/Contents/MacOS/Tailscale` (macOS); Linux packages put it on `PATH`. A missing file, a missing CLI, a logged-out Tailscale or any error means simply nothing to offer. Every address a computer has must show the same pinned server identity, on every OS, so a second address can never reach a different machine | `jarvis/computers/ssh_config.py`, `jarvis/computers/tailscale.py` (`binary`, `peers`), `jarvis/computers/service.py` (`_open`, `add_route`), `jarvis/computers/ssh.py::key_files` | Windows: verified live 2026-10-08 (known_hosts read from `%USERPROFILE%`, no Tailscale installed: empty suggestions; routes, failover and the identity check against two local SSH servers). macOS/Linux: same code, unverified on a real box; the parsers are pure and covered by `tests/unit/computers/test_ssh_config_and_tailscale.py`, the failover by `tests/unit/computers/test_routes_and_switch.py`. Headless `python:3.11-slim`: no `~/.ssh`, no Tailscale: both lists are empty and nothing else changes |## Agent conversation continuity and learning (2026-09-07)diff --git a/docs/server-pairing.md b/docs/server-pairing.mdnew file mode 100644index 0000000000..9db4b304c2--- /dev/null+++ b/docs/server-pairing.md@@ -0,0 +1,46 @@+# Connect an independent Jarvis server++In **Settings → Computers → Add computer**, choose **Server address** to+connect another running Jarvis instance. Choose **SSH** for remote shell,+terminal, agent installation, and computer execution features.++On the target instance, open the same Server address form and expand+**Allow another computer to connect to this Jarvis**. Generate a pairing code.+The code grants access to that instance's Jarvis interface, expires after five+minutes, and can be used once. Enter the target's HTTPS address and code on+the connecting computer, or paste the pairing URL. HTTP is accepted only for+direct loopback connections, such as an SSH tunnel. Generating a code does not+open network ports, change the bind address, or configure a reverse proxy.+Both instances must support the `jarvis-pairing-v1` protocol.++A successful exchange adds the server to the **Jarvis servers** list. **Open+server** obtains a one-minute, single-use link and opens the server's normal+authenticated interface in the browser. Checks verify the saved credential+without invoking a model. The last check's result is displayed explicitly;+there is no background polling or paid health probe.++Server credentials use the existing OS keyring and headless credential-file+fallback. Connection metadata contains no codes or credentials. The target+persists credential hashes and offers client revocation in the pairing panel.+Disconnecting from the client revokes its remote credential before deleting+the local record; an unreachable target reports failure and keeps that record.+Revocation blocks future connections and pending links. Browser sessions that+were already opened remain signed in until their normal session lifetime ends.++Pairing is an independent-server UI connection, not an SSH transport. Paired+servers are therefore not offered as SSH execution or IDE offload targets.+Use SSH for those workflows, or run work from the paired server's own UI.++The mounted `computer-pairing` API group exposes code creation, redemption,+server listing/checking/opening, and client revocation through the dynamic+Jarvis CLI. Supply secrets through stdin or request-body files, never command+arguments. Code, credential, and ticket responses use `Cache-Control: no-store`.++Validation includes two-sided ASGI HTTP tests through the application's+Host/Origin/credential boundary, persistent-store reload, one-use and expiry+checks, blocked redirects/plaintext remote origins, and frontend interactions.+A Windows loopback HTTP probe with the application's credential backend also+verified pairing, persisted reload, browser session exchange, replay rejection,+remote revocation, and removal of the test credential.+These tests do not constitute proof of an arbitrary external deployment's+TLS, firewall, or network configuration.diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.pyindex 98736b4c63..35d5813d4b 100644--- a/jarvis/agent_accounts.py+++ b/jarvis/agent_accounts.py@@ -275,7 +275,7 @@ def _read_store() -> dict[str, Any]:"""The stored state, or an empty one for every unreadable shape."""try:raw = _store_path().read_text(encoding="utf-8")- except FileNotFoundError:+ except FileNotFoundError: # no store yet is the first-run statereturn {"accounts": [], "active": {}}except OSError as exc:logger.warning("Agent accounts: store could not be read ({}) — ignoring it", exc)@@ -289,24 +289,29 @@ def _read_store() -> dict[str, Any]:return {"accounts": [], "active": {}}accounts = data.get("accounts")active = data.get("active")- return {+ switching = data.get("auto_switch")+ state: dict[str, Any] = {"accounts": accounts if isinstance(accounts, list) else [],"active": active if isinstance(active, dict) else {},}+ if isinstance(switching, dict):+ state["auto_switch"] = switching+ return statedef _write_store(state: Mapping[str, Any]) -> None:"""Atomic write — a half-written store must never be a readable one."""path = _store_path()- payload = json.dumps(- {- "version": SCHEMA_VERSION,- "accounts": list(state.get("accounts", [])),- "active": dict(state.get("active", {})),- },- indent=2,- ensure_ascii=False,- )+ document: dict[str, Any] = {+ "version": SCHEMA_VERSION,+ "accounts": list(state.get("accounts", [])),+ "active": dict(state.get("active", {})),+ }+ if isinstance(state.get("auto_switch"), Mapping):+ # Optional and additive: an older build reads the same version and+ # simply ignores the key, so it needs no schema bump.+ document["auto_switch"] = dict(state["auto_switch"])+ payload = json.dumps(document, indent=2, ensure_ascii=False)try:path.parent.mkdir(parents=True, exist_ok=True)tmp = path.with_name(f"{path.name}.{uuid4().hex[:8]}.tmp")@@ -333,7 +338,7 @@ def _parse_account(raw: Any) -> AgentAccount | None:label = label if isinstance(label, str) and label.strip() else account_idtry:directory = Path(config_dir).expanduser()- except (OSError, ValueError):+ except (OSError, ValueError): # an unusable directory makes the row invalidreturn Nonereturn AgentAccount(id=account_id,@@ -531,6 +536,82 @@ def delete_account(account_id: str, *, remove_files: bool = False) -> AgentAccoureturn account+# ------------------------------------------------------------ auto switch++#: Where a seat counts as used up and its work moves to the next one: 97 % of+#: its tightest limit, i.e. three percent left. Late enough not to abandon a+#: seat with real budget on it, early enough that the turn in flight usually+#: finishes before the provider refuses the next request.+DEFAULT_SWITCH_AT_PERCENT = 97.0++#: The bounds a user may move that threshold within. Below 50 a seat would be+#: abandoned with half its plan unused; at 100 the switch only ever follows a+#: refusal, which is still handled (see :mod:`jarvis.agentic_ide.seat_switch`).+MIN_SWITCH_AT_PERCENT = 50.0+MAX_SWITCH_AT_PERCENT = 100.0+++@dataclass(frozen=True, slots=True)+class AutoSwitch:+ """Whether running work follows a seat that runs out, and at what point."""++ enabled: bool = True+ at_percent: float = DEFAULT_SWITCH_AT_PERCENT++ def to_dict(self) -> dict[str, Any]:+ return {"enabled": self.enabled, "at_percent": self.at_percent}+++def _clamp_switch_percent(value: Any) -> float:+ try:+ number = float(value)+ except (TypeError, ValueError): # a malformed setting falls back to the default+ return DEFAULT_SWITCH_AT_PERCENT+ if number != number: # NaN+ return DEFAULT_SWITCH_AT_PERCENT+ return max(MIN_SWITCH_AT_PERCENT, min(MAX_SWITCH_AT_PERCENT, number))+++def auto_switch() -> AutoSwitch:+ """The stored auto-switch choice; on by default.++ On by default because holding a second seat has exactly one purpose — to+ keep working when the first one runs out — and a feature that has to be+ discovered and switched on first fails the user at the very moment it+ exists for. A user with a single seat is unaffected: there is nothing to+ switch to.+ """+ raw = _read_store().get("auto_switch")+ if not isinstance(raw, dict):+ return AutoSwitch()+ enabled = raw.get("enabled")+ return AutoSwitch(+ enabled=enabled if isinstance(enabled, bool) else True,+ at_percent=_clamp_switch_percent(raw.get("at_percent", DEFAULT_SWITCH_AT_PERCENT)),+ )+++def set_auto_switch(*, enabled: bool | None = None, at_percent: float | None = None) -> AutoSwitch:+ """Change the auto-switch choice; omitted fields keep their stored value."""+ with _WRITE_LOCK:+ state = _read_store()+ current = state.get("auto_switch") if isinstance(state.get("auto_switch"), dict) else {}+ merged = dict(current)+ if enabled is not None:+ merged["enabled"] = bool(enabled)+ if at_percent is not None:+ merged["at_percent"] = _clamp_switch_percent(at_percent)+ state["auto_switch"] = merged+ _write_store(state)+ choice = auto_switch()+ logger.info(+ "Agent accounts: auto switch {} at {:.0f} %",+ "on" if choice.enabled else "off",+ choice.at_percent,+ )+ return choice++# ------------------------------------------------------------------ spawn@@ -643,7 +724,7 @@ def _read_settings(path: Path, fmt: str) -> dict[str, Any] | None:"""try:raw = path.read_text(encoding="utf-8-sig")- except OSError:+ except OSError: # an unreadable file means nothing to inheritreturn Nonetry:if fmt == "json":@@ -667,7 +748,7 @@ def _open_settings(path: Path, fmt: str) -> Any:"""try:raw = path.read_text(encoding="utf-8-sig")- except OSError:+ except OSError: # a missing file is written fresh belowraw = ""try:if fmt == "json":@@ -1187,16 +1268,21 @@ def start_login(account: AgentAccount) -> Any:__all__ = [+ "DEFAULT_SWITCH_AT_PERCENT","MAX_ACCOUNTS_PER_PLATFORM",+ "MAX_SWITCH_AT_PERCENT",+ "MIN_SWITCH_AT_PERCENT","MAX_LABEL_CHARS","SCHEMA_VERSION","AccountError","AccountSnapshot","AgentAccount",+ "AutoSwitch","Platform","active_account","active_ids","all_accounts",+ "auto_switch","builtin_id","config_dir_for","create_account",@@ -1214,6 +1300,7 @@ __all__ = ["rename_account","resolve","set_active",+ "set_auto_switch","snapshots","spawn_env","start_login",diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex 2b99654e76..085194d7e7 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -374,6 +374,7 @@ def _account_env(platform: str) -> dict[str, str]:account = pinnedelse:account = agent_accounts.active_account(platform) # type: ignore[arg-type]+ account = _seat_with_budget(platform, account)env = agent_accounts.spawn_env(platform, account.id, base=os.environ) # type: ignore[arg-type]except CliUnavailable:raise@@ -388,6 +389,76 @@ def _account_env(platform: str) -> dict[str, str]:return env+def _seat_with_budget(platform: str, account: Any) -> Any:+ """``account``, or the active seat when ``account`` ran out of its plan.++ A thread pinned to a seat that refused for its usage limit would fail+ every turn until that seat refills; with automatic switching on, the turn+ runs on the seat the rest of the work already moved to+ (:mod:`jarvis.agentic_ide.seat_switch`). Its conversation follows it+ (``_carry_thread_conversation``).+ """+ try:+ from jarvis import agent_accounts+ from jarvis.agentic_ide import seat_switch++ replacement = seat_switch.preferred_seat(platform, account.id)+ if replacement is None:+ return account+ return agent_accounts.resolve(replacement) or account+ except Exception as exc: # noqa: BLE001 - the pinned seat is still a valid answer+ log.debug("Seat failover unavailable for %s (%s)", platform, type(exc).__name__)+ return account+++#: Runner -> (account platform, resume kind) for the CLIs whose conversations+#: can follow a seat switch (:mod:`jarvis.agentic_ide.seat_handoff`).+_SEAT_CONVERSATIONS: dict[str, tuple[str, str]] = {+ "claude-cli": ("claude", "claude_session"),+ "codex-cli": ("codex", "codex_rollout"),+ "grok-cli": ("grok-build", "grok_session"),+}+++#: (runner, conversation id) -> the seat dir its last turn ran on. A thread+#: whose seat did not change since needs no search across the other seats —+#: for Codex that search is a sweep of every rollout folder.+_CARRIED_HOMES: dict[tuple[str, str], str] = {}+++def _carry_thread_conversation(runner: str, resume: str | None, env: dict[str, str]) -> None:+ """Make a resumed thread find its conversation on the seat it runs on now.++ Each seat keeps its own history, so after a switch ``--resume <id>`` on+ the new seat would answer "no conversation found" and the thread would+ lose everything it knew. The newest copy across the CLI's seats is+ carried into the seat this turn runs on. Filesystem work: off the loop.+ """+ pair = _SEAT_CONVERSATIONS.get(runner)+ if not resume or pair is None:+ return+ platform, kind = pair+ try:+ from jarvis import agent_accounts+ from jarvis.agentic_ide import seat_handoff++ if platform not in agent_accounts.platforms():+ return+ variable = agent_accounts.env_var(platform)+ raw = env.get(variable or "", "").strip()+ home = Path(raw).expanduser() if raw else agent_accounts.native_dir(platform)+ key = (runner, resume)+ if _CARRIED_HOMES.get(key) == os.path.normcase(str(home)):+ return+ homes = [account.config_dir for account in agent_accounts.list_accounts(platform)]+ if seat_handoff.carry_conversation(kind, resume, home, homes):+ if len(_CARRIED_HOMES) > 512:+ _CARRIED_HOMES.clear()+ _CARRIED_HOMES[key] = os.path.normcase(str(home))+ except Exception as exc: # noqa: BLE001 - a fresh start is the honest fallback+ log.warning("Conversation could not follow the seat for %s: %s", runner, exc)++def _registry_env(agent: str, base: dict[str, str]) -> dict[str, str]:"""``base`` with the Agentic IDE registry's per-CLI environment on top.@@ -3472,6 +3543,7 @@ async def _run_cli_once(resume=resume,identity=identity,)+ await asyncio.to_thread(_carry_thread_conversation, runner, resume, plan.env)if getattr(handle, "tools_disabled", False):from .native_control import disable_cli_tools@@ -4135,7 +4207,7 @@ async def _drive_cli(# in the turn host and the next app start carries the turn on.proc.detach()else:- await _cancel_acp()+ await _acp_cancel()_kill(proc)raisefinally:diff --git a/jarvis/agent_chat/tool_catalog.py b/jarvis/agent_chat/tool_catalog.pyindex 16f483857e..413759a75d 100644--- a/jarvis/agent_chat/tool_catalog.py+++ b/jarvis/agent_chat/tool_catalog.py@@ -38,6 +38,10 @@ class ToolChoice(BaseModel):available: bool = Truetool_names: tuple[str, ...] = ()skill: str = ""+ # A plugin the owner added here (custom connector or upload). The Add+ # menu lists these even before they are connected, so a connector just+ # added is never hidden behind a search.+ user_added: bool = Falsedef category_for(name: str) -> Category:@@ -99,6 +103,7 @@ def build_catalog(brand=spec.id,available=available,tool_names=names,+ user_added=getattr(spec, "source", "") == "local",))owned.update(names)@@ -113,6 +118,7 @@ def build_catalog(rows.append(ToolChoice(id=f"plugin:custom-api-{api_id}", label=label,description=str(getattr(tool, "custom_api_description", "") or tool.description),+ brand=str(getattr(tool, "custom_api_brand", "")),category="plugins", group=label, tool_names=tuple(names),))owned.update(names)diff --git a/jarvis/agent_runtimes/gateway.py b/jarvis/agent_runtimes/gateway.pyindex 7ccab6e994..48f06259f6 100644--- a/jarvis/agent_runtimes/gateway.py+++ b/jarvis/agent_runtimes/gateway.py@@ -1403,6 +1403,15 @@ def _with_output_capacity(request: Any, limits: ModelLimits) -> Any:return replace(request, max_tokens=max(min(budget, room), _MIN_OUTPUT_TOKENS))+def invalidate_provider_metadata(provider: str) -> None:+ """A changed endpoint must not reuse the previous server's model limits."""+ global _CATALOG+ _CATALOG = None+ with _LOCK:+ for grant in [grant for grant in _MODEL_LIMITS if grant.provider == provider]:+ del _MODEL_LIMITS[grant]++def reset() -> None:"""Forget every token, client and remembered signature (tests)."""global _CATALOGdiff --git a/jarvis/agent_runtimes/model_limits.py b/jarvis/agent_runtimes/model_limits.pyindex 883717ebd8..5b92c0cb87 100644--- a/jarvis/agent_runtimes/model_limits.py+++ b/jarvis/agent_runtimes/model_limits.py@@ -65,7 +65,8 @@ def resolve_limits(config: Any, provider: str, model: str, metadata: Any = None)if provider == "ollama":providers = getattr(getattr(config, "brain", None), "providers", {})options = getattr(providers.get(provider), "models", {})- selected = options.get(model) or options.get(f"{model}:latest")+ selected = (options.get(model) or options.get(model.removesuffix(":latest"))+ or options.get(f"{model}:latest"))allocated = positive_int(getattr(selected, "num_ctx", None))if allocated:context = min(allocated, declared_context or allocated)diff --git a/jarvis/agentic_ide/offload_on_quit.py b/jarvis/agentic_ide/offload_on_quit.pyindex 63a8364091..7a2f66a83d 100644--- a/jarvis/agentic_ide/offload_on_quit.py+++ b/jarvis/agentic_ide/offload_on_quit.py@@ -11,7 +11,8 @@ and a move that could not finish leaves the pane where it was (the placementis recorded only after the move completed).A Windows computer is never a target: it has no tmux, so its panes end with-the app's SSH connection (``jarvis.computers.remote_terminal``).+the app's SSH connection (``jarvis.computers.remote_terminal``). Neither is a+computer the user switched off: nothing connects to it."""from __future__ import annotations@@ -60,6 +61,13 @@ def _is_windows(computer_id: str) -> bool:return facts is not None and facts.os_id == "windows"+def _is_switched_off(computer_id: str) -> bool:+ from jarvis.computers.store import ComputerStore++ computer = ComputerStore().get(computer_id)+ return computer is not None and not computer.enabled++async def offload_before_quit(registry: Any) -> list[str]:"""Move every workspace with a locally running agent. Returns their ids."""computer_id = target()@@ -73,6 +81,9 @@ async def offload_before_quit(registry: Any) -> list[str]:computer_id,)return []+ if _is_switched_off(computer_id):+ logger.warning("Agentic IDE: not moving panes on quit — {} is switched off", computer_id)+ return []moved: list[str] = []for workspace in list(registry.sessions):running_here = [diff --git a/jarvis/agentic_ide/seat_handoff.py b/jarvis/agentic_ide/seat_handoff.pynew file mode 100644index 0000000000..b9da77d8e9--- /dev/null+++ b/jarvis/agentic_ide/seat_handoff.py@@ -0,0 +1,442 @@+"""Carry a coding-CLI conversation from one subscription seat to another.++Every seat of a CLI (:mod:`jarvis.agent_accounts`) is its own config directory,+and the CLI files its conversations INSIDE that directory. So a conversation+started on seat A is invisible to the same CLI started on seat B: ``--resume+<id>`` there answers "no conversation found", and the agent that was supposed+to carry on after the switch starts from nothing. Switching seats mid-work is+only useful if the work comes along — this module is what makes it come along.++**Copy, never link.** The conversation files are copied into the target seat's+directory at the same relative path the CLI would have used there, so the CLI+finds them exactly as if it had written them itself. A link would tie two seats+to one file that both CLIs append to; a copy is owned by whoever resumes it.++**Newest copy wins, and only forward.** A conversation lives on exactly one+seat at a time — the one its pane runs on — so the copy with the newest+modification time IS the conversation, and every other copy is an older prefix+of it. Switching back and forth therefore always moves the latest state, and a+seat that already holds the newest copy is left untouched. ``shutil.copy2``+keeps the modification time, which is what makes a second carry a no-op.++**What travels, per CLI** (the layouts are measured, not assumed):++* Claude Code — ``projects/<folder>/<id>.jsonl``, the sibling ``<id>/`` folder+ (subagent transcripts, large tool results) and ``file-history/<id>/`` (what+ ``/rewind`` restores from).+* Codex — ``sessions/YYYY/MM/DD/rollout-…-<id>.jsonl``.+* Grok Build — ``sessions/<folder>/<id>/``.++Every other CLI keeps its history somewhere this module cannot carry, and gets+an honest ``False``: the pane then starts fresh on the new seat, which is what+it did before this module existed, and the caller says so.++Never raises. A conversation that cannot be carried is a fresh start, not a+pane that fails to open. Cross-platform: ``pathlib`` throughout, no OS branch.+"""++from __future__ import annotations++import json+import os+import shutil+import time+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any+from uuid import uuid4++from loguru import logger++#: Bytes read from the END of a transcript when looking for a usage-limit stop.+#: The record that matters is the last turn, so it is always near the tail.+LIMIT_TAIL_BYTES = 256 * 1024++#: A limit stop older than this no longer explains why a pane is idle; the user+#: has had every chance to see it and act. Keeps a long-quiet pane from being+#: switched and nudged hours later for a limit that already reset.+LIMIT_STALE_S = 6 * 3600.0+++@dataclass(frozen=True, slots=True)+class _Located:+ """One seat's copy of a conversation: its newest file and what belongs to it."""++ home: Path+ #: The file whose modification time dates this copy.+ anchor: Path+ #: (source path, path relative to the home) for every file or folder to copy.+ parts: tuple[tuple[Path, Path], ...]++ @property+ def mtime(self) -> float:+ try:+ return self.anchor.stat().st_mtime+ except OSError: # a vanished transcript sorts as oldest+ return 0.0+++def _safe_id(session_id: str) -> bool:+ return bool(session_id) and not any(sep in session_id for sep in ("/", "\\", "*", "?"))+++# ------------------------------------------------------------------ layouts+++def _claude_locate(home: Path, session_id: str, _captured_at: float) -> _Located | None:+ projects = home / "projects"+ if not projects.is_dir():+ return None+ transcript = next(projects.glob(f"*/{session_id}.jsonl"), None)+ if transcript is None or not transcript.is_file():+ return None+ parts: list[tuple[Path, Path]] = [(transcript, transcript.relative_to(home))]+ sibling = transcript.with_suffix("")+ if sibling.is_dir():+ parts.append((sibling, sibling.relative_to(home)))+ history = home / "file-history" / session_id+ if history.is_dir():+ parts.append((history, history.relative_to(home)))+ return _Located(home=home, anchor=transcript, parts=tuple(parts))+++def _codex_day_folders(sessions: Path, captured_at: float) -> list[Path]:+ """Day folders worth searching; the newest-first full sweep when undated."""+ if captured_at <= 0:+ return []+ day = datetime.fromtimestamp(captured_at, tz=UTC).date()+ folders = []+ for offset in (0, -1, 1):+ shifted = day + timedelta(days=offset)+ folders.append(+ sessions / f"{shifted.year:04d}" / f"{shifted.month:02d}" / f"{shifted.day:02d}"+ )+ return folders+++def _codex_locate(home: Path, session_id: str, captured_at: float) -> _Located | None:+ sessions = home / "sessions"+ if not sessions.is_dir():+ return None+ found: Path | None = None+ for folder in _codex_day_folders(sessions, captured_at):+ found = next(folder.glob(f"rollout-*{session_id}*.jsonl"), None)+ if found is not None:+ break+ if found is None:+ found = next(sessions.glob(f"*/*/*/rollout-*{session_id}*.jsonl"), None)+ if found is None or not found.is_file():+ return None+ return _Located(home=home, anchor=found, parts=((found, found.relative_to(home)),))+++def _grok_locate(home: Path, session_id: str, _captured_at: float) -> _Located | None:+ root = home / "sessions"+ if not root.is_dir():+ return None+ folder = next(root.glob(f"*/{session_id}"), None)+ if folder is None or not folder.is_dir():+ return None+ log = folder / "updates.jsonl"+ return _Located(+ home=home,+ anchor=log if log.is_file() else folder,+ parts=((folder, folder.relative_to(home)),),+ )+++_LAYOUTS = {+ "claude_session": _claude_locate,+ "codex_rollout": _codex_locate,+ "grok_session": _grok_locate,+}+++def can_carry(kind: str) -> bool:+ """Whether conversations of this resume kind can follow a seat switch."""+ return kind in _LAYOUTS+++# -------------------------------------------------------------------- carry+++def _same_dir(left: Path, right: Path) -> bool:+ return os.path.normcase(os.path.abspath(left)) == os.path.normcase(os.path.abspath(right))+++def _copy_file(source: Path, target: Path) -> None:+ """Atomic replace, so a CLI never opens a half-copied transcript."""+ target.parent.mkdir(parents=True, exist_ok=True)+ tmp = target.with_name(f"{target.name}.{uuid4().hex[:8]}.carry")+ try:+ shutil.copy2(source, tmp)+ os.replace(tmp, target)+ finally:+ if tmp.exists():+ tmp.unlink(missing_ok=True)+++def _copy_part(source: Path, target: Path) -> None:+ if source.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ for child in source.iterdir():+ _copy_part(child, target / child.name)+ return+ try:+ if target.is_file():+ src, dst = source.stat(), target.stat()+ if dst.st_mtime >= src.st_mtime and dst.st_size == src.st_size:+ return+ except OSError: # unknown freshness: copy again below+ pass+ _copy_file(source, target)+++def carry_conversation(+ kind: str,+ session_id: str,+ target_home: Path,+ homes: list[Path],+ *,+ captured_at: float = 0.0,+) -> bool:+ """Make the conversation ``session_id`` resumable from ``target_home``.++ ``homes`` are every seat directory of the same CLI; the newest copy among+ them (target included) is the conversation. Returns True when the target+ holds the newest copy afterwards — already did, or does now — and False+ when this kind cannot be carried, nothing holds the conversation, or the+ copy failed.+ """+ locate = _LAYOUTS.get(kind)+ if locate is None or not _safe_id(session_id):+ return False+ target_home = Path(target_home).expanduser()+ try:+ current = locate(target_home, session_id, captured_at)+ newest: _Located | None = None+ for home in homes:+ home = Path(home).expanduser()+ if _same_dir(home, target_home):+ continue+ found = locate(home, session_id, captured_at)+ if found is not None and (newest is None or found.mtime > newest.mtime):+ newest = found+ if newest is None:+ return current is not None+ if current is not None and current.mtime >= newest.mtime:+ return True+ for source, relative in newest.parts:+ _copy_part(source, target_home / relative)+ except OSError as exc:+ logger.warning(+ "Seat handoff: conversation {} could not be carried to {}: {}",+ session_id[:8],+ target_home,+ exc,+ )+ return False+ logger.info(+ "Seat handoff: carried conversation {} from {} to {}",+ session_id[:8],+ newest.home,+ target_home,+ )+ return True+++# ------------------------------------------------------------- limit stops+++def _ts(value: Any) -> float | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, int | float):+ return float(value) / 1000.0 if value > 1e12 else float(value)+ if isinstance(value, str) and value.strip():+ raw = value.strip()+ if raw.endswith(("Z", "z")):+ raw = raw[:-1] + "+00:00"+ try:+ parsed = datetime.fromisoformat(raw)+ except ValueError: # an unparseable time is treated as absent+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return parsed.timestamp()+ return None+++def _tail_rows(path: Path, limit: int = LIMIT_TAIL_BYTES) -> list[dict[str, Any]]:+ try:+ size = path.stat().st_size+ with path.open("rb") as handle:+ if size > limit:+ handle.seek(size - limit)+ handle.readline()+ raw_lines = handle.readlines()+ except OSError: # an unreadable transcript has no rows yet+ return []+ rows: list[dict[str, Any]] = []+ for raw in raw_lines:+ try:+ row = json.loads(raw)+ except (ValueError, UnicodeDecodeError): # a torn or partial line is skipped+ continue+ if isinstance(row, dict):+ rows.append(row)+ return rows+++def _claude_row(row: dict[str, Any]) -> str:+ """``limit`` | ``user`` | ``progress`` | "" for one Claude Code record."""+ if row.get("isSidechain") or row.get("isMeta"):+ return ""+ kind = row.get("type")+ if kind == "assistant":+ status = row.get("apiErrorStatus")+ if row.get("isApiErrorMessage") and (row.get("error") == "rate_limit" or status == 429):+ return "limit"+ return "progress"+ if kind == "user" and not row.get("queueTranscriptOnly"):+ message = row.get("message")+ content = message.get("content") if isinstance(message, dict) else None+ if (+ isinstance(content, list)+ and content+ and all(+ isinstance(block, dict) and block.get("type") == "tool_result" for block in content+ )+ ):+ return "progress"+ return "user"+ return ""+++def _codex_row(row: dict[str, Any]) -> str:+ payload = row.get("payload")+ if not isinstance(payload, dict):+ return ""+ kind, ptype = row.get("type"), payload.get("type")+ if kind == "event_msg":+ if ptype == "user_message":+ return "user"+ if ptype == "error":+ info = str(payload.get("codex_error_info") or "").lower()+ message = str(payload.get("message") or "").lower()+ if "usage_limit" in info or "usage limit" in message:+ return "limit"+ return ""+ if ptype == "token_count":+ limits = payload.get("rate_limits")+ if isinstance(limits, dict) and limits.get("rate_limit_reached_type"):+ return "limit"+ return ""+ if ptype in {"agent_message", "task_started"}:+ return "progress"+ return ""+++_ROW_READERS = {"claude_session": _claude_row, "codex_rollout": _codex_row}++#: The watch asks about every running pane every few seconds, and nearly every+#: time nothing changed. A transcript is re-read only when its size or+#: modification time moved; the located path is kept while it still exists.+#: Bounded by the number of panes, cleared wholesale past the cap.+_CACHE_CAP = 256+_LOCATED: dict[tuple[str, str, str], Path] = {}+_READ: dict[str, tuple[int, int, float | None]] = {}+++def _cached_anchor(kind: str, session_id: str, home: Path, captured_at: float) -> Path | None:+ key = (kind, session_id, os.path.normcase(str(home)))+ known = _LOCATED.get(key)+ if known is not None and known.is_file():+ return known+ found = _LAYOUTS[kind](home, session_id, captured_at)+ if found is None:+ _LOCATED.pop(key, None)+ return None+ if len(_LOCATED) >= _CACHE_CAP:+ _LOCATED.clear()+ _LOCATED[key] = found.anchor+ return found.anchor+++def _last_stop(kind: str, anchor: Path) -> float | None:+ """The unanswered limit stop at the end of ``anchor``, re-read only on change."""+ try:+ stat = anchor.stat()+ except OSError: # a vanished transcript has no pending stop+ return None+ key = os.path.normcase(str(anchor))+ cached = _READ.get(key)+ if cached is not None and cached[:2] == (stat.st_mtime_ns, stat.st_size):+ return cached[2]+ reader = _ROW_READERS[kind]+ stop: float | None = None+ for row in _tail_rows(anchor):+ verdict = reader(row)+ if verdict == "limit":+ stop = _ts(row.get("timestamp")) or stop+ elif verdict in ("user", "progress"):+ # A message from the user, or an agent that carried on after the+ # stop (a retry that went through): the stop is answered.+ stop = None+ if len(_READ) >= _CACHE_CAP:+ _READ.clear()+ _READ[key] = (stat.st_mtime_ns, stat.st_size, stop)+ return stop+++def can_detect_limit(kind: str) -> bool:+ """Whether a usage-limit stop is readable from this CLI's own transcript."""+ return kind in _ROW_READERS+++def limit_stop(+ kind: str,+ session_id: str,+ home: Path,+ *,+ captured_at: float = 0.0,+ after: float = 0.0,+ now: float | None = None,+) -> float | None:+ """When the conversation's LAST turn was cut off by a plan limit, or None.++ Read from the CLI's own protocol records, never from screen text: Claude+ Code files a synthetic assistant message flagged ``isApiErrorMessage``+ with ``error: "rate_limit"`` (HTTP 429), Codex an ``error`` event naming the+ usage limit or a ``token_count`` whose rate limits say one was reached.++ "Last turn" is the point: a limit hit an hour ago that the user already+ typed past is history, so a stop only counts when nothing the user sent+ and nothing the agent did came after it. ``after`` ignores stops at or+ before a moment the caller already handled, which is what keeps a carried+ transcript — whose tail still holds the stop that caused the carry — from+ triggering a second switch on the new seat.+ """+ if kind not in _ROW_READERS or kind not in _LAYOUTS or not _safe_id(session_id):+ return None+ try:+ anchor = _cached_anchor(kind, session_id, Path(home).expanduser(), captured_at)+ except OSError: # a vanished session has no resumable stop+ return None+ if anchor is None:+ return None+ stop = _last_stop(kind, anchor)+ moment = time.time() if now is None else now+ if stop is None or stop <= after or moment - stop > LIMIT_STALE_S:+ return None+ return stop+++__all__ = [+ "LIMIT_STALE_S",+ "can_carry",+ "can_detect_limit",+ "carry_conversation",+ "limit_stop",+]diff --git a/jarvis/agentic_ide/seat_switch.py b/jarvis/agentic_ide/seat_switch.pynew file mode 100644index 0000000000..a4f75dd4fd--- /dev/null+++ b/jarvis/agentic_ide/seat_switch.py@@ -0,0 +1,910 @@+"""Keep coding agents working when a subscription seat runs out.++A user holding several seats of one coding CLI (:mod:`jarvis.agent_accounts`)+holds them for one reason: when the first plan is spent, the work goes on on+the second. This module is what makes that happen without anybody watching.++**One switch moves everything.** :func:`switch_seat` makes a seat the active+one AND moves every pane of that CLI onto it. A pane that is idle moves at+once; a pane in the middle of a turn is marked and moves the moment the turn+ends, because ending its process would cut the step in flight off. Moving a+pane means ending its CLI and starting it again on the new seat with+``--resume`` — the conversation is carried along (:mod:`.seat_handoff`), so+the agent continues exactly where it was and only the plan it spends changes.+Whether a pane is idle is decided again under the pane's own lock, right+before its process ends, so a prompt that lands in between is never cut off.++**Two ways a seat counts as used up**, both read without spending anything:++* **The provider refused.** The CLI files a usage-limit stop in its own+ transcript (:func:`.seat_handoff.limit_stop`). The pane is moved to the next+ seat at once and told to continue, so the interrupted task carries on. This+ is the guarantee: whatever the usage numbers said, a refusal always moves+ the work. A stop that was answered is remembered on disk by conversation,+ so the carried transcript — which still ends in that stop — never triggers+ a second switch, not even after an app restart.+* **The plan is nearly spent.** The usage the Subscriptions panel shows+ (:mod:`jarvis.agent_usage`, a free status read) crosses the threshold — by+ default 97 %, three percent left. Idle panes move straight away, working+ ones when their turn ends, so most work never meets the refusal at all. A+ seat the user picked by hand is left to them until it actually refuses.++**The next seat** is the signed-in subscription of the same CLI with the most+budget left: never the same login under another name (two rows signed in as+one email share one plan), never an API-key login (nothing the user did not+start may bill a key), never one that ran out itself and has not reset, never+one already past the threshold. When there is none, nothing moves and the+status says so; once the refusing seat refills, its cut-off panes are told to+continue where they are.++Never on the boot path (AP-26): the watch starts with the first workspace and+costs a few small file reads per tick while panes run.+"""++from __future__ import annotations++import asyncio+import functools+import json+import os+import random+import threading+import time+from collections import deque+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, Any+from uuid import uuid4++from loguru import logger++if TYPE_CHECKING:+ from jarvis.agent_accounts import AgentAccount+ from jarvis.agent_usage import AccountUsage++ from .session import Registry, Session, Terminal++#: How often running panes are checked for a usage-limit stop. Local file+#: tails only (re-read only when they changed), so this can be short: the+#: sooner a refused pane moves, the less time the user's agents stand still.+WATCH_INTERVAL_S = 8.0++#: How often plan usage is read while panes run. The provider's numbers move+#: slowly and the panel shares the same cache (``agent_usage.USAGE_TTL_S``).+USAGE_INTERVAL_S = 90.0+USAGE_JITTER_S = 20.0++#: How long a seat that refused stays out of rotation when its reset time is+#: unknown. Past it, the seat is tried again — a fresh usage reading decides.+EXHAUSTED_FALLBACK_S = 3600.0++#: A pane somebody typed into this recently is left alone for now: restarting+#: its CLI would throw the half-written prompt away. The move waits like one+#: behind a running turn.+TYPING_GRACE_S = 60.0++#: Recent switches kept for the panel. A handful is all anyone reads.+MAX_EVENTS = 20++#: Answered limit stops remembered on disk, newest kept.+MAX_HANDLED = 500++#: What a pane that was cut off by a usage limit is told after the move. The+#: CLI has the whole conversation back; this only says why it stopped and that+#: it should carry on.+CONTINUE_PROMPT = (+ "Continue exactly where you stopped. The previous subscription reached its "+ "usage limit, so this session now runs on another subscription; nothing "+ "else changed."+)++#: The same, for a pane that waited on its own seat until that seat refilled.+RESUME_PROMPT = (+ "Continue exactly where you stopped. The usage limit that interrupted you has reset."+)+++@dataclass(frozen=True, slots=True)+class SwitchEvent:+ """One switch, as the panel reports it."""++ at: float+ platform: str+ reason: str # "manual" | "limit" | "threshold" | "no_seat" | "refilled"+ to_account: str | None+ to_label: str+ from_label: str+ moved: int = 0+ queued: int = 0++ def to_dict(self) -> dict[str, Any]:+ return {+ "at": self.at,+ "platform": self.platform,+ "reason": self.reason,+ "to_account": self.to_account,+ "to_label": self.to_label,+ "from_label": self.from_label,+ "moved": self.moved,+ "queued": self.queued,+ }+++@dataclass(slots=True)+class _State:+ #: account id -> epoch until which it is out of rotation. Written on the+ #: event loop only.+ exhausted: dict[str, float] = field(default_factory=dict)+ events: deque[SwitchEvent] = field(default_factory=lambda: deque(maxlen=MAX_EVENTS))+ task: asyncio.Task[None] | None = None+ lock: asyncio.Lock | None = None+ next_usage_at: float = 0.0+ #: (platform, leaving ids) of the last "no seat left" report, so a seat+ #: that stays empty is reported once rather than every tick.+ reported_empty: set[tuple[str, frozenset[str]]] = field(default_factory=set)+ #: (conversation id, stop) pairs whose seat was already taken out of+ #: rotation — a stop that waits for a seat must not extend that every tick.+ seen_stops: set[tuple[str, float]] = field(default_factory=set)+ #: platform -> the seat the user picked by hand; the threshold leaves it be.+ manual: dict[str, str] = field(default_factory=dict)+ #: Continue prompts in flight, held so the loop cannot drop them.+ nudges: set[asyncio.Task[None]] = field(default_factory=set)+++_STATE = _State()++# conversation id -> the limit stop (epoch) a switch already answered.+_HANDLED: dict[str, float] | None = None+_HANDLED_LOCK = threading.Lock()+++def _lock() -> asyncio.Lock:+ if _STATE.lock is None:+ _STATE.lock = asyncio.Lock()+ return _STATE.lock+++def reset() -> None:+ """Forget everything — for tests."""+ global _HANDLED+ stop()+ _STATE.exhausted.clear()+ _STATE.events.clear()+ _STATE.lock = None+ _STATE.next_usage_at = 0.0+ _STATE.reported_empty.clear()+ _STATE.seen_stops.clear()+ _STATE.manual.clear()+ _STATE.nudges.clear()+ with _HANDLED_LOCK:+ _HANDLED = None+++# --------------------------------------------------------- answered stops+++def _handled_path() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "agentic_ide" / "seat_switch_handled.json"+++def _handled() -> dict[str, float]:+ """Answered stops by conversation id. Unreadable reads as none answered."""+ global _HANDLED+ with _HANDLED_LOCK:+ if _HANDLED is None:+ try:+ raw = json.loads(_handled_path().read_text(encoding="utf-8"))+ except FileNotFoundError: # nothing handled yet on a first run+ raw = {}+ except (OSError, ValueError) as exc:+ logger.warning(+ "Seat switch: answered-stop record unreadable ({}) — starting empty", exc+ )+ raw = {}+ _HANDLED = {+ str(key): float(value)+ for key, value in (raw.items() if isinstance(raw, dict) else ())+ if isinstance(value, int | float)+ }+ return _HANDLED+++def handled_stop(session_id: str) -> float:+ """The stop already answered for this conversation, or 0."""+ return _handled().get(session_id, 0.0)+++def _remember_handled(session_id: str, stop: float) -> None:+ """Record an answered stop, atomically. Filesystem: off the loop."""+ handled = _handled()+ with _HANDLED_LOCK:+ handled[session_id] = max(stop, handled.get(session_id, 0.0))+ if len(handled) > MAX_HANDLED:+ for key, _value in sorted(handled.items(), key=lambda item: item[1])[+ : len(handled) - MAX_HANDLED+ ]:+ handled.pop(key, None)+ payload = json.dumps(handled, indent=1)+ path = _handled_path()+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(f"{path.name}.{uuid4().hex[:8]}.tmp")+ tmp.write_text(payload, encoding="utf-8")+ os.replace(tmp, path)+ except OSError as exc:+ # The in-memory record still guards this process; only a restart+ # inside the stale window could see the stop again.+ logger.warning("Seat switch: answered stop not saved: {}", exc)+++# ---------------------------------------------------------------- readings+++def _now() -> float:+ return time.time()+++def _window_resets(window: Any) -> float | None:+ from datetime import datetime++ raw = getattr(window, "resets_at", None)+ if not raw:+ return None+ try:+ return datetime.fromisoformat(str(raw).replace("Z", "+00:00")).timestamp()+ except ValueError: # an unparseable reset time is treated as unknown+ return None+++def spent_percent(+ usage: AccountUsage | None, *, now: float | None = None, scoped: bool = True+) -> float | None:+ """The tightest limit's spent share, or None when nothing was measured.++ A window whose reset time has already passed counts as empty: a cached+ reading from before the reset still says 100 %, and trusting it would+ keep a refilled seat out of rotation.++ ``scoped=False`` ignores budgets that bind only one model+ (``weekly_scoped``). Those must not move ALL work off a seat ahead of+ time — agents on other models still have the whole plan — while a turn+ that does run into one is refused and moved on by the limit-stop path.+ """+ if usage is None or usage.status != "ok" or not usage.windows:+ return None+ moment = _now() if now is None else now+ worst = 0.0+ for window in usage.windows:+ if not scoped and window.kind == "weekly_scoped":+ continue+ resets = _window_resets(window)+ if resets is not None and resets <= moment:+ continue+ worst = max(worst, float(window.percent))+ return worst+++def _refill_at(+ usage: AccountUsage | None, at_percent: float, *, scoped: bool = True+) -> float | None:+ """When the windows at or past ``at_percent`` refill, the latest of them."""+ if usage is None or usage.status != "ok":+ return None+ moment = _now()+ latest: float | None = None+ for window in usage.windows:+ if not scoped and window.kind == "weekly_scoped":+ continue+ resets = _window_resets(window)+ if resets is None or resets <= moment or float(window.percent) < at_percent:+ continue+ latest = resets if latest is None else max(latest, resets)+ return latest+++def is_exhausted(account_id: str | None, *, now: float | None = None) -> bool:+ """Whether a seat is out of rotation after refusing or crossing the threshold."""+ if not account_id:+ return False+ until = _STATE.exhausted.get(account_id)+ return until is not None and until > (_now() if now is None else now)+++def _identity(snapshot: Any) -> str:+ email = (getattr(snapshot, "email", None) or "").strip().lower()+ return email or f"id:{snapshot.account.id}"+++def _same_login_ids(platform: str, account_ids: set[str]) -> set[str]:+ """``account_ids`` plus every seat signed in as one of the same logins.++ Filesystem reads: callers run it off the event loop.+ """+ from jarvis import agent_accounts++ snapshots = agent_accounts.snapshots(platform)+ identities = {_identity(s) for s in snapshots if s.account.id in account_ids}+ return {s.account.id for s in snapshots if _identity(s) in identities} | set(account_ids)+++def _set_exhausted(account_ids: set[str], until: float | None) -> None:+ """Take these seats out of rotation. On the event loop."""+ deadline = until if until and until > _now() else _now() + EXHAUSTED_FALLBACK_S+ for account_id in account_ids:+ _STATE.exhausted[account_id] = max(deadline, _STATE.exhausted.get(account_id, 0.0))+++def choose_seat(+ platform: str,+ leaving: set[str],+ usage: dict[str, AccountUsage],+ at_percent: float,+ *,+ prefer: str | None = None,+ scoped: bool = True,+) -> AgentAccount | None:+ """The seat with the most budget left that is a different subscription.++ ``prefer`` (the active seat) wins whenever it is eligible at all: work+ leaving a pinned seat goes where everything else already runs, rather than+ pulling the whole CLI onto a third seat.++ Filesystem reads: callers run it off the event loop.+ """+ from jarvis import agent_accounts++ snapshots = agent_accounts.snapshots(platform)+ leaving_logins = {_identity(s) for s in snapshots if s.account.id in leaving}+ ranked: list[tuple[int, float, int, AgentAccount]] = []+ for order, snapshot in enumerate(snapshots):+ account = snapshot.account+ if account.id in leaving or _identity(snapshot) in leaving_logins:+ continue+ # A subscription only: an API-key login bills per token, and nothing+ # the user did not start may spend a key (AGENTS.md §2).+ if not snapshot.connected or snapshot.mode != "subscription":+ continue+ if is_exhausted(account.id):+ continue+ spent = spent_percent(usage.get(account.id), scoped=scoped)+ if spent is not None and spent >= at_percent:+ continue+ # Measured seats first, least spent first; an unmeasured seat is a+ # last resort, never preferred over one known to have budget.+ ranked.append((0 if spent is not None else 1, spent or 0.0, order, account))+ if not ranked:+ return None+ for item in ranked:+ if item[3].id == prefer:+ return item[3]+ ranked.sort(key=lambda item: (item[0], item[1], item[2]))+ return ranked[0][3]+++def preferred_seat(platform: str, account_id: str | None) -> str | None:+ """The seat a NEW turn of ``platform`` should run on instead of ``account_id``.++ For callers outside the panes (chat threads, agents): when the seat they+ would use is out of rotation and auto switch is on, the active seat —+ which the watch has already moved to the next subscription — is the+ answer, but only when it is a signed-in SUBSCRIPTION: a turn is never+ rerouted onto a login that bills per token. ``None`` means "keep yours".+ No network, no spawn; the file reads happen only for a spent seat.+ """+ from jarvis import agent_accounts++ if not account_id or not is_exhausted(account_id):+ return None+ if not agent_accounts.auto_switch().enabled:+ return None+ active = agent_accounts.active_account(platform)+ if active.id == account_id or is_exhausted(active.id):+ return None+ snapshot = agent_accounts.describe(active)+ if not snapshot.connected or snapshot.mode != "subscription":+ return None+ return active.id+++# --------------------------------------------------------------- the moves+++def _local_panes(registry: Registry, platform: str) -> list[tuple[Session, Terminal]]:+ from .session import has_accounts++ return [+ (session, term)+ for session in registry.sessions+ for term in session.terminals+ if term.agent == platform and not term.computer_id and has_accounts(term.agent)+ ]+++def _record(event: SwitchEvent) -> None:+ _STATE.events.append(event)+ logger.info(+ "Seat switch ({}): {} {} -> {} — {} moved, {} after their turn",+ event.reason,+ event.platform,+ event.from_label or "-",+ event.to_label or "-",+ event.moved,+ event.queued,+ )+++async def _busy(registry: Registry, term: Terminal) -> bool:+ """Is the pane working, asking, starting, or being typed into?"""+ if term.status != "live" or not term.pty_id:+ return False+ typed_at = getattr(term, "last_input_at", None)+ if typed_at and _now() - typed_at < TYPING_GRACE_S:+ return True+ try:+ state = await registry.turn_in_progress(term)+ except Exception as exc: # noqa: BLE001 - unknown counts as busy: never cut work off+ logger.debug("Seat switch: could not read {}'s turn: {}", term.name, exc)+ return True+ return state in ("working", "starting", "asking")+++def _idle_check(registry: Registry) -> Callable[[Terminal], Awaitable[bool]]:+ async def idle(term: Terminal) -> bool:+ return not await _busy(registry, term)++ return idle+++def _nudge(registry: Registry, session: Session, term: Terminal, text: str) -> None:+ """Tell a pane that was cut off by a limit to carry on, once it is ready."""++ async def send() -> None:+ try:+ await registry.send_prompt(+ "pane:" + term.history_id, text, workspace_id=session.id, require_idle=True+ )+ except Exception as exc: # noqa: BLE001 - the pane keeps its seat either way+ logger.info("Seat switch: {} was not told to continue: {}", term.name, exc)++ task = asyncio.ensure_future(send())+ _STATE.nudges.add(task)+ task.add_done_callback(_STATE.nudges.discard)+++async def _move_panes(+ registry: Registry,+ platform: str,+ target: str,+ *,+ only_from: set[str] | None,+ skip: set[str],+ force: set[int],+) -> dict[int, tuple[Session, Terminal, str]]:+ """Move panes of ``platform`` onto ``target``; busy ones after their turn.++ ``only_from`` limits the move to panes on those seats; ``skip`` never+ moves panes on those seats (the target's own login). ``force`` holds panes+ (by ``id``) stopped by a limit — their turn is over even when the+ transcript has not recorded its end yet. Every other pane is moved only+ if it is still idle under its own lock; otherwise it waits+ (``pending_account``) and the watch moves it when its turn ends.++ Returns each pane's outcome: moved, repointed, deferred, unchanged, failed.+ """+ idle = _idle_check(registry)+ chosen: list[tuple[Session, Terminal]] = []+ for session, term in _local_panes(registry, platform):+ if term.account == target or term.account in skip:+ term.pending_account = None+ continue+ if only_from is not None and term.account not in only_from:+ continue+ chosen.append((session, term))++ async def one(term: Terminal) -> str:+ try:+ return await registry.move_to_seat(+ term, target, idle=None if id(term) in force else idle+ )+ except Exception as exc: # noqa: BLE001 - one pane must not stop the others+ logger.warning("Seat switch: {} could not be moved: {}", term.name, exc)+ return "failed"++ # Together: each pane restarts under its own lock, and a grid of agents+ # standing still one after another is exactly what a switch must avoid.+ outcomes = await asyncio.gather(*(one(term) for _session, term in chosen))+ return {+ id(term): (session, term, outcome)+ for (session, term), outcome in zip(chosen, outcomes, strict=True)+ }+++def _count(outcomes: dict[int, tuple[Session, Terminal, str]]) -> tuple[int, int]:+ moved = sum(1 for *_pair, outcome in outcomes.values() if outcome in ("moved", "repointed"))+ queued = sum(1 for *_pair, outcome in outcomes.values() if outcome == "deferred")+ return moved, queued+++async def _switch(+ registry: Registry,+ platform: str,+ account_id: str,+ *,+ reason: str,+ only_from: set[str] | None = None,+ stopped: list[tuple[Session, Terminal]] | None = None,+) -> tuple[SwitchEvent, dict[int, tuple[Session, Terminal, str]]]:+ """:func:`switch_seat`, also returning every pane's outcome. Holds the lock."""+ from jarvis import agent_accounts++ account = await asyncio.to_thread(agent_accounts.resolve, account_id)+ if account is None or account.platform != platform:+ raise agent_accounts.AccountError("That account no longer exists.")+ previous = await asyncio.to_thread(agent_accounts.active_account, platform)+ await asyncio.to_thread(agent_accounts.set_active, platform, account.id)+ same_login = await asyncio.to_thread(_same_login_ids, platform, {account.id})+ if reason == "manual":+ # The user knows something the readings do not (a reset, an+ # upgrade): their pick is back in rotation, and the threshold leaves+ # it to them until the provider actually refuses it.+ for seat in same_login:+ _STATE.exhausted.pop(seat, None)+ _STATE.manual[platform] = account.id+ elif _STATE.manual.get(platform) != account.id:+ _STATE.manual.pop(platform, None)+ forced = {id(term) for _session, term in (stopped or [])}+ outcomes = await _move_panes(+ registry,+ platform,+ account.id,+ only_from=only_from,+ skip=same_login - {account.id},+ force=forced,+ )+ moved, queued = _count(outcomes)+ event = SwitchEvent(+ at=_now(),+ platform=platform,+ reason=reason,+ to_account=account.id,+ to_label=account.label,+ from_label=previous.label if previous.id != account.id else "",+ moved=moved,+ queued=queued,+ )+ _record(event)+ for session, term, outcome in outcomes.values():+ if id(term) in forced and outcome == "moved":+ _nudge(registry, session, term, CONTINUE_PROMPT)+ return event, outcomes+++async def switch_seat(+ registry: Registry,+ platform: str,+ account_id: str,+ *,+ reason: str = "manual",+ only_from: set[str] | None = None,+) -> SwitchEvent:+ """Make ``account_id`` the active seat of ``platform`` and move the work.++ Every pane of that CLI follows — except panes already on the same login+ as the target, which would restart for nothing. ``only_from`` restricts+ the move to panes on the seats being left (an automatic switch leaves+ panes on other healthy seats alone).+ """+ async with _lock():+ event, _outcomes = await _switch(+ registry, platform, account_id, reason=reason, only_from=only_from+ )+ return event+++def _report_empty(platform: str, leaving: set[str], labels: str, reason: str) -> None:+ key = (platform, frozenset(leaving))+ if key in _STATE.reported_empty:+ return+ _STATE.reported_empty.add(key)+ _record(+ SwitchEvent(+ at=_now(),+ platform=platform,+ reason="no_seat",+ to_account=None,+ to_label="",+ from_label=labels,+ )+ )+ logger.warning(+ "Seat switch ({}): {} has no other subscription with budget left — work stays put",+ reason,+ platform,+ )+++# ------------------------------------------------------------------- watch+++async def _apply_pending(registry: Registry) -> None:+ """Carry out moves that waited for a turn to end."""+ idle = _idle_check(registry)+ for session in list(registry.sessions):+ for term in list(session.terminals):+ if not term.pending_account:+ continue+ async with _lock():+ # Re-read under the lock: a switch may have moved the pane or+ # changed its target while this tick was waiting.+ target = term.pending_account+ if not target or term.account == target:+ term.pending_account = None+ continue+ if await _busy(registry, term):+ continue+ try:+ await registry.move_to_seat(term, target, idle=idle)+ except Exception as exc: # noqa: BLE001 - one pane must not stop the watch+ logger.warning("Seat switch: {} could not be moved: {}", term.name, exc)+ term.pending_account = None+++def _limit_stops(registry: Registry) -> list[tuple[Session, Terminal, float]]:+ """Panes whose last turn a usage limit cut off. Filesystem: off the loop."""+ from . import seat_handoff+ from .session import account_home, has_accounts++ found: list[tuple[Session, Terminal, float]] = []+ for session in list(registry.sessions):+ for term in list(session.terminals):+ handle = term.resume+ if (+ term.computer_id+ or term.status != "live"+ or handle is None+ or not has_accounts(term.agent)+ or not seat_handoff.can_detect_limit(handle.kind)+ ):+ continue+ home = account_home(term.agent, term.account)+ if home is None:+ continue+ stop = seat_handoff.limit_stop(+ handle.kind,+ handle.id,+ home,+ captured_at=handle.captured_at,+ after=max(term.limit_handled_at, handled_stop(handle.id)),+ )+ if stop is not None:+ found.append((session, term, stop))+ return found+++async def _answered(term: Terminal, stop: float) -> None:+ term.limit_handled_at = max(term.limit_handled_at, stop)+ if term.resume is not None:+ await asyncio.to_thread(_remember_handled, term.resume.id, stop)+++async def _handle_limit_stops(registry: Registry, at_percent: float) -> None:+ from jarvis import agent_accounts++ stops = await asyncio.to_thread(_limit_stops, registry)+ by_platform: dict[str, list[tuple[Session, Terminal, float]]] = {}+ for item in stops:+ by_platform.setdefault(item[1].agent, []).append(item)+ for platform, items in by_platform.items():+ leaving = {term.account for _s, term, _at in items if term.account}+ usage = await asyncio.to_thread(_cached_usage, platform)+ leaving_all = await asyncio.to_thread(_same_login_ids, platform, leaving)+ fresh = [+ (term, at)+ for _s, term, at in items+ if term.resume is not None and (term.resume.id, at) not in _STATE.seen_stops+ ]+ if fresh:+ # Out of rotation once per stop, until its refill: a stop that+ # waits for a seat must not push that refill back every tick.+ until = max((_refill_at(usage.get(a), 99.0) or 0.0 for a in leaving), default=0.0)+ _set_exhausted(leaving_all, until or None)+ _STATE.seen_stops.update((term.resume.id, at) for term, at in fresh if term.resume)+ active = await asyncio.to_thread(agent_accounts.active_account, platform)+ seat = await asyncio.to_thread(+ functools.partial(choose_seat, platform, leaving, usage, at_percent, prefer=active.id)+ )+ if seat is None:+ refilled = not any(is_exhausted(a) for a in leaving_all) and all(+ (percent := spent_percent(usage.get(a))) is not None and percent < at_percent+ for a in leaving+ )+ if refilled:+ # Nowhere else to go, but the seat itself measurably refilled:+ # carry on where it is. Never on a guess — a "continue" into a+ # seat that is still spent is refused all over again.+ for session, term, at in items:+ _nudge(registry, session, term, RESUME_PROMPT)+ await _answered(term, at)+ labels = await asyncio.to_thread(+ lambda ids=frozenset(leaving): ", ".join(sorted(_label(a) for a in ids))+ )+ _record(+ SwitchEvent(+ at=_now(),+ platform=platform,+ reason="refilled",+ to_account=None,+ to_label=labels,+ from_label=labels,+ moved=len(items),+ )+ )+ continue+ labels = await asyncio.to_thread(+ lambda ids=frozenset(leaving): ", ".join(sorted(_label(a) for a in ids))+ )+ _report_empty(platform, leaving, labels, "limit")+ continue+ _STATE.reported_empty.discard((platform, frozenset(leaving)))+ async with _lock():+ _event, outcomes = await _switch(+ registry,+ platform,+ seat.id,+ reason="limit",+ only_from=leaving_all,+ stopped=[(session, term) for session, term, _at in items],+ )+ for _session, term, at in items:+ outcome = outcomes.get(id(term), (None, None, "unchanged"))[2]+ # Answered only once the pane really is on a seat with budget; a+ # failed move is tried again on the next tick.+ if outcome in ("moved", "repointed") or term.account == seat.id:+ await _answered(term, at)+++def _label(account_id: str | None) -> str:+ from .session import account_label++ return account_label(account_id) or (account_id or "")+++def _cached_usage(platform: str) -> dict[str, AccountUsage]:+ """This platform's usage from the shared cache, reading only what is stale."""+ from jarvis import agent_accounts, agent_usage++ if not agent_usage.supports_usage(platform):+ return {}+ return agent_usage.collect(agent_accounts.list_accounts(platform)) # type: ignore[arg-type]+++async def _check_thresholds(registry: Registry, at_percent: float) -> None:+ """Move work off seats whose plan is nearly spent."""+ from jarvis import agent_accounts++ platforms: dict[str, set[str]] = {}+ for platform in agent_accounts.platforms():+ for _session, term in _local_panes(registry, platform):+ if term.status == "live" and term.account:+ platforms.setdefault(platform, set()).add(term.account)+ for platform, in_use in platforms.items():+ usage = await asyncio.to_thread(_cached_usage, platform)+ if not usage:+ continue+ active = await asyncio.to_thread(agent_accounts.active_account, platform)+ manual = _STATE.manual.get(platform)+ watched = in_use | {active.id}+ spent = {+ account_id+ for account_id in watched+ if account_id != manual+ and (percent := spent_percent(usage.get(account_id), scoped=False)) is not None+ and percent >= at_percent+ }+ if not spent:+ continue+ leaving_all = await asyncio.to_thread(_same_login_ids, platform, spent)+ until = max(+ (_refill_at(usage.get(a), at_percent, scoped=False) or 0.0 for a in spent),+ default=0.0,+ )+ _set_exhausted(leaving_all, until or None)+ seat = await asyncio.to_thread(+ functools.partial(+ choose_seat, platform, spent, usage, at_percent, prefer=active.id, scoped=False+ )+ )+ if seat is None:+ labels = await asyncio.to_thread(+ lambda ids=frozenset(spent): ", ".join(sorted(_label(a) for a in ids))+ )+ _report_empty(platform, spent, labels, "threshold")+ continue+ _STATE.reported_empty.discard((platform, frozenset(spent)))+ async with _lock():+ await _switch(registry, platform, seat.id, reason="threshold", only_from=leaving_all)+++async def _tick(registry: Registry) -> None:+ from jarvis import agent_accounts++ await _apply_pending(registry)+ choice = await asyncio.to_thread(agent_accounts.auto_switch)+ if not choice.enabled:+ return+ await _handle_limit_stops(registry, choice.at_percent)+ if _now() >= _STATE.next_usage_at:+ _STATE.next_usage_at = _now() + USAGE_INTERVAL_S + random.uniform(0, USAGE_JITTER_S) # noqa: S311+ await _check_thresholds(registry, choice.at_percent)+++async def _run(registry: Registry) -> None:+ """Watch until the last workspace closes; the next one starts it again."""+ try:+ while True:+ await asyncio.sleep(WATCH_INTERVAL_S)+ if not registry.sessions:+ return+ try:+ await _tick(registry)+ except Exception as exc: # noqa: BLE001 - one bad tick must not end the watch+ logger.warning("Seat switch: watch tick failed: {}", exc)+ except asyncio.CancelledError: # pragma: no cover - shutdown+ raise+ finally:+ _STATE.task = None+++def start(registry: Registry) -> None:+ """Make sure the watch runs for ``registry``. Idempotent."""+ if _STATE.task is not None and not _STATE.task.done():+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError: # no loop: called outside the server, nothing to schedule+ return+ _STATE.task = loop.create_task(_run(registry), name="agentic-ide-seat-switch")+++def stop() -> None:+ task = _STATE.task+ _STATE.task = None+ if task is not None and not task.done():+ task.cancel()+++def status() -> dict[str, Any]:+ """What the panel shows: the setting, seats out of rotation, recent switches."""+ from jarvis import agent_accounts++ moment = _now()+ choice = agent_accounts.auto_switch()+ return {+ **choice.to_dict(),+ "watching": _STATE.task is not None and not _STATE.task.done(),+ "exhausted": [+ {"account_id": account_id, "until": until}+ for account_id, until in sorted(_STATE.exhausted.items())+ if until > moment+ ],+ "events": [event.to_dict() for event in reversed(_STATE.events)],+ }+++__all__ = [+ "CONTINUE_PROMPT",+ "SwitchEvent",+ "choose_seat",+ "handled_stop",+ "is_exhausted",+ "preferred_seat",+ "reset",+ "spent_percent",+ "start",+ "status",+ "stop",+ "switch_seat",+]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 8544ed4ec7..47d2e97623 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -848,6 +848,43 @@ def account_home(agent: str, account_id: str | None) -> Path | None:return agent_accounts.config_dir_for(agent, account_id) # type: ignore[arg-type]+def seat_homes(agent: str) -> list[Path]:+ """Every config dir a conversation of ``agent`` may live in, one per seat."""+ if not has_accounts(agent):+ return []+ from jarvis import agent_accounts++ return [account.config_dir for account in agent_accounts.list_accounts(agent)] # type: ignore[arg-type]+++def _carry_to_seat(term: Terminal) -> bool:+ """Make the pane's conversation resumable from the seat it runs on now.++ Cheap for the common case: a pane that was never moved and whose seat+ already holds its conversation costs one lookup. The cross-seat search+ runs only after a move, or when the pane's own seat lacks the+ conversation (a thread or an earlier switch ran it elsewhere). Filesystem+ work: callers run it off the event loop.+ """+ from . import seat_handoff++ handle = term.resume+ home = account_home(term.agent, term.account)+ if handle is None or home is None or not seat_handoff.can_carry(handle.kind):+ return False+ if not term.seat_carry and has_conversation(term.agent, handle, home):+ return True+ carried = seat_handoff.carry_conversation(+ handle.kind,+ handle.id,+ home,+ seat_homes(term.agent),+ captured_at=handle.captured_at,+ )+ term.seat_carry = False+ return carried++def remote_agent_argv(agent: str) -> tuple[str, ...] | None:"""argv for ``agent`` on a connected computer (a POSIX server).@@ -1016,6 +1053,19 @@ class Terminal:# the 2026-08-12 report: "I changed my subscriptions twice and it doesn't# change", with every split resurrecting the seat the user had just left.account_pinned: bool = False+ # A seat switch that waits for this pane's turn to end (see+ # `seat_switch`): moving a working agent would cut its step off, so the+ # move is recorded here and carried out the moment the pane is idle.+ pending_account: str | None = None+ # Set by a seat move: the next start must look for the NEWEST copy of the+ # conversation across every seat of this CLI (`seat_handoff`), because+ # the seat it now runs on may hold none, or an older one from before an+ # earlier switch.+ seat_carry: bool = False+ # The usage-limit stop (epoch seconds) a seat switch already answered. The+ # carried transcript still ends in that stop; without this the new seat+ # would read it as its own limit and switch again.+ limit_handled_at: float = 0.0# What this pane was OPENED on: the model, the effort level and the# permission stance picked for it before it started# (:mod:`jarvis.workspace.launch_picks`). Empty means "whatever the CLI@@ -3074,6 +3124,12 @@ class Registry:notifications.start(self)except Exception as exc: # noqa: BLE001 - the bell is additivelogger.warning("Agentic IDE: pane notifications not started: {}", exc)+ try:+ from . import seat_switch++ seat_switch.start(self)+ except Exception as exc: # noqa: BLE001 - switching seats is additive+ logger.warning("Agentic IDE: seat watch not started: {}", exc)await self._persist()return session@@ -4247,6 +4303,11 @@ class Registry:await asyncio.to_thread(self._sync_hooked_session, term)home = account_home(term.agent, term.account)continuing = resume_argv(term.agent, term.resume)+ if continuing is not None and not term.computer_id and home is not None:+ # The conversation may live on another seat of this CLI: the pane+ # was just moved, or a thread ran it there. Bring the newest copy+ # here before asking whether there is one (`seat_handoff`).+ await asyncio.to_thread(_carry_to_seat, term)# A remote pane's history lives on that computer; its handle was# carried there with it (``remote.push_conversation``), so trust it.if (@@ -6086,6 +6147,84 @@ class Registry:except SessionError as exc:logger.warning("Agentic IDE: {} did not start after its move: {}", term.name, exc)+ async def move_to_seat(+ self,+ term: Terminal,+ account_id: str,+ *,+ idle: Callable[[Terminal], Awaitable[bool]] | None = None,+ ) -> str:+ """Put one pane on another subscription seat of its CLI.++ The same three steps a move to another computer takes: end the+ process, re-point the pane, start it again on its own conversation.+ The conversation follows the pane (``_carry_to_seat`` in the start+ path copies it into the new seat), so the agent continues exactly+ where it was; only the plan it spends changes.++ Returns ``moved`` (a running agent was restarted on the new seat),+ ``repointed`` (a stopped pane will start there next time),+ ``deferred`` (``idle`` said the agent is busy: the move is recorded in+ ``pending_account`` for when its turn ends) or ``unchanged``. Never+ moves a pane on a connected computer: its CLI uses that server's own+ login.++ A working agent must not be moved — ending its process cuts the step+ in flight off. ``idle`` is asked UNDER the pane's lock, right before+ the process ends, so a prompt that arrived after the caller last+ looked is never cut off; without it the caller vouches that the turn+ is over (a pane stopped by a usage limit).+ """+ session = self._owner_of(term)+ if session is None or term.computer_id or not has_accounts(term.agent):+ return "unchanged"+ async with term.attach_lock:+ if term.account == account_id:+ term.pending_account = None+ return "unchanged"+ live = term.status == "live" and bool(term.pty_id)+ if live and idle is not None and not await idle(term):+ term.pending_account = account_id+ return "deferred"+ if live:+ if reports_session_starts(term.agent):+ await asyncio.to_thread(self._sync_hooked_session, term)+ elif term.resume is None and term.started_at and can_resume(term.agent):+ # A CLI whose id is discovered afterwards may not have been+ # looked up yet; the move must not cost its conversation.+ taken = {+ other.resume.id for other in session.terminals if other.resume is not None+ }+ found = await asyncio.to_thread(+ discover,+ term.agent,+ term.cwd(session.folder),+ term.started_at,+ taken,+ account_home(term.agent, term.account),+ )+ if found is not None:+ term.resume = found+ await self._stop_for_move(term, self._pool(term))+ previous = term.account+ term.account = account_id+ # Following a switch is not a deliberate pick of this seat: the+ # next switch moves the pane again, and its splits follow too.+ term.account_pinned = False+ term.pending_account = None+ term.seat_carry = True+ if live:+ await self._restart_in_place(session, term)+ logger.info(+ "Agentic IDE: {} moved from seat {} to {} ({})",+ term.name,+ account_label(previous) or previous,+ account_label(account_id) or account_id,+ "its own conversation" if term.resumed else "a fresh conversation",+ )+ await self._persist()+ return "moved" if live else "repointed"+async def fork_terminal(self,wanted: str,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 4762c32c64..b20a9910aa 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -4780,13 +4780,14 @@ class BrainManager:self._dead_provider_models = {k for k in self._dead_provider_models if k[0] != provider}- keys_to_drop = [k for k in self._brain_cache if k[0] == provider]+ keys_to_drop = [k for k in self._brain_cache+ if k[0] == provider or str(k[0]).startswith(provider + "@")]for k in keys_to_drop:self._brain_cache.pop(k, None)self._rate_tracker.clear(provider)if was_dead or keys_to_drop:log.info(- "Provider '%s' reaktiviert (dead=%s, brain_cache_dropped=%d)",+ "Provider '%s' reactivated (dead=%s, brain_cache_dropped=%d)",provider, was_dead, len(keys_to_drop),)@@ -10618,31 +10619,11 @@ class BrainManager:"""The chain for a caller-picked turn: exactly the pick, no stand-in.A person who chose a model in the chat gets that model or an honest- error — never a silent cross-provider fallback (the "wrong model used,- shown right" defect, anti-drift mandate 2026-06-29). The one thing kept- from the normal chain is the intelligent-router lead: when the pick- cannot emit tool_calls at all, a tool-capable provider leads the turn- and falls through to the pick for the answer, exactly as for a- tool-incapable voice brain (``_router_lead_key``).+ error — never a silent cross-provider fallback. A tool-incapable pick+ does not authorize another provider to lead or bill this turn."""pick: tuple[str, str | None] = (override.provider, override.model)- chain: list[tuple[str, str | None]] = [pick]- intelligent = bool(getattr(self._config.brain.routing, "intelligent_router", True))- if (- intelligent- and getattr(self, "_turn_substantive", False)- and not self._brain_can_call_tools(override.provider, override.model)- ):- helper = self._first_tool_capable_provider(level, exclude=override.provider)- if helper is not None:- log.info(- "Intelligent router: picked %s cannot call tools — %s leads this "- "turn and picks the tool (falls through to %s if none).",- override.provider, helper[0], override.provider,- )- self._router_lead_key = helper- chain.insert(0, helper)- return chain+ return [pick]def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:"""Returns a prioritised list of (provider, model) attempts."""diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex 03d92a300e..40471a1575 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -894,6 +894,8 @@ def parse_models_response(provider: str, payload: dict) -> list[ModelInfo]:"""out: list[ModelInfo] = []if provider == "ollama":+ from jarvis.brain.ollama_inventory import is_hidden_alias+# Native /api/tags: {"models": [{"name": "qwen3.5:9b", ...}, ...]} —# the installed-model list of the user's own server. DOWNLOADED models# only: ``:cloud`` entries are ollama.com-proxied references, not@@ -901,7 +903,7 @@ def parse_models_response(provider: str, payload: dict) -> list[ModelInfo]:# the machine (maintainer report 2026-07-25).for m in payload.get("models", []) or []:raw = (m.get("name") or "").strip()- if not raw or raw.endswith(":cloud") or m.get("remote"):+ if not raw or raw.endswith(":cloud") or m.get("remote") or is_hidden_alias(raw):continueout.append(ModelInfo(id=raw, label=raw))return out@@ -1830,6 +1832,13 @@ class ModelCatalog:aliases = {model, f"{model}:latest"} if provider == "ollama" else {model}return next((item for item in entry[1] if item.id in aliases), None)+ async def invalidate(self, provider: str) -> None:+ """Forget a previous endpoint's models and failed-fetch cooldown."""+ async with self._lock:+ self._cache.pop(provider, None)+ self._fetch_failed_at.pop(provider, None)+ await asyncio.to_thread(self._save_cache)+async def list_models(self, provider: str, *, force_refresh: bool = False) -> CatalogResult:"""Return the catalog for ``provider`` with an honest ``source`` flag.diff --git a/jarvis/computers/github_access.py b/jarvis/computers/github_access.pynew file mode 100644index 0000000000..98b8991fcc--- /dev/null+++ b/jarvis/computers/github_access.py@@ -0,0 +1,131 @@+"""Share this PC's GitHub login with the coding agents on one computer.++Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+GitHubRoutingSettings.tsx: per-machine GitHub sharing with the trust warning+next to the switch), MIT License, Copyright (c) 2026 T3 Tools Inc. Full text:+third_party/t3code/LICENSE.++An agent working in tmux on a server has to clone and push without this PC+being on. On an explicit click, :func:`share` writes this PC's GitHub token+(the app's GitHub connection, else the GitHub CLI's login) to+:data:`remote_os.GITHUB_ENV_FILE` on the server — readable by that login+only, sourced by every agent launcher — and points git's credential helper+for ``https://github.com`` at it, so ``git push`` and ``gh`` both work there.+The token itself never enters ``~/.gitconfig``, a command line or a log.++The token carries the user's whole GitHub access; the UI says so beside the+switch. :func:`unshare` deletes the file and the helper again.+"""++from __future__ import annotations++import logging+import shlex+import time++from jarvis.computers import remote_os+from jarvis.computers.models import Computer+from jarvis.computers.service import ComputerError, get_service+from jarvis.computers.ssh import SshError++log = logging.getLogger(__name__)++_HELPER_KEY = "credential.https://github.com.helper"+#: Reads the token from the environment the launcher set; holds no secret.+HELPER = (+ '!f() { test "$1" = get && echo username=x-access-token && echo "password=${GH_TOKEN}"; }; f'+)+++def _local_token() -> tuple[str, str]:+ from jarvis.agentic_ide import github_link++ found = github_link.credential()+ if found is None:+ raise ComputerError(+ "GitHub is not connected on this PC. Connect it under Plugins, GitHub, or log in "+ "with the GitHub CLI (gh auth login), then share it again.",+ status=409,+ kind="github_missing",+ )+ return found.token, found.source+++def env_file_body(token: str) -> str:+ quoted = shlex.quote(token)+ return (+ "# Written by Personal Jarvis: the GitHub login this PC shared with the agents here.\n"+ f"export GH_TOKEN={quoted}\n"+ f"export GITHUB_TOKEN={quoted}\n"+ )+++def helper_script(on: bool) -> str:+ """The git configuration step; removes only the helper this module set."""+ key = shlex.quote(_HELPER_KEY)+ ours = shlex.quote(HELPER)+ if on:+ return (+ f"git config --global --unset-all {key} >/dev/null 2>&1\n"+ f"git config --global --add {key} ''\n" # drop helpers inherited from system config+ f"git config --global --add {key} {ours}\n"+ )+ return (+ f'if [ "$(git config --global --get-all {key} 2>/dev/null | tail -n 1)" = {ours} ]; then\n'+ f" git config --global --unset-all {key}\n"+ "fi\n"+ f'rm -f "$HOME/{remote_os.GITHUB_ENV_FILE}"\n'+ )+++async def share(computer_id: str) -> Computer:+ """Write this PC's GitHub login to the computer (explicit user action)."""+ token, source = _local_token()+ service = get_service()+ async with service.session(computer_id) as session:+ try:+ host = await remote_os.remote_host(computer_id, session)+ await remote_os.upload_text(+ session, host, remote_os.GITHUB_ENV_FILE, env_file_body(token), private=True+ )+ result = await remote_os.run_script(session, host, helper_script(True), timeout_s=30)+ except SshError as exc:+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc+ if result.exit_status not in (0, None):+ log.warning(+ "computers: git credential helper not set on %s (exit %s)",+ computer_id,+ result.exit_status,+ )+ raise ComputerError(+ "The GitHub login was saved, but git could not be configured there. "+ "Install git on that computer (Agents tab), then share again.",+ status=502,+ kind="git_missing",+ )+ log.info(+ "computers: shared the GitHub login (%s) with %s at the user's request", source, computer_id+ )+ return _mark(computer_id, time.time())+++async def unshare(computer_id: str) -> Computer:+ """Remove the shared login and the helper from the computer again."""+ service = get_service()+ async with service.session(computer_id) as session:+ try:+ host = await remote_os.remote_host(computer_id, session)+ await remote_os.run_script(session, host, helper_script(False), timeout_s=30)+ except SshError as exc:+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc+ log.info("computers: removed the shared GitHub login from %s", computer_id)+ return _mark(computer_id, None)+++def _mark(computer_id: str, when: float | None) -> Computer:+ updated = get_service()._store.update( # noqa: SLF001 — the service owns the record+ computer_id, lambda row: row.model_copy(update={"github_shared_at": when})+ )+ if updated is None:+ raise ComputerError("This computer does not exist.", status=404)+ return updateddiff --git a/jarvis/computers/models.py b/jarvis/computers/models.pyindex ae4f10fd7c..d7cb054cd7 100644--- a/jarvis/computers/models.py+++ b/jarvis/computers/models.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import Literal-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, model_validator#: A rented or self-hosted machine reached over the network, or a VM on this box.ComputerKind = Literal["server", "local_vm"]@@ -43,6 +43,29 @@ HealthStatus = Literal[]+#: Where an address came from: typed in, suggested by Tailscale, or read from+#: this PC's ``~/.ssh/config``.+RouteSource = Literal["manual", "tailscale", "ssh_config"]++#: The id of the route a record without routes is given on read.+PRIMARY_ROUTE_ID = "r_main"+++class ComputerRoute(BaseModel):+ """One address the machine answers on (a LAN IP, a Tailscale name, …)."""++ model_config = ConfigDict(frozen=True)++ id: str+ host: str+ port: int = Field(default=22, ge=1, le=65535)+ #: A short name the user gave this way in ("Home LAN", "Tailscale").+ label: str | None = None+ source: RouteSource = "manual"+ #: When a connection last got through on this address (epoch seconds).+ last_ok_at: float | None = None++class ComputerFacts(BaseModel):"""What the machine is, read by the last successful check."""@@ -72,6 +95,8 @@ class ComputerHealth(BaseModel):mem_used_pct: float | None = Nonedisk_used_pct: float | None = Noneuptime_s: int | None = None+ #: The log correlation id of a failed check, for a bug report.+ trace_id: str | None = Noneclass Computer(BaseModel):@@ -99,3 +124,32 @@ class Computer(BaseModel):created_at: floatfacts: ComputerFacts | None = Nonehealth: ComputerHealth = Field(default_factory=ComputerHealth)+ #: Switched off: kept with its login, but nothing connects to it, nothing+ #: is checked and no picker offers it until it is switched on again.+ enabled: bool = True+ #: Every address the machine answers on, preferred first. A connection+ #: tries them in this order; ``host``/``port`` mirror the one that last+ #: got through (``active_route_id``), so readers of a single address keep+ #: working. A record stored before routes existed gets its ``host`` as the+ #: only route.+ routes: list[ComputerRoute] = Field(default_factory=list)+ active_route_id: str | None = None+ #: How often "Automatic" sends a new workspace here: 0 never, 1 less,+ #: 2 normal, 3 more (see :mod:`jarvis.computers.placement`).+ placement_weight: int = Field(default=2, ge=0, le=3)+ #: When this PC's GitHub login was last shared with the agents here;+ #: ``None`` when it is not shared (see :mod:`jarvis.computers.github_access`).+ github_shared_at: float | None = None++ @model_validator(mode="after")+ def _routes_cover_the_address(self) -> Computer:+ if not self.routes:+ route = ComputerRoute(id=PRIMARY_ROUTE_ID, host=self.host, port=self.port)+ object.__setattr__(self, "routes", [route])+ object.__setattr__(self, "active_route_id", route.id)+ elif self.active_route_id not in {r.id for r in self.routes}:+ object.__setattr__(self, "active_route_id", self.routes[0].id)+ return self++ def route(self, route_id: str | None) -> ComputerRoute | None:+ return next((r for r in self.routes if r.id == route_id), None)diff --git a/jarvis/computers/pairing.py b/jarvis/computers/pairing.pynew file mode 100644index 0000000000..859b399faa--- /dev/null+++ b/jarvis/computers/pairing.py@@ -0,0 +1,405 @@+"""Pair independent Jarvis servers without exchanging their control keys."""++from __future__ import annotations++import asyncio+import hashlib+import ipaddress+import os+import platform+import secrets+import tempfile+import threading+import time+from pathlib import Path+from typing import Any, Literal+from urllib.parse import urlsplit, urlunsplit++import httpx+from pydantic import BaseModel, Field, ValidationError++from jarvis.computers.pairing_errors import PairingError+from jarvis.core.config import delete_secret, get_secret, set_secret+from jarvis.core.http_pool import HttpClientPool+from jarvis.core.paths import user_data_dir++PROTOCOL = "jarvis-pairing-v1"+CODE_TTL = 300+TICKET_TTL = 60+_LOCK = threading.RLock()+++class ServerIdentity(BaseModel):+ protocol: Literal["jarvis-pairing-v1"]+ name: str = Field(min_length=1, max_length=120)+ platform: str = Field(max_length=120)+++class PairedServer(BaseModel):+ id: str+ url: str+ name: str+ platform: str+ created_at: float+ checked_at: float+ online: bool+++class PairingGrant(BaseModel):+ id: str+ name: str = Field(max_length=120)+ digest: str+ created_at: float+++class PairingState(BaseModel):+ servers: list[PairedServer] = Field(default_factory=list)+ grants: list[PairingGrant] = Field(default_factory=list)+++class Redemption(ServerIdentity):+ credential: str = Field(min_length=43, max_length=128, pattern=r"^[A-Za-z0-9_-]+$")+++def _digest(value: str) -> str:+ return hashlib.sha256(value.encode()).hexdigest()+++def _slot(server_id: str) -> str:+ return f"paired_server_{server_id}"+++def normalize_server(value: str) -> str:+ value = value.strip()+ if "://" not in value:+ value = "https://" + value+ try:+ url = urlsplit(value)+ if (+ any(char.isspace() for char in value)+ or "\\" in value+ or url.scheme not in {"http", "https"}+ or not url.hostname+ or url.username is not None+ or url.password is not None+ or url.path not in {"", "/"}+ or url.query+ or url.fragment+ ):+ raise ValueError("Use a server origin such as https://jarvis.example.com.")+ port = url.port+ if port is not None and port < 1:+ raise ValueError("The server port must be between 1 and 65535.")+ host = url.hostname.encode("idna").decode("ascii")+ try:+ address = ipaddress.ip_address(host)+ except ValueError:+ address = None # A DNS name is valid too; only localhost permits cleartext HTTP.+ if url.scheme == "http" and host != "localhost" and not (address and address.is_loopback):+ raise ValueError("Remote servers require HTTPS. An SSH tunnel may use local HTTP.")+ authority = f"[{host}]" if address and address.version == 6 else host+ if port is not None:+ authority += f":{port}"+ return urlunsplit((url.scheme, authority, "", "", ""))+ except ValueError as exc:+ raise PairingError(str(exc)) from exc+++class ServerPairing:+ """Durable public metadata, keyring credentials, and one-use in-memory codes."""++ def __init__(self, path: Path | None = None, pool: HttpClientPool | None = None) -> None:+ self.path = path or user_data_dir() / "computers" / "paired-servers.json"+ self.pool = pool or HttpClientPool(+ timeout_s=15,+ client_kwargs={"follow_redirects": False, "trust_env": False},+ )+ self._codes: dict[str, float] = {}+ self._tickets: dict[str, tuple[float, str]] = {}+ self._operation_loop: asyncio.AbstractEventLoop | None = None+ self._operations: dict[str, asyncio.Lock] = {}++ def _operation(self, url: str) -> asyncio.Lock:+ loop = asyncio.get_running_loop()+ if self._operation_loop is not loop:+ self._operations = {}+ self._operation_loop = loop+ return self._operations.setdefault(url, asyncio.Lock())++ def _read(self) -> PairingState:+ try:+ return PairingState.model_validate_json(self.path.read_text(encoding="utf-8"))+ except FileNotFoundError: # no pairings yet is the first-run state+ return PairingState()+ except (ValueError, OSError) as exc:+ raise PairingError("The saved server connections could not be read.", 500) from exc++ def _write(self, state: PairingState) -> None:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ fd, name = tempfile.mkstemp(prefix=".pairing-", dir=self.path.parent)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as stream:+ stream.write(state.model_dump_json(indent=2))+ os.replace(name, self.path)+ finally:+ Path(name).unlink(missing_ok=True)++ def identity(self) -> ServerIdentity:+ return ServerIdentity(+ protocol=PROTOCOL, name=platform.node()[:120] or "Jarvis", platform=platform.system()+ )++ def issue_code(self) -> dict[str, Any]:+ with _LOCK:+ now = time.time()+ self._codes = {code: expiry for code, expiry in self._codes.items() if expiry > now}+ if len(self._codes) >= 16:+ raise PairingError("Wait for an existing pairing code to expire.", 429)+ code = secrets.token_urlsafe(24)+ self._codes[_digest(code)] = now + CODE_TTL+ return {"code": code, "expires_at": now + CODE_TTL}++ def redeem(self, code: str, name: str) -> Redemption:+ with _LOCK:+ digest = _digest(code.strip())+ if self._codes.get(digest, 0) <= time.time():+ raise PairingError("The pairing code is invalid, expired, or already used.", 401)+ state = self._read()+ if len(state.grants) >= 64:+ raise PairingError("Remove an existing paired client before adding another.", 409)+ credential = secrets.token_urlsafe(32)+ state.grants.append(+ PairingGrant(+ id="g_" + secrets.token_hex(8),+ name=name.strip() or "Jarvis client",+ digest=_digest(credential),+ created_at=time.time(),+ )+ )+ self._write(state)+ self._codes.pop(digest)+ return Redemption(**self.identity().model_dump(), credential=credential)++ def authenticate(self, credential: str) -> PairingGrant:+ with _LOCK:+ digest = _digest(credential)+ grant = next(+ (g for g in self._read().grants if secrets.compare_digest(g.digest, digest)), None+ )+ if not credential or grant is None:+ raise PairingError(+ "This server connection is no longer authorized. Pair again.", 401+ )+ return grant++ def clients(self) -> list[dict[str, Any]]:+ with _LOCK:+ return [grant.model_dump(exclude={"digest"}) for grant in self._read().grants]++ def revoke(self, grant_id: str) -> None:+ with _LOCK:+ state = self._read()+ state.grants = [g for g in state.grants if g.id != grant_id]+ self._write(state)+ self._tickets = {+ key: value for key, value in self._tickets.items() if value[1] != grant_id+ }++ def issue_ticket(self, credential: str) -> str:+ with _LOCK:+ grant = self.authenticate(credential)+ now = time.time()+ self._tickets = {key: value for key, value in self._tickets.items() if value[0] > now}+ if len(self._tickets) >= 64:+ raise PairingError("Too many pending server windows. Try again in one minute.", 429)+ ticket = secrets.token_urlsafe(32)+ self._tickets[_digest(ticket)] = (now + TICKET_TTL, grant.id)+ return ticket++ def consume_ticket(self, ticket: str) -> None:+ with _LOCK:+ expiry, grant_id = self._tickets.pop(_digest(ticket), (0, ""))+ if expiry <= time.time() or not any(g.id == grant_id for g in self._read().grants):+ raise PairingError(+ "This server link expired or was already used. Open it again.", 401+ )++ def servers(self) -> list[PairedServer]:+ with _LOCK:+ return self._read().servers++ def server(self, server_id: str) -> PairedServer:+ server = next((s for s in self.servers() if s.id == server_id), None)+ if server is None:+ raise PairingError("This server connection does not exist.", 404)+ return server++ async def _request(+ self, url: str, path: str, *, credential: str = "", body: dict | None = None+ ) -> dict:+ # Revalidate stored origins too; credentials never follow redirects or environment proxies.+ origin = normalize_server(url)+ try:+ response = await self.pool.client().request(+ "POST" if body is not None else "GET",+ origin + "/api/computers/pairing/" + path,+ headers={"Authorization": "Bearer " + credential} if credential else {},+ json=body,+ )+ if response.status_code in {401, 403}:+ raise PairingError(+ "The server rejected this pairing code or saved connection. Pair again.", 401+ )+ if response.status_code != 200:+ raise PairingError(+ "The server did not accept the connection. Check its address and version.", 502+ )+ result = response.json()+ if not isinstance(result, dict):+ raise ValueError("Expected an object")+ return result+ except (httpx.HTTPError, ValueError) as exc:+ # Never echo response bodies or submitted credentials into user errors or logs.+ raise PairingError("Could not reach a compatible Jarvis server securely.", 502) from exc++ async def add(self, host: str, code: str) -> PairedServer:+ url = normalize_server(host)+ async with self._operation(url):+ return await self._add(url, code)++ async def _add(self, url: str, code: str) -> PairedServer:+ try:+ reply = Redemption.model_validate(+ await self._request(+ url,+ "redeem",+ body={+ "code": code.strip(),+ "name": self.identity().name,+ },+ )+ )+ except ValidationError as exc:+ raise PairingError(+ "The server returned an incompatible pairing response.", 502+ ) from exc+ return await asyncio.to_thread(self._save_server, url, reply)++ def _save_server(self, url: str, reply: Redemption) -> PairedServer:+ now = time.time()+ with _LOCK:+ state = self._read()+ previous = next((s for s in state.servers if s.url == url), None)+ server = PairedServer(+ id=previous.id if previous else "s_" + secrets.token_hex(8),+ url=url,+ name=reply.name,+ platform=reply.platform,+ created_at=previous.created_at if previous else now,+ checked_at=now,+ online=True,+ )+ old_credential = get_secret(_slot(server.id), env_fallback="")+ if not set_secret(_slot(server.id), reply.credential):+ raise PairingError(+ "The server credential could not be saved. Generate a new code and try again.",+ 500,+ )+ state.servers = [s for s in state.servers if s.id != server.id] + [server]+ try:+ self._write(state)+ except OSError as exc:+ if old_credential:+ set_secret(_slot(server.id), old_credential)+ else:+ delete_secret(_slot(server.id))+ raise PairingError("The server connection could not be saved.", 500) from exc+ return server++ def _credential(self, server_id: str) -> str:+ value = get_secret(_slot(server_id), env_fallback="")+ if not value:+ raise PairingError("The saved server credential is missing. Pair again.", 409)+ return value++ async def check(self, server_id: str) -> PairedServer:+ server = self.server(server_id)+ async with self._operation(server.url):+ return await self._check(server_id)++ async def _check(self, server_id: str) -> PairedServer:+ server = self.server(server_id)+ online = False+ try:+ reply = ServerIdentity.model_validate(+ await self._request(+ server.url,+ "status",+ credential=self._credential(server_id),+ )+ )+ online = True+ except (PairingError, ValidationError):+ # A failed health check is represented explicitly in the saved status.+ reply = ServerIdentity(protocol=PROTOCOL, name=server.name, platform=server.platform)+ with _LOCK:+ state = self._read()+ current = next((s for s in state.servers if s.id == server_id), None)+ if current is None:+ raise PairingError("This server connection was removed.", 404)+ updated = current.model_copy(+ update={+ "online": online,+ "checked_at": time.time(),+ "name": reply.name,+ "platform": reply.platform,+ }+ )+ state.servers = [updated if s.id == server_id else s for s in state.servers]+ self._write(state)+ return updated++ async def launch(self, server_id: str) -> str:+ server = self.server(server_id)+ async with self._operation(server.url):+ return await self._launch(server_id)++ async def _launch(self, server_id: str) -> str:+ server = self.server(server_id)+ result = await self._request(+ server.url, "launch", credential=self._credential(server_id), body={}+ )+ ticket = result.get("ticket")+ import re++ if not isinstance(ticket, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", ticket):+ raise PairingError("The server returned an invalid opening link.", 502)+ return server.url + "/api/computers/pairing/enter#" + ticket++ async def remove(self, server_id: str) -> None:+ server = self.server(server_id)+ async with self._operation(server.url):+ await self._remove(server_id)++ async def _remove(self, server_id: str) -> None:+ server = self.server(server_id)+ # Refuse to claim the remote grant was revoked when its server is unreachable.+ await self._request(+ server.url, "disconnect", credential=self._credential(server_id), body={}+ )+ with _LOCK:+ state = self._read()+ state.servers = [s for s in state.servers if s.id != server_id]+ self._write(state)+ delete_secret(_slot(server_id))+++_service: ServerPairing | None = None+++def get_pairing() -> ServerPairing:+ global _service+ with _LOCK:+ if _service is None:+ _service = ServerPairing()+ return _servicediff --git a/jarvis/computers/pairing_errors.py b/jarvis/computers/pairing_errors.pynew file mode 100644index 0000000000..755663a9ec--- /dev/null+++ b/jarvis/computers/pairing_errors.py@@ -0,0 +1,7 @@+"""Dependency-free errors shared by the pairing API and its lazy service."""+++class PairingError(Exception):+ def __init__(self, message: str, status: int = 400) -> None:+ super().__init__(message)+ self.status = statusdiff --git a/jarvis/computers/placement.py b/jarvis/computers/placement.pynew file mode 100644index 0000000000..e2ffe5532c--- /dev/null+++ b/jarvis/computers/placement.py@@ -0,0 +1,107 @@+"""Where "Automatic" sends a new IDE workspace: weighted over this PC and computers.++Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+LoadBalancingSettings.tsx: one share per switched-on machine, offered once at+least two machines can take work), MIT License, Copyright (c) 2026 T3 Tools+Inc. Full text: third_party/t3code/LICENSE.++Opt-in: off by default. When on, the new-workspace dialog offers "Automatic"+and :func:`pick` chooses among this PC and every switched-on computer that is+online, in proportion to each one's share (never / less / normal / more). A+computer's share lives on its record (``placement_weight``); this PC's share+and the switch live in ``<user data>/computers/placement.json``.+"""++from __future__ import annotations++import json+import logging+import os+import random+import tempfile+import threading+from dataclasses import asdict, dataclass+from pathlib import Path++from jarvis.computers.models import Computer+from jarvis.core.paths import user_data_dir++log = logging.getLogger(__name__)++#: Share level -> relative weight. "More" is twice "normal", "less" half.+WEIGHTS: dict[int, int] = {0: 0, 1: 1, 2: 2, 3: 4}+_LOCK = threading.Lock()+++@dataclass(frozen=True)+class PlacementSettings:+ enabled: bool = False+ #: This PC's share, on the same 0-3 scale as a computer's.+ local_weight: int = 2+++def _path() -> Path:+ return user_data_dir() / "computers" / "placement.json"+++def load() -> PlacementSettings:+ try:+ data = json.loads(_path().read_text(encoding="utf-8"))+ except FileNotFoundError: # never set: the feature is off+ return PlacementSettings()+ except (OSError, ValueError) as exc:+ log.warning("computers: unreadable placement settings: %s", exc)+ return PlacementSettings()+ if not isinstance(data, dict):+ return PlacementSettings()+ weight = data.get("local_weight", 2)+ return PlacementSettings(+ enabled=bool(data.get("enabled", False)),+ local_weight=weight if isinstance(weight, int) and 0 <= weight <= 3 else 2,+ )+++def save(settings: PlacementSettings) -> PlacementSettings:+ path = _path()+ with _LOCK:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(prefix=".placement.", suffix=".tmp", dir=path.parent)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(asdict(settings), handle)+ os.replace(tmp, path)+ except BaseException:+ Path(tmp).unlink(missing_ok=True)+ raise+ return settings+++def candidates(+ settings: PlacementSettings, computers: list[Computer]+) -> list[tuple[str | None, int]]:+ """``(computer id or None for this PC, weight)`` for every machine that may take work."""+ pool: list[tuple[str | None, int]] = []+ if WEIGHTS[settings.local_weight]:+ pool.append((None, WEIGHTS[settings.local_weight]))+ for computer in computers:+ weight = WEIGHTS.get(computer.placement_weight, 0)+ if computer.enabled and weight and computer.health.status == "online":+ pool.append((computer.id, weight))+ return pool+++def pick(+ settings: PlacementSettings, computers: list[Computer], *, rng: random.Random | None = None+) -> str | None:+ """The machine a new workspace goes to; ``None`` is this PC.++ With nothing else to choose (every computer off, offline or at "never"),+ the answer is this PC, whatever its own share says.+ """+ pool = candidates(settings, computers)+ if not pool:+ return None+ chooser = rng or random.SystemRandom()+ ids = [machine for machine, _weight in pool]+ weights = [weight for _machine, weight in pool]+ return chooser.choices(ids, weights=weights, k=1)[0]diff --git a/jarvis/computers/remote_os.py b/jarvis/computers/remote_os.pyindex 421fa8a460..1cc1fb6b2e 100644--- a/jarvis/computers/remote_os.py+++ b/jarvis/computers/remote_os.py@@ -62,6 +62,10 @@ LAUNCH_DIR: Final[str] = "jarvis-agents/.launch"#: launcher: ``CLAUDE_CODE_OAUTH_TOKEN`` lives here on a Mac, whose Keychain#: is locked in SSH sessions.AGENT_ENV_FILE: Final[str] = ".config/jarvis/agent.env"+#: The GitHub login this PC shared with the agents here (owner-only), sourced+#: by every launcher after :data:`AGENT_ENV_FILE`; absent unless the user+#: shared it (``jarvis.computers.github_access``).+GITHUB_ENV_FILE: Final[str] = ".config/jarvis/github.env"#: The user's own install folders: put FIRST when present, so a Node.js the#: readiness panel installed there wins over an older one from the system.@@ -360,7 +364,9 @@ def pid_record(host: RemoteHost, pid_file: str) -> str:def _source_agent_env() -> str:- return f'[ -f "$HOME/{AGENT_ENV_FILE}" ] && . "$HOME/{AGENT_ENV_FILE}"\n'+ return "".join(+ f'[ -f "$HOME/{name}" ] && . "$HOME/{name}"\n' for name in (AGENT_ENV_FILE, GITHUB_ENV_FILE)+ )def launcher_script(diff --git a/jarvis/computers/service.py b/jarvis/computers/service.pyindex 1c3646f782..e06ede2b7e 100644--- a/jarvis/computers/service.py+++ b/jarvis/computers/service.py@@ -28,13 +28,23 @@ import timefrom collections.abc import AsyncIteratorfrom typing import Any-from jarvis.computers import cloud, identity, local_vm, providers, remote_os+from jarvis.computers import (+ cloud,+ identity,+ local_vm,+ providers,+ remote_os,+ ssh_config,+ tailscale,+)from jarvis.computers.models import (AuthMethod,Computer,ComputerHealth,+ ComputerRoute,LoginMode,ProviderId,+ RouteSource,)from jarvis.computers.probe import PROBE_SCRIPT, WINDOWS_PROBE_SCRIPT, parse_probefrom jarvis.computers.ssh import (@@ -57,6 +67,17 @@ log = logging.getLogger(__name__)_HOST_RE = re.compile(r"^[A-Za-z0-9._:\-\[\]]{1,253}$")_USER_RE = re.compile(r"^[A-Za-z0-9._\-]{1,64}$")_PROBE_TIMEOUT_S = 25.0+#: With several addresses, one that does not even accept a TCP connection+#: within this time is skipped for the next one instead of costing the full+#: SSH login timeout.+_ROUTE_REACH_TIMEOUT_S = 4.0+#: A route that could not be reached is skipped by ordinary connections for+#: this long (a check still tries it, so a preferred route that came back is+#: picked up again).+_ROUTE_DOWN_S = 60.0+#: How stale a route's ``last_ok_at`` may get before a success rewrites it.+_ROUTE_SEEN_REFRESH_S = 300.0+_MAX_ROUTES = 8async def _probe(opened: Session, host: remote_os.RemoteHost) -> CommandResult:@@ -173,6 +194,42 @@ def _new_id() -> str:return f"c_{secrets.token_hex(6)}"+def _new_route_id() -> str:+ return f"r_{secrets.token_hex(4)}"+++def _alias_keys(alias: str | None) -> tuple[str, ...]:+ """The ``IdentityFile`` keys this PC's ``~/.ssh/config`` names for ``alias``."""+ if not alias:+ return ()+ found = ssh_config.find(alias)+ return found.identity_files if found is not None else ()+++def _with_address(row: Computer, host: str, port: int | None = None) -> Computer:+ """``row`` reached on a new address for its ACTIVE route (an edit, a VM's new IP)."""+ port = row.port if port is None else port+ routes = [+ r.model_copy(update={"host": host, "port": port}) if r.id == row.active_route_id else r+ for r in row.routes+ ]+ return row.model_copy(update={"host": host, "port": port, "routes": routes})+++async def _reachable(host: str, port: int) -> bool:+ """Whether anything accepts a TCP connection on ``host:port`` right now."""+ try:+ _reader, writer = await asyncio.wait_for(+ asyncio.open_connection(host, port), timeout=_ROUTE_REACH_TIMEOUT_S+ )+ except (OSError, TimeoutError): # unreachable is the answer this probe reports+ return False+ writer.close()+ with contextlib.suppress(OSError):+ await writer.wait_closed()+ return True++def _clean_name(name: str) -> str:cleaned = " ".join(name.split())[:80]if not cleaned:@@ -226,6 +283,9 @@ class ComputerService:self._store = store or ComputerStore()#: Running background jobs (VM creation) per computer id.self._jobs: dict[str, asyncio.Task[None]] = {}+ #: (computer id, route id) -> monotonic time until which that address+ #: counts as unreachable for ordinary connections.+ self._route_down: dict[tuple[str, str], float] = {}# -- reading ------------------------------------------------------------@@ -244,7 +304,19 @@ class ComputerService:# -- connecting ---------------------------------------------------------- def _target(self, computer: Computer, *, password: str | None = None) -> SshTarget:+ def _target(+ self,+ computer: Computer,+ *,+ password: str | None = None,+ route: ComputerRoute | None = None,+ ) -> SshTarget:+ target = self._login_target(computer, password=password)+ if route is None:+ return target+ return dataclasses.replace(target, host=route.host, port=route.port)++ def _login_target(self, computer: Computer, *, password: str | None = None) -> SshTarget:if password is not None:return SshTarget(host=computer.host,@@ -302,6 +374,84 @@ class ComputerService:self._store.update(computer_id, change)+ def _ordered_routes(self, computer: Computer, *, every: bool) -> list[ComputerRoute]:+ """The routes to try, preferred first; recently unreachable ones last.++ ``every`` (a check) keeps the plain preference order, so a preferred+ address that came back is found again.+ """+ if every or len(computer.routes) < 2:+ return list(computer.routes)+ now = time.monotonic()+ up = [r for r in computer.routes if self._route_down.get((computer.id, r.id), 0) <= now]+ down = [r for r in computer.routes if r not in up]+ return up + down++ async def _open(self, computer: Computer, *, every: bool = False) -> Session:+ """Log in on the first address that answers; remember which one it was.++ Only an address that cannot be reached falls through to the next one.+ A refused login or a changed server identity on ANY address stops the+ attempt: the same machine must show the same identity on every route,+ so a stranger answering on a second address is never trusted.+ """+ if not computer.enabled:+ raise ComputerError(+ "This computer is switched off. Switch it on under Settings, Computers to use it.",+ status=409,+ kind="disabled",+ )+ routes = self._ordered_routes(computer, every=every)+ first_error: SshError | None = None+ for index, route in enumerate(routes):+ last = index == len(routes) - 1+ if not last and not await _reachable(route.host, route.port):+ self._route_down[(computer.id, route.id)] = time.monotonic() + _ROUTE_DOWN_S+ first_error = first_error or SshError(+ "unreachable", f"{route.host}:{route.port} could not be reached."+ )+ continue+ try:+ opened = await open_session(self._target(computer, route=route))+ except SshError as exc:+ if exc.kind in ("unreachable", "timeout"):+ self._route_down[(computer.id, route.id)] = time.monotonic() + _ROUTE_DOWN_S+ if not last:+ first_error = first_error or exc+ continue+ # Every address failed: report the preferred one.+ exc = first_error or exc+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc+ self._route_down.pop((computer.id, route.id), None)+ self._note_route(computer, route)+ self._pin(computer.id, opened)+ return opened+ error = first_error or SshError("unreachable", "The server could not be reached.")+ raise ComputerError(error.message, status=502, kind=error.kind)++ def _note_route(self, computer: Computer, route: ComputerRoute) -> None:+ """Make ``route`` the active address; refresh when it last got through."""+ now = time.time()+ fresh = route.last_ok_at is not None and now - route.last_ok_at < _ROUTE_SEEN_REFRESH_S+ if computer.active_route_id == route.id and fresh:+ return++ def change(row: Computer) -> Computer:+ routes = [+ r.model_copy(update={"last_ok_at": now}) if r.id == route.id else r+ for r in row.routes+ ]+ return row.model_copy(+ update={+ "routes": routes,+ "active_route_id": route.id,+ "host": route.host,+ "port": route.port,+ }+ )++ self._store.update(computer.id, change)+async def connect(self, computer_id: str) -> Session:"""A long-lived authenticated connection; the caller closes it.@@ -309,24 +459,12 @@ class ComputerService:remote terminals). Pins the host key on first contact like:meth:`session`."""- computer = self.get(computer_id)- try:- opened = await open_session(self._target(computer))- except SshError as exc:- raise ComputerError(exc.message, status=502, kind=exc.kind) from exc- self._pin(computer_id, opened)- return opened+ return await self._open(self.get(computer_id))@contextlib.asynccontextmanager- async def session(self, computer_id: str) -> AsyncIterator[Session]:+ async def session(self, computer_id: str, *, every: bool = False) -> AsyncIterator[Session]:"""An authenticated connection; pins the host key on first contact."""- computer = self.get(computer_id)- target = self._target(computer)- try:- opened = await open_session(target)- except SshError as exc:- raise ComputerError(exc.message, status=502, kind=exc.kind) from exc- self._pin(computer_id, opened)+ opened = await self._open(self.get(computer_id), every=every)try:yield openedfinally:@@ -347,9 +485,11 @@ class ComputerService:computer = self.get(computer_id)if computer.health.status == "provisioning" and self.is_busy(computer_id):return computer+ if not computer.enabled:+ return computernow = time.time()try:- async with self.session(computer_id) as opened:+ async with self.session(computer_id, every=True) as opened:try:# A check asks afresh: a CLI installed since may live in a# folder the remembered PATH does not have yet.@@ -364,9 +504,22 @@ class ComputerService:status = _ERROR_STATUS.get(exc.kind or "", "error")if computer.kind == "local_vm" and status == "offline":status = await self._local_vm_state(computer) or status+ trace_id = f"cmp-{secrets.token_hex(4)}"+ log.warning(+ "computers: check of %s failed [%s] (%s): %s",+ computer_id,+ trace_id,+ exc.kind,+ exc.message,+ )return self._set_health(computer_id,- ComputerHealth(status=status, checked_at=now, message=exc.message), # type: ignore[arg-type]+ ComputerHealth(+ status=status, # type: ignore[arg-type]+ checked_at=now,+ message=exc.message,+ trace_id=trace_id,+ ),)reading = parse_probe(result.stdout)return self._set_health(@@ -384,7 +537,7 @@ class ComputerService:)async def check_all(self) -> list[Computer]:- ids = [c.id for c in self.all()]+ ids = [c.id for c in self.all() if c.enabled]results = await asyncio.gather(*(self.check(cid) for cid in ids), return_exceptions=True)for cid, outcome in zip(ids, results, strict=True):if isinstance(outcome, BaseException):@@ -484,6 +637,7 @@ class ComputerService:provider_ref: str | None = None,region: str | None = None,plan: str | None = None,+ ssh_alias: str | None = None,) -> Computer:"""Register a server. With a password, plant the key first (default).@@ -492,6 +646,9 @@ class ComputerService:the computer is stored with key login. When none opens the server theerror says whether a password would (``needs_password``) or only a key(``key_only``).++ ``ssh_alias`` names a host from this PC's ``~/.ssh/config``: its+ ``IdentityFile`` keys are offered too in the ``auto`` login."""computer = Computer(id=_new_id(),@@ -527,7 +684,9 @@ class ComputerService:self._save_private_key(computer.id, private_key or "", passphrase)computer = computer.model_copy(update={"auth": "private_key"})elif auth == "auto":- proof = await self._plant_key(self._this_pc_target(computer))+ proof = await self._plant_key(+ self._this_pc_target(computer, extra_key_files=_alias_keys(ssh_alias))+ )close(proof)computer = computer.model_copy(update={"host_key": proof.host_key, "host_fingerprint": proof.host_fingerprint}@@ -544,7 +703,9 @@ class ComputerService:else:delete_secret(_passphrase_slot(computer_id))- def _this_pc_target(self, computer: Computer) -> SshTarget:+ def _this_pc_target(+ self, computer: Computer, *, extra_key_files: tuple[str, ...] = ()+ ) -> SshTarget:"""The app's key plus this PC's own SSH keys, for one planting login."""try:key = identity.private_key()@@ -557,8 +718,28 @@ class ComputerService:host_key=computer.host_key,client_key=key,use_this_pc=True,+ extra_key_files=extra_key_files,)+ # -- what this PC already knows ------------------------------------------++ def ssh_config_hosts(self) -> list[dict[str, Any]]:+ """Servers from this PC's ``~/.ssh/config`` and ``known_hosts``."""+ added = {(r.host.lower(), r.port): c.id for c in self.all() for r in c.routes}+ return [+ {**h.to_dict(), "added_as": added.get((h.host.lower(), h.port))}+ for h in ssh_config.discover()+ ]++ async def tailscale_status(self) -> dict[str, Any]:+ """The tailnet's machines and, per computer, the addresses to suggest."""+ tailnet = await tailscale.peers()+ return {+ "available": tailscale.binary() is not None,+ "peers": [p.to_dict() for p in tailnet],+ "suggestions": tailscale.suggestions(self.all(), tailnet),+ }+async def test_connection(self,*,@@ -569,6 +750,7 @@ class ComputerService:password: str | None = None,private_key: str | None = None,passphrase: str | None = None,+ ssh_alias: str | None = None,) -> dict[str, Any]:"""Try a login WITHOUT saving anything; nothing is planted on the server."""if importlib.util.find_spec("asyncssh") is None:@@ -590,7 +772,10 @@ class ComputerService:target = dataclasses.replace(base, client_key=key)elif auth == "auto":target = dataclasses.replace(- base, client_key=identity.private_key(), use_this_pc=True+ base,+ client_key=identity.private_key(),+ use_this_pc=True,+ extra_key_files=_alias_keys(ssh_alias),)else:target = dataclasses.replace(base, client_key=identity.private_key())@@ -689,11 +874,141 @@ class ComputerService:changes["username"] = _check_user(fields["username"])if fields.get("port") is not None:changes["port"] = int(fields["port"])+ if fields.get("enabled") is not None:+ changes["enabled"] = bool(fields["enabled"])+ if fields.get("placement_weight") is not None:+ weight = int(fields["placement_weight"])+ if not 0 <= weight <= 3:+ raise ComputerError("Choose a share from 0 (never) to 3 (more).")+ changes["placement_weight"] = weightcurrent = self.get(computer_id)if "host" in changes and changes["host"] != current.host:# A different address is a different machine until proven otherwise.changes.update(host_key=None, host_fingerprint=None)- updated = self._store.update(computer_id, lambda row: row.model_copy(update=changes))++ def change(row: Computer) -> Computer:+ if "host" in changes or "port" in changes:+ row = _with_address(row, changes.get("host", row.host), changes.get("port"))+ rest = {k: v for k, v in changes.items() if k not in ("host", "port")}+ return row.model_copy(update=rest)++ updated = self._store.update(computer_id, change)+ if updated is None:+ raise ComputerError("This computer does not exist.", status=404)+ if changes.get("enabled") is False:+ self._route_down = {k: v for k, v in self._route_down.items() if k[0] != computer_id}+ return updated++ # -- routes ---------------------------------------------------------------++ async def add_route(+ self,+ computer_id: str,+ *,+ host: str,+ port: int = 22,+ label: str | None = None,+ source: RouteSource = "manual",+ ) -> Computer:+ """Add another address for the same machine, proven to BE that machine.++ The new address must answer with the identity already pinned for this+ computer; a different identity is a different machine and is refused.+ A refused login still counts as proof: the identity is checked before+ any login is tried.+ """+ computer = self.get(computer_id)+ if computer.kind == "local_vm":+ raise ComputerError("A local virtual machine has exactly one address.")+ host = _check_host(host)+ if any(r.host == host and r.port == port for r in computer.routes):+ raise ComputerError(+ "This address is already one of this computer's routes.", status=409+ )+ if len(computer.routes) >= _MAX_ROUTES:+ raise ComputerError(f"A computer can have at most {_MAX_ROUTES} addresses.")+ route = ComputerRoute(+ id=_new_route_id(),+ host=host,+ port=port,+ label=" ".join((label or "").split())[:40] or None,+ source=source,+ )+ if not computer.host_key:+ raise ComputerError(+ "Connect to this computer once before adding another address, so the "+ "new address can be checked against its identity.",+ status=409,+ )+ try:+ proof = await open_session(self._target(computer, route=route))+ except SshError as exc:+ if exc.kind == "host_key_changed":+ raise ComputerError(+ "A different machine answers on this address (its identity does "+ "not match this computer). The address was not added.",+ status=409,+ kind="host_key_changed",+ ) from exc+ if exc.kind in ("unreachable", "timeout"):+ raise ComputerError(+ f"{host}:{port} could not be reached. Add it while the computer "+ "answers on this address.",+ status=502,+ kind=exc.kind,+ ) from exc+ if exc.kind != "auth":+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc+ # The identity is verified before any login: a refused login on the+ # right machine still proves the address.+ else:+ close(proof)+ route = route.model_copy(update={"last_ok_at": time.time()})+ updated = self._store.update(+ computer_id, lambda row: row.model_copy(update={"routes": [*row.routes, route]})+ )+ if updated is None:+ raise ComputerError("This computer does not exist.", status=404)+ return updated++ def remove_route(self, computer_id: str, route_id: str) -> Computer:+ computer = self.get(computer_id)+ if computer.route(route_id) is None:+ raise ComputerError("This address is not one of this computer's routes.", status=404)+ if len(computer.routes) < 2:+ raise ComputerError(+ "This is the computer's only address. Remove the computer instead.", status=409+ )++ def change(row: Computer) -> Computer:+ kept = [r for r in row.routes if r.id != route_id]+ active = row.active_route_id if row.active_route_id != route_id else kept[0].id+ current = next(r for r in kept if r.id == active)+ return row.model_copy(+ update={+ "routes": kept,+ "active_route_id": active,+ "host": current.host,+ "port": current.port,+ }+ )++ self._route_down.pop((computer_id, route_id), None)+ updated = self._store.update(computer_id, change)+ if updated is None:+ raise ComputerError("This computer does not exist.", status=404)+ return updated++ def order_routes(self, computer_id: str, route_ids: list[str]) -> Computer:+ """Set the preference order; ``route_ids`` must name every route once."""+ computer = self.get(computer_id)+ if sorted(route_ids) != sorted(r.id for r in computer.routes):+ raise ComputerError("Name every address of this computer exactly once.")+ by_id = {r.id: r for r in computer.routes}+ updated = self._store.update(+ computer_id,+ lambda row: row.model_copy(update={"routes": [by_id[i] for i in route_ids]}),+ )if updated is None:raise ComputerError("This computer does not exist.", status=404)return updated@@ -857,11 +1172,8 @@ class ComputerService:returnself._store.update(computer_id,- lambda row: row.model_copy(- update={- "host": instance.ipv4 or row.host,- "health": ComputerHealth(status="unknown", checked_at=time.time()),- }+ lambda row: _with_address(row, instance.ipv4 or row.host).model_copy(+ update={"health": ComputerHealth(status="unknown", checked_at=time.time())}),)# cloud-init may still be writing the key for a few seconds after boot.@@ -881,9 +1193,8 @@ class ComputerService:instance = await local_vm.info(computer.provider_ref)if instance is not None and instance.ipv4 and instance.ipv4 != computer.host:# A restarted VM may come back on a new address; same machine.- self._store.update(- computer_id, lambda row: row.model_copy(update={"host": instance.ipv4})- )+ ipv4 = instance.ipv4+ self._store.update(computer_id, lambda row: _with_address(row, ipv4))elif action == "stop":await local_vm.stop(computer.provider_ref)return self._set_health(diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.pyindex 20bce29ae5..6a12d5ff34 100644--- a/jarvis/computers/ssh.py+++ b/jarvis/computers/ssh.py@@ -65,6 +65,9 @@ class SshTarget:#: once, to plant the app's own key; never stored.use_this_pc: bool = Falseclient_key: asyncssh.SSHKey | None = None+ #: With ``use_this_pc``: further key files to offer, the ``IdentityFile``+ #: lines this PC's ``~/.ssh/config`` names for the host.+ extra_key_files: tuple[str, ...] = ()@dataclass(frozen=True)@@ -98,6 +101,21 @@ def this_pc_keys() -> list[Any]:return list(load_default_keypairs())+def key_files(paths: tuple[str, ...]) -> list[Any]:+ """The readable, unencrypted keys among ``paths``; the rest are skipped."""+ import asyncssh++ keys: list[Any] = []+ for path in paths:+ try:+ keys.append(asyncssh.read_private_key(path))+ except (OSError, asyncssh.KeyImportError, asyncssh.KeyEncryptionError, ValueError) as exc:+ # A protected or unreadable key cannot be offered without a prompt;+ # the default keys and the agent are still tried.+ log.info("computers: skipping key file %s (%s)", path, type(exc).__name__)+ return keys++def _password_probe(offered: list[bool]) -> Any:"""An SSH client that notes whether the server would take a password."""import asyncssh@@ -183,7 +201,8 @@ async def open_session(target: SshTarget, *, timeout_s: float = CONNECT_TIMEOUT_offered: list[bool] = []if target.use_this_pc:own = [target.client_key] if target.client_key is not None else []- options["client_keys"] = [*own, *this_pc_keys()] or ()+ extra = key_files(target.extra_key_files)+ options["client_keys"] = [*own, *extra, *this_pc_keys()] or ()options["agent_path"] = THIS_PC_AGENT# Keys only; a password offer is noted, never answered.options["preferred_auth"] = "publickey,keyboard-interactive,password"diff --git a/jarvis/computers/ssh_config.py b/jarvis/computers/ssh_config.pynew file mode 100644index 0000000000..5302997779--- /dev/null+++ b/jarvis/computers/ssh_config.py@@ -0,0 +1,301 @@+"""The servers this PC's own ``ssh`` already knows, offered in the add dialog.++Portions adapted from pingdotgg/t3code @ 12069ee (packages/ssh/src/config.ts:+alias collection with ``Include`` globs, ``known_hosts`` parsing), MIT License,+Copyright (c) 2026 T3 Tools Inc. Full text: third_party/t3code/LICENSE.++Two sources, read from the user's home on every OS (``~`` is ``%USERPROFILE%``+on Windows):++* ``~/.ssh/config`` (and every file it ``Include``\\ s): each concrete ``Host``+ alias, resolved the way OpenSSH resolves it — the FIRST value a matching+ block gives an option wins, wildcard blocks such as ``Host *`` included.+* ``~/.ssh/known_hosts``: hosts this PC has logged in to before (hashed lines+ are unreadable by design and skipped).++Nothing here connects anywhere or changes a file. ``Match`` blocks need a+live connection to evaluate and are skipped; a host that needs a jump host+(``ProxyJump``/``ProxyCommand``) is listed but marked, because the app's own+SSH client does not route through one.+"""++from __future__ import annotations++import fnmatch+import getpass+import glob+import logging+import os+import re+from dataclasses import dataclass, field, replace+from pathlib import Path+from typing import Literal++log = logging.getLogger(__name__)++HostSource = Literal["ssh_config", "known_hosts"]++#: ``Include`` may nest; OpenSSH stops at 16 levels.+_MAX_INCLUDE_DEPTH = 16+#: A config is a handful of lines; anything bigger is not one.+_MAX_FILE_BYTES = 1_000_000+_PORT_RE = re.compile(r"^\d{1,5}$")+#: Git forges show up in ``known_hosts`` from every ``git clone``; they are not+#: machines anyone adds as a computer.+_GIT_FORGES = frozenset(+ {+ "github.com",+ "gitlab.com",+ "bitbucket.org",+ "codeberg.org",+ "ssh.dev.azure.com",+ "vs-ssh.visualstudio.com",+ "git.sr.ht",+ "ssh.github.com",+ "altssh.gitlab.com",+ "altssh.bitbucket.org",+ }+)+++@dataclass(frozen=True)+class SshConfigHost:+ """One server this PC knows, resolved to what a login needs."""++ alias: str+ host: str+ port: int+ username: str | None+ source: HostSource+ #: Private key files the config names for this host (that exist).+ identity_files: tuple[str, ...] = ()+ #: Reached through a jump host; the app cannot connect to it directly.+ needs_proxy: bool = False++ def to_dict(self) -> dict[str, object]:+ return {+ "alias": self.alias,+ "host": self.host,+ "port": self.port,+ "username": self.username,+ "source": self.source,+ "has_identity_file": bool(self.identity_files),+ "needs_proxy": self.needs_proxy,+ }+++@dataclass+class _Block:+ patterns: tuple[str, ...]+ options: dict[str, list[str]] = field(default_factory=dict)+ #: A ``Match`` block: it needs a live connection to evaluate, so never applies.+ match: bool = False++ def applies_to(self, alias: str) -> bool:+ if self.match:+ return False+ name = alias.lower()+ positive = False+ for pattern in self.patterns:+ negated = pattern.startswith("!")+ if fnmatch.fnmatchcase(name, pattern.lstrip("!").lower()):+ if negated:+ return False+ positive = True+ return positive+++def home_dir() -> Path:+ return Path(os.path.expanduser("~"))+++def _strip_comment(line: str) -> str:+ index = line.find("#")+ return (line[:index] if index >= 0 else line).strip()+++def _split(line: str) -> list[str]:+ """``Key value`` or ``Key=value``; double quotes group a value with spaces."""+ line = re.sub(r"^(\S+?)\s*=\s*", r"\1 ", line, count=1)+ parts: list[str] = []+ for match in re.finditer(r'"([^"]*)"|(\S+)', line):+ parts.append(match.group(1) if match.group(1) is not None else match.group(2))+ return parts+++def _is_pattern(value: str) -> bool:+ return "*" in value or "?" in value or value.startswith("!")+++def _expand_home(value: str, home: Path) -> str:+ if value == "~" or value.startswith(("~/", "~\\")):+ return str(home) + value[1:]+ return value+++def _include_paths(pattern: str, home: Path) -> list[Path]:+ expanded = _expand_home(pattern, home)+ path = Path(expanded)+ if not path.is_absolute():+ path = home / ".ssh" / expanded+ return [Path(p) for p in sorted(glob.glob(str(path))) if Path(p).is_file()]+++def _read(path: Path) -> str | None:+ try:+ if path.stat().st_size > _MAX_FILE_BYTES:+ log.info("computers: %s is too large to be an SSH config; skipped", path)+ return None+ return path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ # Unreadable or missing simply means nothing to offer from it.+ return None+++def parse_config(path: Path, home: Path) -> list[_Block]:+ """Every ``Host``/``Match`` block of ``path`` and its includes, in file order.++ Lines before the first block belong to an implicit ``Host *``.+ """+ blocks: list[_Block] = [_Block(patterns=("*",))]+ visited: set[Path] = set()++ def walk(file: Path, depth: int) -> None:+ resolved = file.resolve()+ if depth > _MAX_INCLUDE_DEPTH or resolved in visited:+ return+ visited.add(resolved)+ text = _read(file)+ if text is None:+ return+ for raw in text.splitlines():+ line = _strip_comment(raw)+ if not line:+ continue+ parts = _split(line)+ if not parts:+ continue+ key, args = parts[0].lower(), parts[1:]+ if key == "include":+ for pattern in args:+ for included in _include_paths(pattern, home):+ walk(included, depth + 1)+ elif key == "host":+ blocks.append(_Block(patterns=tuple(args)))+ elif key == "match":+ blocks.append(_Block(patterns=(), match=True))+ elif key == "identityfile" and args:+ # The one option OpenSSH collects from every matching line.+ blocks[-1].options.setdefault(key, []).append(args[0])+ elif args:+ blocks[-1].options.setdefault(key, args)++ walk(path, 0)+ return blocks+++def _aliases(blocks: list[_Block]) -> list[str]:+ seen: dict[str, None] = {}+ for block in blocks[1:]:+ for pattern in block.patterns:+ if pattern and not _is_pattern(pattern):+ seen.setdefault(pattern, None)+ return list(seen)+++def resolve(blocks: list[_Block], alias: str, home: Path) -> SshConfigHost:+ """What OpenSSH would use for ``alias``: the first value per option wins."""+ options: dict[str, list[str]] = {}+ identity_files: list[str] = []+ for block in blocks:+ if not block.applies_to(alias):+ continue+ for key, value in block.options.items():+ if key == "identityfile":+ identity_files.extend(value)+ else:+ options.setdefault(key, value)+ host = (options.get("hostname") or [alias])[0].replace("%h", alias)+ port_text = (options.get("port") or ["22"])[0]+ port = int(port_text) if _PORT_RE.match(port_text) and 0 < int(port_text) < 65536 else 22+ user = (options.get("user") or [None])[0]+ files = tuple(+ path+ for path in (+ _expand_home(f.replace("%d", str(home)).replace("%h", host), home)+ for f in identity_files+ )+ if Path(path).is_file()+ )+ proxy = (options.get("proxyjump") or options.get("proxycommand") or ["none"])[0]+ return SshConfigHost(+ alias=alias,+ host=host,+ port=port,+ username=user,+ source="ssh_config",+ identity_files=files,+ needs_proxy=proxy.lower() != "none",+ )+++def _known_host(raw: str) -> tuple[str, int] | None:+ bracket = re.match(r"^\[([^\]]+)\]:(\d+)$", raw)+ if bracket:+ return bracket.group(1), int(bracket.group(2))+ if raw.count(":") > 1: # a bare IPv6 address+ return raw, 22+ return (raw.rsplit(":", 1)[0], 22) if ":" in raw else (raw, 22)+++def parse_known_hosts(text: str) -> list[tuple[str, int]]:+ """The readable host entries of a ``known_hosts`` file, in file order."""+ found: dict[tuple[str, int], None] = {}+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ fields = line.split()+ if fields[0].startswith("@"): # @cert-authority / @revoked+ continue+ if fields[0].startswith("|"): # hashed: unreadable by design+ continue+ for name in fields[0].split(","):+ entry = _known_host(name.strip())+ if entry and entry[0] and not _is_pattern(entry[0]):+ found.setdefault(entry, None)+ return list(found)+++def discover(home: Path | None = None) -> list[SshConfigHost]:+ """Every server this PC's ``ssh`` knows, config aliases first."""+ home = home or home_dir()+ ssh_dir = home / ".ssh"+ blocks = parse_config(ssh_dir / "config", home)+ hosts = [resolve(blocks, alias, home) for alias in _aliases(blocks)]+ covered = {(h.host.lower(), h.port) for h in hosts} | {(h.alias.lower(), h.port) for h in hosts}+ known_text = _read(ssh_dir / "known_hosts") or ""+ try:+ local_user: str | None = getpass.getuser()+ except (OSError, KeyError):+ # No login name in this environment (a service account): leave it to the form.+ local_user = None+ for host, port in parse_known_hosts(known_text):+ if (host.lower(), port) in covered or host in ("localhost", "127.0.0.1", "::1"):+ continue+ if host.lower() in _GIT_FORGES:+ continue+ covered.add((host.lower(), port))+ hosts.append(+ SshConfigHost(alias=host, host=host, port=port, username=None, source="known_hosts")+ )+ # OpenSSH logs in as the local user when the config names none.+ return [+ h if h.username or h.source == "known_hosts" else replace(h, username=local_user)+ for h in hosts+ ]+++def find(alias: str, home: Path | None = None) -> SshConfigHost | None:+ """One discovered host by its alias (the add form sends the alias back)."""+ return next((h for h in discover(home) if h.alias == alias), None)diff --git a/jarvis/computers/tailscale.py b/jarvis/computers/tailscale.pynew file mode 100644index 0000000000..dd64341347--- /dev/null+++ b/jarvis/computers/tailscale.py@@ -0,0 +1,165 @@+"""This PC's Tailscale network, read to suggest a second address per computer.++Portions adapted from pingdotgg/t3code @ 12069ee+(apps/desktop/src/backend/tailscaleEndpointProvider.ts: reading+``tailscale status --json`` and preferring the MagicDNS name), MIT License,+Copyright (c) 2026 T3 Tools Inc. Full text: third_party/t3code/LICENSE.++A machine reached on its LAN address at home can still be reached on its+Tailscale name (``box.tail1234.ts.net``) from anywhere. When this PC runs+Tailscale, :func:`peers` lists the machines in the tailnet and+:func:`suggestions` matches them to the user's computers — by an address the+computer already has, or by the host name the computer reported. Nothing is+ever added on its own: a suggestion is a button the user presses.++Without Tailscale (no CLI, not logged in, any error) every function returns+nothing; this is an optional extra on every OS.+"""++from __future__ import annotations++import asyncio+import json+import logging+import shutil+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jarvis.computers.models import Computer+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)++_TIMEOUT_S = 8.0+++@dataclass(frozen=True)+class TailscalePeer:+ host_name: str+ #: The MagicDNS name without its trailing dot; empty when MagicDNS is off.+ dns_name: str+ ips: tuple[str, ...]+ online: bool+ os: str++ @property+ def address(self) -> str:+ """The address to connect to: MagicDNS name, else the first tailnet IP."""+ return self.dns_name or (self.ips[0] if self.ips else "")++ def to_dict(self) -> dict[str, Any]:+ return {+ "host_name": self.host_name,+ "dns_name": self.dns_name,+ "ips": list(self.ips),+ "online": self.online,+ "os": self.os,+ "address": self.address,+ }+++def binary() -> str | None:+ """The Tailscale CLI: on PATH, else where the installers put it."""+ found = shutil.which("tailscale")+ if found:+ return found+ candidates: list[Path] = []+ if sys.platform == "win32":+ candidates.append(Path(r"C:\Program Files\Tailscale\tailscale.exe"))+ elif sys.platform == "darwin":+ candidates.append(Path("/Applications/Tailscale.app/Contents/MacOS/Tailscale"))+ return next((str(p) for p in candidates if p.is_file()), None)+++def parse_status(raw: str) -> list[TailscalePeer]:+ """The peers in ``tailscale status --json`` output; ``[]`` when unreadable."""+ try:+ data = json.loads(raw)+ except json.JSONDecodeError: # unreadable status output means no peers+ return []+ if not isinstance(data, dict):+ return []+ peers: list[TailscalePeer] = []+ for item in (data.get("Peer") or {}).values():+ if not isinstance(item, dict):+ continue+ ips = tuple(str(ip) for ip in item.get("TailscaleIPs") or [] if isinstance(ip, str))+ peer = TailscalePeer(+ host_name=str(item.get("HostName") or ""),+ dns_name=str(item.get("DNSName") or "").rstrip("."),+ ips=ips,+ online=bool(item.get("Online")),+ os=str(item.get("OS") or ""),+ )+ if peer.address:+ peers.append(peer)+ return sorted(peers, key=lambda p: (not p.online, p.host_name.lower()))+++async def peers() -> list[TailscalePeer]:+ """The tailnet's other machines, or ``[]`` without a running Tailscale."""+ exe = binary()+ if exe is None:+ return []+ try:+ proc = await asyncio.create_subprocess_exec(+ exe,+ "status",+ "--json",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except OSError as exc:+ log.info("computers: tailscale could not be started: %s", exc)+ return []+ try:+ out, _err = await asyncio.wait_for(proc.communicate(), timeout=_TIMEOUT_S)+ except TimeoutError:+ proc.kill()+ await proc.wait()+ log.info("computers: tailscale status did not answer within %s s", _TIMEOUT_S)+ return []+ if proc.returncode != 0:+ # Logged out or the daemon is stopped: simply no tailnet to offer.+ return []+ return parse_status(out.decode("utf-8", errors="replace"))+++def _first_label(name: str) -> str:+ return name.split(".", 1)[0].lower()+++def match(computer: Computer, peer: TailscalePeer) -> bool:+ """Whether ``peer`` is the same machine as ``computer``."""+ known = {r.host.lower() for r in computer.routes}+ if known & ({peer.dns_name.lower()} | {ip.lower() for ip in peer.ips}):+ return True+ reported = (computer.facts.hostname if computer.facts else None) or ""+ return bool(reported) and _first_label(reported) == peer.host_name.lower()+++def suggestions(+ computers: list[Computer], tailnet: list[TailscalePeer]+) -> dict[str, list[dict[str, Any]]]:+ """Per computer id: tailnet addresses it does not have as a route yet."""+ out: dict[str, list[dict[str, Any]]] = {}+ for computer in computers:+ if computer.kind == "local_vm":+ continue+ have = {r.host.lower() for r in computer.routes}+ for peer in tailnet:+ if not match(computer, peer) or peer.address.lower() in have:+ continue+ out.setdefault(computer.id, []).append(+ {+ "host": peer.address,+ # sshd listens on the same port on every interface.+ "port": computer.routes[0].port,+ "label": "Tailscale",+ "online": peer.online,+ }+ )+ return outdiff --git a/jarvis/hardware/detection.py b/jarvis/hardware/detection.pyindex 845e0d4a0d..259f25183b 100644--- a/jarvis/hardware/detection.py+++ b/jarvis/hardware/detection.py@@ -731,6 +731,10 @@ def _probe_accelerator_gb() -> tuple[float, str]:log.debug("hardware: vendor-neutral accelerator probe failed", exc_info=True)vendor_gb, vendor_source = 0.0, ""if vendor_gb > 0:+ if sys.platform == "darwin" and platform.machine() == "arm64":+ # Keep the measured Metal budget and its supported device family.+ # Consumers distinguish MPS from generic, unqualified GPU reports.+ return vendor_gb, "apple-unified"return vendor_gb, vendor_sourceif sys.platform == "darwin" and platform.machine() == "arm64":try:diff --git a/jarvis/marketplace/catalog.py b/jarvis/marketplace/catalog.pyindex 9ef2353020..984de03881 100644--- a/jarvis/marketplace/catalog.py+++ b/jarvis/marketplace/catalog.py@@ -58,6 +58,11 @@ class PatPasteAuth(_BaseAuth):token_prefixes: list[str] = Field(default_factory=list)validation_endpoint: strinstruction_md: str+ # How the pasted token is proven to work. ``http_get`` expects a 200 from+ # ``validation_endpoint``; ``mcp_initialize`` sends an MCP handshake to it+ # with the plugin's own auth header, for custom connectors whose server+ # has no REST "who am I" endpoint to ask.+ validation_method: Literal["http_get", "mcp_initialize"] = "http_get"# Set for self-hosted services: the user supplies the address, so# `validation_endpoint` above is ignored in favour of# `instance_url.validation_path` appended to what they entered.@@ -135,6 +140,18 @@ class LocalAuth(_BaseAuth):mode: Literal["local"]+class HostedMcpOpenAuth(_BaseAuth):+ """A remote MCP server that answers without any sign-in.++ Connecting is still an explicit step: the server is probed once, and only+ an answered handshake marks it connected, so the on/off state stays the+ user's choice like every other plugin's.+ """++ mode: Literal["hosted_mcp_open"]+ mcp_url: str++AuthConfig = Annotated[PatPasteAuth| InstanceBrowserAuth@@ -142,7 +159,8 @@ AuthConfig = Annotated[| HostedMcpOAuthDcrAuth| OAuthPkceLoopbackAuth| HostedMcpAllowlistAuth- | LocalAuth,+ | LocalAuth+ | HostedMcpOpenAuth,Field(discriminator="mode"),]diff --git a/jarvis/marketplace/custom_api.py b/jarvis/marketplace/custom_api.pyindex 37acd24740..78008f4a46 100644--- a/jarvis/marketplace/custom_api.py+++ b/jarvis/marketplace/custom_api.py@@ -13,6 +13,7 @@ import loggingimport osimport reimport tempfile+from copy import deepcopyfrom pathlib import Pathfrom typing import Any, Literalfrom urllib.parse import unquote, urlsplit@@ -26,7 +27,7 @@ from jarvis.marketplace.token_store import Tokens, TokenStorelog = logging.getLogger(__name__)_ID = re.compile(r"^[a-f0-9]{32}$")-_PARAM = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")+_PARAM = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_.\[\]-]*)\}")def validate_path(value: str) -> str:@@ -47,8 +48,8 @@ def validate_path(value: str) -> str:class ApiAuth(BaseModel):model_config = ConfigDict(extra="forbid")- mode: Literal["none", "bearer", "header"] = "bearer"- header_name: str = Field(default="X-API-Key", pattern=r"^[A-Za-z][A-Za-z0-9-]{0,63}$")+ mode: Literal["none", "bearer", "header", "query"] = "bearer"+ header_name: str = Field(default="X-API-Key", pattern=r"^[A-Za-z][A-Za-z0-9_.-]{0,127}$")@model_validator(mode="after")def allowed_header(self) -> ApiAuth:@@ -68,21 +69,26 @@ class ApiAuth(BaseModel):class ApiParameter(BaseModel):model_config = ConfigDict(extra="forbid")- name: str = Field(pattern=r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$")- location: Literal["path", "query"] = "query"- type: Literal["string", "integer", "number", "boolean"] = "string"+ name: str = Field(pattern=r"^[a-zA-Z_][a-zA-Z0-9_.\[\]-]{0,127}$")+ location: Literal["path", "query", "header"] = "query"+ type: Literal["string", "integer", "number", "boolean", "array", "object"] = "string"required: bool = Falsedescription: str = Field(default="", max_length=500)+ value_schema: dict[str, Any] | None = Noneclass ApiAction(BaseModel):model_config = ConfigDict(extra="forbid")id: str = Field(pattern=r"^[a-z][a-z0-9_]{0,23}$")description: str = Field(min_length=1, max_length=1500)- method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] = "GET"+ method: Literal["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"] = "GET"path: str = Field(max_length=2000)parameters: list[ApiParameter] = Field(default_factory=list, max_length=64)body_schema: dict[str, Any] | None = None+ body_required: bool = True+ body_encoding: Literal["json", "multipart", "form", "binary"] = "json"+ file_fields: list[str] = Field(default_factory=list)+ content_type: str = "application/json"risk_tier: Literal["monitor", "ask", "block"] = "monitor"response: Literal["auto", "json", "text", "file"] = "auto"@@ -97,7 +103,7 @@ class ApiAction(BaseModel):from jsonschema.exceptions import SchemaErrorraw = json.dumps(value)- if len(raw) > 32_000:+ if len(raw) > 128_000:raise ValueError("Request schema is too large")# Reference resolution must never make hidden network requests.@@ -130,12 +136,14 @@ class ApiAction(BaseModel):raise ValueError("Every {path_parameter} must have a matching path parameter")if self.method == "GET" and self.body_schema is not None:raise ValueError("GET actions use path and query parameters, not a body")+ for parameter in self.parameters:+ self.valid_schema(parameter.value_schema)return selfdef input_schema(self) -> dict[str, Any]:properties: dict[str, Any] = {}required = []- for location in ("path", "query"):+ for location in ("path", "query", "header"):params = [p for p in self.parameters if p.location == location]if not params:continue@@ -144,15 +152,19 @@ class ApiAction(BaseModel):"type": "object","additionalProperties": False,"properties": {- p.name: {"type": p.type, "description": p.description} for p in params+ p.name: deepcopy(+ p.value_schema or {"type": p.type, "description": p.description}+ )+ for p in params},"required": needed,}if needed:required.append(location)if self.body_schema is not None:- properties["body"] = self.body_schema- required.append("body")+ properties["body"] = deepcopy(self.body_schema)+ if self.body_required:+ required.append("body")return {"type": "object","properties": properties,@@ -161,6 +173,27 @@ class ApiAction(BaseModel):}+class ApiConnectionInfo(BaseModel):+ """Public provenance and presentation for an automatically configured service."""++ model_config = ConfigDict(extra="forbid")+ service_id: str+ website: str+ spec_url: str+ brand_id: str = ""+ logo_data: str = Field(default="", max_length=100_000)+ categories: list[str] = Field(default_factory=list)+ status: Literal["configured", "verified", "limited"] = "configured"+ omitted_operations: int = 0++ @field_validator("logo_data")+ @classmethod+ def safe_logo(cls, value: str) -> str:+ if value and not re.fullmatch(r"data:image/png;base64,[A-Za-z0-9+/=]+", value):+ raise ValueError("Connection artwork must be a cached PNG")+ return value++class ApiDefinition(BaseModel):model_config = ConfigDict(extra="forbid")id: str = Field(default_factory=lambda: uuid4().hex, pattern=_ID.pattern)@@ -169,7 +202,8 @@ class ApiDefinition(BaseModel):base_url: str = Field(max_length=2000)auth: ApiAuth = Field(default_factory=ApiAuth)enabled: bool = True- actions: list[ApiAction] = Field(min_length=1, max_length=64)+ actions: list[ApiAction] = Field(min_length=1, max_length=4096)+ connection: ApiConnectionInfo | None = None@field_validator("base_url")@classmethod@@ -206,6 +240,7 @@ class CustomApiStore:)self.directory = directory if directory is not None else data_root / "custom-apis"self.tokens = tokens if tokens is not None else TokenStore()+ self._cache: dict[str, tuple[int, int, ApiDefinition]] = {}def _path(self, api_id: str) -> Path:if not _ID.fullmatch(api_id):@@ -219,8 +254,15 @@ class CustomApiStore:def get(self, api_id: str) -> ApiDefinition | None:path = self._path(api_id)try:- return ApiDefinition.model_validate_json(path.read_text(encoding="utf-8"))+ stat = path.stat()+ cached = self._cache.get(api_id)+ if cached and cached[:2] == (stat.st_mtime_ns, stat.st_size):+ return cached[2].model_copy(deep=True)+ definition = ApiDefinition.model_validate_json(path.read_text(encoding="utf-8"))+ self._cache[api_id] = (stat.st_mtime_ns, stat.st_size, definition)+ return definition.model_copy(deep=True)except FileNotFoundError:+ self._cache.pop(api_id, None)log.debug("Custom API %s has no saved definition", api_id)return Nonediff --git a/jarvis/marketplace/custom_api_connect.py b/jarvis/marketplace/custom_api_connect.pynew file mode 100644index 0000000000..c64569ba83--- /dev/null+++ b/jarvis/marketplace/custom_api_connect.py@@ -0,0 +1,95 @@+"""Single-key setup checks. Discovery receives a name, never the supplied key."""++from __future__ import annotations++import asyncio+import logging+from typing import Any++import httpx++from jarvis.core.http_guard import public_only_async+from jarvis.core.http_pool import HttpClientPool+from jarvis.marketplace.custom_api import ApiDefinition+from jarvis.marketplace.custom_api_discovery import ApiDiscoveryError+from jarvis.marketplace.custom_api_transport import QUERY_AUTH_EXTENSION, ApiTransport++log = logging.getLogger(__name__)+_ACCOUNT_READS = (+ "/v1/user",+ "/user",+ "/v1/me",+ "/me",+ "/account",+ "/v1/account",+ "/v1/models",+ "/models",+ "/openai/v1/models",+)+++async def verify_api_key(+ definition: ApiDefinition, credential: str, *, transport: Any = None+) -> str:+ """Only documented, parameter-free account reads can verify setup."""+ action = next(+ (+ a+ for path in _ACCOUNT_READS+ for a in definition.actions+ if a.path == path+ and a.method == "GET"+ and not any(p.required or p.location == "path" for p in a.parameters)+ ),+ None,+ )+ if action is None or definition.auth.mode == "none":+ return "configured"+ headers = {"Accept": "application/json"}+ extensions = {}+ if definition.auth.mode == "bearer":+ headers["Authorization"] = f"Bearer {credential}"+ elif definition.auth.mode == "header":+ headers[definition.auth.header_name] = credential+ elif definition.auth.mode == "query":+ extensions[QUERY_AUTH_EXTENSION] = (definition.auth.header_name, credential)+ pool = HttpClientPool(+ timeout_s=8,+ transport=ApiTransport(transport),+ client_kwargs={+ "follow_redirects": False,+ "trust_env": False,+ **public_only_async(),+ },+ )+ try:+ async with (+ asyncio.timeout(10),+ pool.client().stream(+ "GET", definition.base_url + action.path, headers=headers, extensions=extensions+ ) as response,+ ):+ if 200 <= response.status_code < 300:+ return "verified"+ if response.status_code == 403:+ return "limited"+ if response.status_code == 401:+ raw = bytearray()+ async for part in response.aiter_bytes(8192):+ raw.extend(part)+ if len(raw) > 32_768:+ break+ # Some restricted keys cannot read their account but can still+ # perform allowed operations. Only known machine codes qualify.+ if any(+ code in raw+ for code in (b'"missing_permissions"', b'"insufficient_permissions"')+ ):+ return "limited"+ raise ApiDiscoveryError("invalid_key")+ return "configured"+ except (httpx.HTTPError, TimeoutError):+ log.warning("Custom API account check unavailable; key remains unverified")+ return "configured"+ finally:+ await pool.aclose()diff --git a/jarvis/marketplace/custom_api_discovery.py b/jarvis/marketplace/custom_api_discovery.pynew file mode 100644index 0000000000..7ddd0683c1--- /dev/null+++ b/jarvis/marketplace/custom_api_discovery.py@@ -0,0 +1,404 @@+"""Name-only discovery of published API descriptions. Never accepts a credential."""++from __future__ import annotations++import asyncio+import base64+import io+import json+import logging+import re+import time+from difflib import SequenceMatcher+from html.parser import HTMLParser+from typing import Any+from urllib.parse import urljoin, urlsplit++import httpx++from jarvis.core.http_guard import public_only_async+from jarvis.core.http_pool import HttpClientPool+from jarvis.marketplace.custom_api import ApiConnectionInfo, ApiDefinition+from jarvis.marketplace.custom_api_openapi import api_auth, api_base_url, compile_openapi++log = logging.getLogger(__name__)+DIRECTORY_URL = "https://api.apis.guru/v2/list.json"+BRAND_DIRECTORY_URL = (+ "https://raw.githubusercontent.com/simple-icons/simple-icons/develop/data/simple-icons.json"+)+_ALIASES = {"11labs": "elevenlabs", "elevenlab": "elevenlabs"}+# A bootstrap address is a discovery hint, not a hand-maintained action list.+# Every operation still comes from the provider's current published document.+_BOOTSTRAP = {+ "elevenlabs": ("ElevenLabs", "elevenlabs.io", "https://api.elevenlabs.io/openapi.json")+}+++class ApiDiscoveryError(ValueError):+ def __init__(self, code: str, suggestions: list[str] | None = None) -> None:+ super().__init__(code)+ self.code = code+ self.suggestions = suggestions or []+++def normalized_name(name: str) -> str:+ value = re.sub(r"\b(api|apis|documentation|official)\b", "", name.lower())+ value = re.sub(r"[^\w]", "", value)+ return _ALIASES.get(value, value)+++def same_service_host(host: str, domain: str) -> bool:+ host, domain = host.lower().rstrip("."), domain.lower().rstrip(".")+ return host == domain or host.endswith("." + domain)+++class _Links(HTMLParser):+ def __init__(self) -> None:+ super().__init__()+ self.links: list[str] = []++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ values = dict(attrs)+ if tag in {"a", "link"} and values.get("href"):+ self.links.append(str(values["href"]))+++class ApiDiscovery:+ def __init__(+ self, *, transport: Any = None, directory: dict[str, Any] | None = None, search: Any = None+ ) -> None:+ self._pool = HttpClientPool(+ timeout_s=15,+ transport=transport,+ client_kwargs={+ "follow_redirects": False,+ "trust_env": False,+ **public_only_async(),+ },+ )+ self._directory = directory+ self._loaded_at = time.monotonic() if directory is not None else 0.0+ self._lock = asyncio.Lock()+ self._search = search+ self._brands: list[dict[str, Any]] | None = None+ self._documents: dict[str, dict[str, Any]] = {}++ async def close(self) -> None:+ await self._pool.aclose()++ async def _fetch(self, url: str, maximum: int = 32 * 1024 * 1024) -> tuple[bytes, str]:+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.username or parts.password:+ raise ApiDiscoveryError("unsafe_documentation")+ # All redirects are separately checked before sending a request. No+ # authentication headers, keys or cookies are used for documentation.+ for _ in range(4):+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.username or parts.password:+ raise ApiDiscoveryError("unsafe_documentation")+ async with self._pool.client().stream(+ "GET",+ url,+ headers={"Accept": "application/json, application/yaml, text/html, image/png"},+ ) as response:+ if response.is_redirect and response.headers.get("location"):+ url = urljoin(url, response.headers["location"])+ if urlsplit(url).scheme != "https":+ raise ApiDiscoveryError("unsafe_documentation")+ continue+ response.raise_for_status()+ data = bytearray()+ async for chunk in response.aiter_bytes(64 * 1024):+ data.extend(chunk)+ if len(data) > maximum:+ raise ApiDiscoveryError("documentation_too_large")+ return bytes(data), url+ raise ApiDiscoveryError("documentation_unavailable")++ async def _catalog(self) -> dict[str, Any]:+ async with self._lock:+ if self._directory is not None and time.monotonic() - self._loaded_at < 6 * 3600:+ return self._directory+ raw, _ = await self._fetch(DIRECTORY_URL, 16 * 1024 * 1024)+ result = await asyncio.to_thread(json.loads, raw)+ if not isinstance(result, dict):+ raise ApiDiscoveryError("documentation_unavailable")+ self._directory, self._loaded_at = result, time.monotonic()+ return result++ @staticmethod+ def _match(name: str, directory: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:+ target = normalized_name(name)+ scored = []+ for service, entry in directory.items():+ version = entry.get("versions", {}).get(entry.get("preferred"), {})+ info = version.get("info", {})+ domain, _, suffix = service.partition(":")+ labels = [info.get("title", ""), service, domain.split(".")[0] + " " + suffix]+ names = [normalized_name(str(v)) for v in labels]+ score = max(+ (1.0 if target == value else SequenceMatcher(None, target, value).ratio())+ for value in names+ )+ if score >= 0.78:+ scored.append((score, service, version))+ scored.sort(key=lambda item: (-item[0], item[1]))+ if not scored:+ return None+ if scored[0][0] < 1 or (len(scored) > 1 and scored[0][0] - scored[1][0] < 0.08):+ raise ApiDiscoveryError(+ "ambiguous_service",+ [str(v[2].get("info", {}).get("title", v[1])) for v in scored[:5]],+ )+ return scored[0][1], scored[0][2]++ async def _search_document(self, name: str) -> tuple[str, str, str]:+ """Discover an unlisted provider from its own public documentation."""+ target = normalized_name(name)+ try:+ if self._brands is None:+ raw, _ = await self._fetch(BRAND_DIRECTORY_URL, 2 * 1024 * 1024)+ self._brands = json.loads(raw)+ matches = [+ b+ for b in self._brands+ if target+ in {+ normalized_name(str(b.get("title", ""))),+ *[normalized_name(v) for v in b.get("aliases", {}).get("aka", [])],+ }+ ]+ if len(matches) == 1:+ brand = matches[0]+ host = urlsplit(str(brand.get("source", ""))).hostname or ""+ for prefix in ("www.", "docs.", "developers.", "brand."):+ host = host.removeprefix(prefix)+ if host and host not in {+ "github.com",+ "raw.githubusercontent.com",+ "wikipedia.org",+ "commons.wikimedia.org",+ }:+ found = await self._published_document(host)+ if found:+ return str(brand["title"]), host, found+ except (httpx.HTTPError, ValueError):+ log.debug("Custom API brand directory discovery was unavailable")+ if self._search is None:+ from jarvis.plugins.tool.search_backends import run_search++ found = await run_search(+ f'"{name}" official OpenAPI swagger API documentation',+ 6,+ client=self._pool.client(),+ apifare_key="",+ )+ rows = found.results+ else:+ rows = await self._search(name)+ domain_input = urlsplit(name if "://" in name else "https://" + name).hostname or ""+ candidates: list[tuple[str, str]] = []+ for row in rows:+ url = row.get("url") or row.get("href") or ""+ host = urlsplit(url).hostname or ""+ if urlsplit(url).scheme != "https":+ continue+ # A search result alone never chooses an unrelated credential host.+ # An official domain must identify the requested service itself.+ labels = host.split(".")+ # Match the service's registrable label, never an arbitrary+ # subdomain such as requested-service.someone-else.example.+ suffix_size = (+ 2+ if ".".join(labels[-2:])+ in {+ "co.uk",+ "com.au",+ "co.nz",+ "co.jp",+ "com.br",+ "co.in",+ }+ else 1+ )+ brand_index = len(labels) - suffix_size - 1+ if brand_index >= 0 and normalized_name(labels[brand_index]) == target:+ domain = ".".join(labels[brand_index:])+ elif "." in domain_input and same_service_host(host, domain_input):+ domain = domain_input+ else:+ continue+ candidates.append((url, domain))+ if not candidates:+ raise ApiDiscoveryError("service_not_found")+ domains = {domain for _, domain in candidates}+ if len(domains) != 1:+ raise ApiDiscoveryError("ambiguous_service", sorted(domains))+ for page, domain in candidates[:3]:+ try:+ raw, actual = await self._fetch(page, 3 * 1024 * 1024)+ document = self._parse(raw)+ if document:+ self._documents[actual] = document+ return name, domain, actual+ links = _Links()+ links.feed(raw.decode("utf-8", errors="replace"))+ for href in links.links:+ if re.search(+ r"(?:openapi|swagger)[^?#]*\.(?:json|ya?ml)(?:[?#]|$)", href, re.I+ ):+ return name, domain, urljoin(actual, href)+ except (httpx.HTTPError, ValueError):+ log.debug("Custom API public documentation candidate was unavailable")+ raise ApiDiscoveryError("documentation_not_found")++ async def _published_document(self, domain: str) -> str | None:+ """Check public documentation conventions on a catalog-identified domain."""+ for path in ("/openapi.json", "/openapi.yaml", "/openapi.yml", "/llms.txt"):+ try:+ raw, actual = await self._fetch(f"https://{domain}{path}")+ document = await asyncio.to_thread(self._parse, raw)+ if document:+ self._documents[actual] = document+ return actual+ if path == "/llms.txt":+ links = re.findall(+ r"https://[^\s)<>\"']+", raw.decode("utf-8", errors="replace")+ )+ for link in links:+ if re.search(+ r"(?:openapi|swagger).*\.(?:json|ya?ml)(?:[?#]|$)", link, re.I+ ):+ return link+ except (httpx.HTTPError, ValueError):+ log.debug("Custom API conventional documentation address was unavailable")+ try:+ raw, actual = await self._fetch(f"https://api.{domain}/openapi.json")+ document = await asyncio.to_thread(self._parse, raw)+ if document:+ self._documents[actual] = document+ return actual+ except (httpx.HTTPError, ValueError):+ log.debug("Custom API API-host documentation address was unavailable")+ return None++ @staticmethod+ def _parse(raw: bytes) -> dict[str, Any] | None:+ try:+ value = json.loads(raw)+ except (ValueError, UnicodeDecodeError):+ log.debug("Custom API documentation is not JSON; checking YAML")+ try:+ import yaml++ value = yaml.safe_load(raw)+ except (ValueError, yaml.YAMLError):+ log.debug("Custom API documentation candidate is not an OpenAPI document")+ return None+ if (+ isinstance(value, dict)+ and (value.get("openapi") or value.get("swagger"))+ and isinstance(value.get("paths"), dict)+ ):+ return value+ return None++ async def _logo(self, domain: str, image_url: str = "") -> str:+ for url in [image_url, f"https://{domain}/favicon.ico"]:+ if not url:+ continue+ try:+ raw, _ = await self._fetch(url, 512 * 1024)+ return await asyncio.to_thread(self._png, raw)+ except (httpx.HTTPError, ValueError, OSError):+ log.debug("Custom API brand artwork candidate was unavailable")+ return ""++ @staticmethod+ def _png(raw: bytes) -> str:+ from PIL import Image++ with Image.open(io.BytesIO(raw)) as picture:+ if picture.width > 2048 or picture.height > 2048:+ raise ValueError("Artwork is too large")+ picture.thumbnail((96, 96))+ out = io.BytesIO()+ picture.convert("RGBA").save(out, format="PNG")+ return "data:image/png;base64," + base64.b64encode(out.getvalue()).decode("ascii")++ async def resolve(self, name: str) -> ApiDefinition:+ """Resolve a name to validated metadata. Credentials cannot enter this path."""+ name = name.strip()+ if not name or len(name) > 100 or any(ord(c) < 32 for c in name):+ raise ApiDiscoveryError("invalid_service_name")+ async with asyncio.timeout(60):+ normalized = normalized_name(name)+ logo_url = ""+ if normalized in _BOOTSTRAP:+ title, domain, spec_url = _BOOTSTRAP[normalized]+ service_id = domain+ else:+ try:+ match = self._match(name, await self._catalog())+ except httpx.HTTPError:+ log.warning("Custom API directory unavailable; checking public documentation")+ match = None+ if match:+ service_id, version = match+ domain = service_id.partition(":")[0]+ info = version.get("info", {})+ title = re.sub(+ r"\s+(API\s*)?(Documentation|Reference)$",+ "",+ str(info.get("title") or name),+ flags=re.I,+ )+ origins = info.get("x-origin", [])+ if isinstance(origins, dict):+ origins = [origins]+ origin = next(+ (+ v.get("url")+ for v in origins+ if v.get("format") in {"openapi", "swagger"}+ and str(v.get("url", "")).startswith("https://")+ ),+ None,+ )+ spec_url = origin or version.get("swaggerUrl", "")+ logo_url = str(info.get("x-logo", {}).get("url", ""))+ else:+ title, domain, spec_url = await self._search_document(name)+ service_id = domain+ document = self._documents.pop(spec_url, None)+ actual_url = spec_url+ if document is None:+ raw, actual_url = await self._fetch(spec_url)+ document = await asyncio.to_thread(self._parse, raw)+ if document is None:+ raise ApiDiscoveryError("documentation_not_found")+ base_url = api_base_url(document, actual_url)+ if not same_service_host(urlsplit(base_url).hostname or "", domain):+ raise ApiDiscoveryError("service_address_mismatch")+ auth = api_auth(document)+ actions, categories, omitted = await asyncio.to_thread(+ compile_openapi, document, auth, base_url+ )+ logo = "" if normalized == "elevenlabs" else await self._logo(domain, logo_url)+ return ApiDefinition(+ name=title[:100],+ description=", ".join(categories)[:2000],+ base_url=base_url,+ auth=auth,+ actions=actions,+ enabled=True,+ connection=ApiConnectionInfo(+ service_id=service_id,+ website=f"https://{domain}",+ spec_url=actual_url,+ brand_id=domain.split(".")[0],+ logo_data=logo,+ categories=categories,+ omitted_operations=omitted,+ ),+ )diff --git a/jarvis/marketplace/custom_api_openapi.py b/jarvis/marketplace/custom_api_openapi.pynew file mode 100644index 0000000000..518b7bfd65--- /dev/null+++ b/jarvis/marketplace/custom_api_openapi.py@@ -0,0 +1,361 @@+"""Compile published OpenAPI operations into native, credential-free API actions."""++from __future__ import annotations++import hashlib+import re+from collections import Counter+from typing import Any+from urllib.parse import urljoin, urlsplit++from jarvis.marketplace.custom_api import ApiAction, ApiAuth, ApiParameter++METHODS = frozenset({"get", "post", "put", "patch", "delete", "head", "options"})+_SCHEMA_KEYS = frozenset(+ {+ "type",+ "properties",+ "required",+ "items",+ "enum",+ "const",+ "anyOf",+ "oneOf",+ "allOf",+ "additionalProperties",+ "minimum",+ "maximum",+ "exclusiveMinimum",+ "exclusiveMaximum",+ "minLength",+ "maxLength",+ "minItems",+ "maxItems",+ "pattern",+ "format",+ "description",+ "uniqueItems",+ "minProperties",+ "maxProperties",+ "not",+ }+)+++class OpenApiImportError(ValueError):+ """A document cannot safely describe a single-key HTTP service."""+++def dereference(document: dict[str, Any], value: Any) -> dict[str, Any]:+ """Resolve local object references without ever fetching a reference URL."""+ seen: set[str] = set()+ while isinstance(value, dict) and "$ref" in value:+ ref = value["$ref"]+ if not isinstance(ref, str) or not ref.startswith("#/") or ref in seen:+ raise OpenApiImportError("The API description contains an unsupported reference")+ seen.add(ref)+ target: Any = document+ try:+ for part in ref[2:].split("/"):+ target = target[part.replace("~1", "/").replace("~0", "~")]+ except (KeyError, TypeError):+ raise OpenApiImportError("The API description contains a missing reference") from None+ value = target+ return value if isinstance(value, dict) else {}+++def inline_schema(+ document: dict[str, Any],+ source: Any,+ *,+ depth: int = 0,+ seen: frozenset[str] = frozenset(),+ budget: list[int] | None = None,+) -> dict[str, Any]:+ """Bound recursive schemas, retain JSON constraints, omit documentation noise."""+ if budget is None:+ budget = [350]+ budget[0] -= 1+ if not isinstance(source, dict) or depth > 14 or budget[0] < 0:+ return {}+ ref = source.get("$ref")+ if ref:+ if ref in seen:+ return {+ "type": "object",+ "description": "Recursive object; use the service documentation",+ }+ seen = seen | {str(ref)}+ source = dereference(document, source)+ result: dict[str, Any] = {}+ for key, value in source.items():+ if key not in _SCHEMA_KEYS:+ continue+ if key == "properties":+ result[key] = {+ name: inline_schema(document, item, depth=depth + 1, seen=seen, budget=budget)+ for name, item in value.items()+ if not item.get("readOnly", False)+ }+ elif key in {"items", "not"} or (key == "additionalProperties" and isinstance(value, dict)):+ result[key] = inline_schema(document, value, depth=depth + 1, seen=seen, budget=budget)+ elif key in {"anyOf", "oneOf", "allOf"}:+ result[key] = [+ inline_schema(document, v, depth=depth + 1, seen=seen, budget=budget) for v in value+ ]+ elif key == "description":+ result[key] = re.sub(r"<[^>]+>", "", str(value))[:120]+ elif key in {"exclusiveMinimum", "exclusiveMaximum"} and isinstance(value, bool):+ if value:+ bound = "minimum" if key == "exclusiveMinimum" else "maximum"+ if bound in source:+ result[key] = source[bound]+ else:+ result[key] = value+ if source.get("nullable") and isinstance(result.get("type"), str):+ result["type"] = [result["type"], "null"]+ if "properties" in result and "required" in result:+ result["required"] = [n for n in result["required"] if n in result["properties"]]+ return result+++def api_base_url(document: dict[str, Any], source_url: str) -> str:+ servers = document.get("servers") or []+ if servers:+ server = servers[0]+ value = str(server.get("url", ""))+ for name, variable in server.get("variables", {}).items():+ value = value.replace("{" + name + "}", str(variable.get("default", "")))+ return urljoin(source_url, value).rstrip("/")+ if document.get("host"):+ if "https" not in document.get("schemes", ["https"]):+ raise OpenApiImportError("This API does not publish an HTTPS address")+ return "https://" + document["host"] + document.get("basePath", "").rstrip("/")+ parts = urlsplit(source_url)+ # FastAPI documents on the provider's API host commonly omit `servers`.+ if parts.hostname and parts.hostname.startswith("api.") and parts.hostname != "api.apis.guru":+ return f"https://{parts.netloc}"+ raise OpenApiImportError("The API description does not identify its service address")+++def _scheme_auth(document: dict[str, Any], source: Any) -> ApiAuth | None:+ scheme = dereference(document, source)+ if scheme.get("type") == "apiKey" and scheme.get("in") in {"header", "query"}:+ return ApiAuth(mode=scheme["in"], header_name=scheme["name"])+ if (+ scheme.get("type") == "http" and str(scheme.get("scheme")).lower() == "bearer"+ ) or scheme.get("type") in {"oauth2", "openIdConnect"}:+ return ApiAuth(mode="bearer")+ return None+++def api_auth(document: dict[str, Any]) -> ApiAuth:+ schemes = document.get("components", {}).get("securitySchemes", {}) or document.get(+ "securityDefinitions", {}+ )+ for source in schemes.values():+ auth = _scheme_auth(document, source)+ if auth is not None:+ return auth+ headers: Counter[str] = Counter()+ for item in document.get("paths", {}).values():+ for method, operation in item.items():+ if method not in METHODS:+ continue+ for value in [*item.get("parameters", []), *operation.get("parameters", [])]:+ parameter = dereference(document, value)+ name = str(parameter.get("name", ""))+ if parameter.get("in") == "header" and re.search(+ r"api[-_]?key|authorization|access[-_]?token", name, re.I+ ):+ headers[name] += 1+ if headers:+ name = headers.most_common(1)[0][0]+ return (+ ApiAuth(mode="bearer")+ if name.lower() == "authorization"+ else ApiAuth(mode="header", header_name=name)+ )+ raise OpenApiImportError("The published API does not describe how to send an API key")+++def _accepts_auth(document: dict[str, Any], operation: dict[str, Any], auth: ApiAuth) -> bool:+ requirements = operation.get("security", document.get("security", []))+ schemes = document.get("components", {}).get("securitySchemes", {}) or document.get(+ "securityDefinitions", {}+ )+ if not requirements:+ return True+ return any(+ not requirement+ or (+ len(requirement) == 1+ and _scheme_auth(document, schemes.get(next(iter(requirement)), {})) == auth+ )+ for requirement in requirements+ )+++def _action_id(method: str, path: str, operation: dict[str, Any]) -> str:+ label = re.sub(+ r"[^a-z0-9_]+", "_", str(operation.get("operationId") or f"{method}_{path}").lower()+ ).strip("_")+ if not label or not label[0].isalpha():+ label = "action_" + label+ digest = hashlib.sha256(f"{method} {path}".encode()).hexdigest()[:6]+ return label[:17] + "_" + digest+++def compile_openapi(+ document: dict[str, Any], auth: ApiAuth, base_url: str+) -> tuple[list[ApiAction], list[str], int]:+ """Import HTTP actions; return explicit unsupported-operation coverage."""+ actions: list[ApiAction] = []+ categories: set[str] = set()+ omitted = 0+ for path, path_source in document.get("paths", {}).items():+ item = dereference(document, path_source)+ for method, operation in item.items():+ if method not in METHODS:+ continue+ server_source = operation if operation.get("servers") else item+ if (+ server_source.get("servers") and api_base_url(server_source, base_url) != base_url+ ) or not _accepts_auth(document, operation, auth):+ omitted += 1+ continue+ parameters: dict[tuple[str, str], ApiParameter] = {}+ body_schema = None+ body_required = False+ file_fields: list[str] = []+ encoding = "json"+ content_type = "application/json"+ form_properties: dict[str, Any] = {}+ form_required: list[str] = []+ for value in [*item.get("parameters", []), *operation.get("parameters", [])]:+ param = dereference(document, value)+ location, name = param.get("in"), param.get("name", "")+ if location == "header" and name.lower() in {+ auth.header_name.lower(),+ "authorization",+ "content-type",+ "accept",+ }:+ continue+ if location == "query" and auth.mode == "query" and name == auth.header_name:+ continue+ schema = inline_schema(document, param.get("schema", param))+ if location == "body":+ body_schema = schema+ body_required = bool(param.get("required"))+ elif location == "formData":+ form_properties[name] = schema+ if param.get("type") == "file":+ form_properties[name] = {+ "type": "string",+ "description": "Absolute path of the file to upload",+ }+ file_fields.append(name)+ if param.get("required"):+ form_required.append(name)+ elif location in {"path", "query", "header"}:+ kind = schema.get("type", "string")+ if not isinstance(kind, str) or kind not in {+ "string",+ "integer",+ "number",+ "boolean",+ "array",+ "object",+ }:+ kind = "string"+ parameters[(location, name)] = ApiParameter(+ name=name,+ location=location,+ type=kind,+ required=bool(param.get("required")),+ value_schema=schema,+ description=str(param.get("description", ""))[:500],+ )+ body = dereference(document, operation.get("requestBody", {}))+ content = body.get("content", {})+ if content:+ body_required = bool(body.get("required"))+ content_type = next(+ (+ t+ for t in [+ "application/json",+ "multipart/form-data",+ "application/x-www-form-urlencoded",+ "application/octet-stream",+ ]+ if t in content+ ),+ "",+ )+ if not content_type:+ omitted += 1+ continue+ body_schema = inline_schema(document, content[content_type].get("schema", {}))+ encoding = {+ "multipart/form-data": "multipart",+ "application/x-www-form-urlencoded": "form",+ "application/octet-stream": "binary",+ }.get(content_type, "json")+ for name, prop in body_schema.get("properties", {}).items():+ variants = [prop, *prop.get("anyOf", []), prop.get("items", {})]+ if any(v.get("format") == "binary" for v in variants):+ file_fields.append(name)+ prop["description"] = (+ "Absolute local file path to upload (or a list of paths)"+ )+ if encoding == "binary":+ body_schema = {+ "type": "string",+ "description": "Absolute local file path to upload",+ }+ elif form_properties:+ body_required = bool(form_required)+ encoding = (+ "multipart"+ if file_fields+ or "multipart/form-data"+ in operation.get("consumes", document.get("consumes", []))+ else "form"+ )+ content_type = (+ "multipart/form-data"+ if encoding == "multipart"+ else "application/x-www-form-urlencoded"+ )+ body_schema = {+ "type": "object",+ "properties": form_properties,+ "required": form_required,+ }+ if method == "get":+ body_schema = None+ actions.append(+ ApiAction(+ id=_action_id(method, path, operation),+ method=method.upper(),+ path=path,+ description=str(+ operation.get("summary")+ or operation.get("description")+ or f"{method.upper()} {path}"+ )[:1500],+ parameters=list(parameters.values()),+ body_schema=body_schema,+ body_required=body_required,+ body_encoding=encoding,+ content_type=content_type,+ file_fields=file_fields,+ risk_tier="ask" if method == "delete" else "monitor",+ )+ )+ categories.update(str(tag) for tag in operation.get("tags", []) if tag)+ if not actions:+ raise OpenApiImportError("No usable HTTP operations were found in the API description")+ return actions, sorted(categories), omitteddiff --git a/jarvis/marketplace/custom_api_runtime.py b/jarvis/marketplace/custom_api_runtime.pyindex ae589d6cae..3f27840e4c 100644--- a/jarvis/marketplace/custom_api_runtime.py+++ b/jarvis/marketplace/custom_api_runtime.py@@ -19,6 +19,7 @@ from jarvis.core.http_guard import public_only_asyncfrom jarvis.core.http_pool import HttpClientPoolfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.marketplace.custom_api import ApiAction, ApiDefinition, CustomApiStore, validate_path+from jarvis.marketplace.custom_api_transport import QUERY_AUTH_EXTENSION, ApiTransport, encode_bodylog = logging.getLogger(__name__)MAX_RESPONSE_BYTES = 16 * 1024 * 1024@@ -89,6 +90,7 @@ class CustomApiTool:self.custom_api_id = definition.idself.custom_api_name = definition.nameself.custom_api_description = definition.description+ self.custom_api_brand = definition.connection.brand_id if definition.connection else ""self.display_name = f"{definition.name}: {action.description[:80]}"self.description = (f"[ACTION-ONLY · API: {definition.name}] {action.description} "@@ -100,7 +102,7 @@ class CustomApiTool:def describe_args(self, args: dict[str, Any]) -> dict[str, str]:return {- "level": "read" if self.action.method == "GET" else "modify",+ "level": "read" if self.action.method in {"GET", "HEAD", "OPTIONS"} else "modify","summary": f"{self.action.method} {self.definition.name}: {self.action.description}",}@@ -124,15 +126,47 @@ class CustomApiTool:path = path.replace("{" + name + "}", encoded)validate_path(path)headers = {"Accept": "*/*"}+ for name, value in args.get("header", {}).items():+ if name.lower() in {+ "host",+ "authorization",+ "cookie",+ "content-length",+ "connection",+ "transfer-encoding",+ "proxy-authorization",+ }:+ return ToolResult(+ False, None, "This request header is controlled by the connection"+ )+ headers[name] = str(value)if current.auth.mode == "bearer":headers["Authorization"] = f"Bearer {key}"elif current.auth.mode == "header":headers[current.auth.header_name] = key or ""query = {- k: str(v).lower() if isinstance(v, bool) else str(v)+ k: v+ if isinstance(v, list)+ else str(v).lower()+ if isinstance(v, bool)+ else json.dumps(v)+ if isinstance(v, dict)+ else str(v)for k, v in args.get("query", {}).items()+ if v is not None}- body = {"json": args["body"]} if "body" in args else {}+ extensions = (+ {QUERY_AUTH_EXTENSION: (current.auth.header_name, key)}+ if current.auth.mode == "query"+ else {}+ )+ body = (+ await asyncio.to_thread(encode_body, self.action, args["body"])+ if "body" in args+ else {}+ )+ if self.action.body_encoding == "binary":+ headers["Content-Type"] = self.action.content_type# No retries, including on timeout: an action may already have run.# No redirects: credentials stay on the exact configured origin.async with asyncio.timeout(60):@@ -141,6 +175,7 @@ class CustomApiTool:current.base_url + path,params=query,headers=headers,+ extensions=extensions,**body,) as response:if not 200 <= response.status_code < 300:@@ -212,6 +247,163 @@ class CustomApiTool:)+class CustomApiCatalogTool(CustomApiTool):+ """Discover any operation without flooding every model turn with schemas."""++ is_action_tool = False+ yields_instructions_only = True++ def __init__(+ self,+ definition: ApiDefinition,+ store: CustomApiStore,+ pool: HttpClientPool,+ output_dir: Path | None = None,+ ) -> None:+ super().__init__(+ definition,+ ApiAction(+ id="actions",+ path="/",+ description="Find available actions and inspect their input parameters",+ ),+ store,+ pool,+ output_dir,+ )+ self.risk_tier = "safe"+ self.description = (+ f"Discover {definition.name} actions. {definition.description[:1200]}. "+ "Search with query, then supply an action ID to get its input schema. "+ f"Execute it with api_{definition.id}_call. This lookup makes no provider request."+ )+ self.schema = {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Search by task, capability or operation name",+ },+ "action": {"type": "string", "description": "Exact action ID to inspect"},+ "offset": {"type": "integer", "minimum": 0, "default": 0},+ },+ "additionalProperties": False,+ }++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ from jsonschema import Draft202012Validator++ if not Draft202012Validator(self.schema).is_valid(args):+ return ToolResult(False, None, "Invalid action search")+ try:+ current = await asyncio.to_thread(self.store.get, self.definition.id)+ if current != self.definition or not current.enabled:+ return ToolResult(False, None, "API connection changed; reload its tools")+ if args.get("action"):+ action = next((a for a in current.actions if a.id == args["action"]), None)+ if action is None:+ return ToolResult(+ False, None, "Unknown action ID; search the available actions"+ )+ return ToolResult(+ True,+ {+ "id": action.id,+ "description": action.description,+ "input_schema": action.input_schema(),+ "risk_tier": action.risk_tier,+ "call_tool": f"api_{current.id}_call",+ },+ )+ words = str(args.get("query", "")).lower().split()+ actions = [+ a+ for a in current.actions+ if all(word in f"{a.id} {a.description} {a.path}".lower() for word in words)+ ]+ offset = int(args.get("offset", 0))+ return ToolResult(+ True,+ {+ "service": current.name,+ "total": len(actions),+ "next_offset": offset + 15 if len(actions) > offset + 15 else None,+ "actions": [+ {+ "id": a.id,+ "description": a.description,+ "method": a.method,+ "risk_tier": a.risk_tier,+ }+ for a in actions[offset : offset + 15]+ ],+ "instruction": "Use action=<id> to inspect arguments before calling",+ },+ )+ except (ValueError, OSError):+ log.warning("Custom API action catalog is unavailable for %s", self.definition.id)+ return ToolResult(False, None, "The connection's action catalog is unavailable")+++class CustomApiCallTool(CustomApiTool):+ def __init__(+ self,+ definition: ApiDefinition,+ store: CustomApiStore,+ pool: HttpClientPool,+ output_dir: Path | None = None,+ ) -> None:+ super().__init__(+ definition,+ ApiAction(+ id="call", path="/", description="Execute an action on this connected service"+ ),+ store,+ pool,+ output_dir,+ )+ self._actions = {a.id: a for a in definition.actions}+ self.description = (+ f"Use {definition.name}. {definition.description[:1200]}. "+ f"First find the operation and its arguments with api_{definition.id}_actions. "+ "Pass its exact ID as action and its path/query/body arguments as arguments. "+ "The connection supplies credentials; never ask for or pass an API key."+ )+ self.schema = {+ "type": "object",+ "properties": {+ "action": {"type": "string"},+ "arguments": {"type": "object"},+ },+ "required": ["action", "arguments"],+ "additionalProperties": False,+ }++ def risk_tier_for_args(self, args: dict[str, Any]) -> str:+ action = self._actions.get(str(args.get("action", "")))+ return action.risk_tier if action else "block"++ def describe_args(self, args: dict[str, Any]) -> dict[str, str]:+ action = self._actions.get(str(args.get("action", "")))+ description = action.description if action else "Unknown action"+ return {+ "level": "read" if action and action.method in {"GET", "HEAD", "OPTIONS"} else "modify",+ "summary": f"{self.definition.name}: {description}",+ }++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ from jsonschema import Draft202012Validator++ if not Draft202012Validator(self.schema).is_valid(args):+ return ToolResult(False, None, "Provide an action ID and its arguments")+ action = self._actions.get(args["action"])+ if action is None:+ return ToolResult(False, None, "Unknown action ID; inspect the available actions")+ return await CustomApiTool(+ self.definition, action, self.store, self.pool, self.output_dir+ ).execute(args["arguments"], ctx)++class CustomApiRuntime:"""Cached tool surface, with HTTP clients allocated only on first use."""@@ -229,6 +421,14 @@ class CustomApiRuntime:self._pools: dict[str, HttpClientPool] = {}self._lock = asyncio.Lock()self._stopped = False+ self._discovery: Any = None++ def discovery(self) -> Any:+ if self._discovery is None:+ from jarvis.marketplace.custom_api_discovery import ApiDiscovery++ self._discovery = ApiDiscovery()+ return self._discoveryasync def refresh(self) -> None:async with self._lock:@@ -247,7 +447,7 @@ class CustomApiRuntime:definition.id,HttpClientPool(timeout_s=45,- transport=self.transport,+ transport=ApiTransport(self.transport),client_kwargs={"follow_redirects": False,"trust_env": False,@@ -255,8 +455,17 @@ class CustomApiRuntime:},),)- for action in definition.actions:- tool = CustomApiTool(definition, action, self.store, pool, self.output_dir)+ if definition.connection is not None:+ available = [+ CustomApiCatalogTool(definition, self.store, pool, self.output_dir),+ CustomApiCallTool(definition, self.store, pool, self.output_dir),+ ]+ else:+ available = [+ CustomApiTool(definition, a, self.store, pool, self.output_dir)+ for a in definition.actions+ ]+ for tool in available:tools[tool.name] = toolregistry = get_registry()for name in self.tools:@@ -276,7 +485,7 @@ class CustomApiRuntime:),description=tool.description[:250],risk_tier=tool.risk_tier,- requires_evidence=True,+ requires_evidence=tool.is_action_tool,))self.tools = tools@@ -290,3 +499,5 @@ class CustomApiRuntime:for pool in self._pools.values():await pool.aclose()self._pools.clear()+ if self._discovery is not None:+ await self._discovery.close()diff --git a/jarvis/marketplace/custom_api_transport.py b/jarvis/marketplace/custom_api_transport.pynew file mode 100644index 0000000000..d4ef02ee77--- /dev/null+++ b/jarvis/marketplace/custom_api_transport.py@@ -0,0 +1,93 @@+"""Bounded upload encoding and query-key injection below HTTP request logging."""++from __future__ import annotations++import json+import mimetypes+from pathlib import Path+from typing import Any++import httpx++from jarvis.marketplace.custom_api import ApiAction++UPLOAD_LIMIT = 64 * 1024 * 1024+QUERY_AUTH_EXTENSION = "jarvis_api_query_auth"+++class ApiTransport(httpx.AsyncBaseTransport):+ """Keep query credentials off public request objects and HTTPX log lines."""++ def __init__(self, inner: Any = None) -> None:+ self._inner = inner++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ if self._inner is None:+ self._inner = httpx.AsyncHTTPTransport(trust_env=False)+ credential = request.extensions.pop(QUERY_AUTH_EXTENSION, None)+ if credential is None:+ return await self._inner.handle_async_request(request)+ name, value = credential+ private = httpx.Request(+ request.method,+ request.url.copy_set_param(name, value),+ headers=request.headers,+ stream=request.stream,+ extensions=request.extensions,+ )+ try:+ response = await self._inner.handle_async_request(private)+ response.request = request+ return response+ except httpx.RequestError as exc:+ exc.request = request+ raise+ finally:+ private.url = request.url++ async def aclose(self) -> None:+ if self._inner is not None:+ await self._inner.aclose()+++def _file(value: Any, remaining: int) -> tuple[str, bytes, str]:+ if not isinstance(value, str) or not Path(value).is_absolute():+ raise ValueError("Uploads require an absolute local file path")+ path = Path(value)+ if not path.is_file() or path.stat().st_size > remaining:+ raise ValueError("The upload is unavailable or exceeds the 64 MiB limit")+ with path.open("rb") as stream:+ content = stream.read(remaining + 1)+ if len(content) > remaining:+ raise ValueError("The upload exceeds the 64 MiB limit")+ return path.name, content, mimetypes.guess_type(path.name)[0] or "application/octet-stream"+++def encode_body(action: ApiAction, body: Any) -> dict[str, Any]:+ """File I/O is isolated by the caller's to_thread; all buffers are bounded."""+ if action.body_encoding == "json":+ return {"json": body}+ if action.body_encoding == "binary":+ return {"content": _file(body, UPLOAD_LIMIT)[1]}+ if not isinstance(body, dict):+ raise ValueError("This API expects named form fields")+ remaining = UPLOAD_LIMIT+ files = []+ fields: dict[str, Any] = {}+ for name, value in body.items():+ if name in action.file_fields:+ for item in value if isinstance(value, list) else [value]:+ if item is None:+ continue+ upload = _file(item, remaining)+ remaining -= len(upload[1])+ files.append((name, upload))+ elif value is not None:+ fields[name] = (+ json.dumps(value) if isinstance(value, (dict, list, bool)) else str(value)+ )+ if action.body_encoding == "form":+ return {"data": fields}+ # Force multipart even when this operation has only text form fields.+ files.extend((name, (None, value)) for name, value in fields.items())+ return {"files": files}diff --git a/jarvis/marketplace/custom_connector.py b/jarvis/marketplace/custom_connector.pynew file mode 100644index 0000000000..cab8ec3a3b--- /dev/null+++ b/jarvis/marketplace/custom_connector.py@@ -0,0 +1,625 @@+"""Custom connectors: any remote MCP server, added by its address.++A custom connector is the short way to a plugin. Instead of writing a+``plugin.json`` the owner types a name and the URL where an MCP server+accepts requests; this module asks that server how it wants to be signed in+to and turns the answer into an ordinary catalog entry:++* OAuth with Dynamic Client Registration -> ``hosted_mcp_oauth_dcr``, the+ same browser flow the shipped Notion and Linear entries use;+* a server that wants a key it cannot issue itself -> ``pat_paste``, checked+ with an MCP handshake instead of a REST "who am I" call;+* a server that answers without credentials -> ``hosted_mcp_open``.++The entry lands in the same override catalog an uploaded plugin uses, with+``source="local"``, so connect, disconnect, removal, the live tool registry,+the worker bridge and the composer's Add menu all treat it like any other+plugin. Nothing here keeps a second registry of its own.++Every request goes only to the address the owner typed. A redirect may not+leave that host, so a server cannot point the probe somewhere else, and plain+``http`` is accepted only for a server on this computer or the local network.+"""++from __future__ import annotations++import ipaddress+import json+import logging+import re+import unicodedata+from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from typing import Any, Literal+from urllib.parse import urlsplit, urlunsplit++import httpx++from jarvis.core.branding import PRODUCT_NAME+from jarvis.marketplace.catalog import PluginSpec++log = logging.getLogger(__name__)++ConnectorAuth = Literal["oauth", "token", "none"]+AuthChoice = Literal["auto", "oauth", "token", "none"]+Transport = Literal["http", "sse"]++#: The category every custom connector is filed under. Not part of+#: ``CATEGORY_ORDER``: the store appends categories it does not know.+CUSTOM_CATEGORY = "Custom"+#: The ``source`` an entry the owner added here carries (same as an upload).+LOCAL_SOURCE = "local"++_PROBE_TIMEOUT_S = 10.0+_MAX_REDIRECTS = 3+# Enough for an initialize result; an SSE reply that never ends is cut here.+_MAX_BODY_BYTES = 64 * 1024+_HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,63}$")+# Headers the transport owns. Letting a key ride in one of them would either+# be overwritten silently or break the request.+_RESERVED_HEADERS = frozenset(+ {+ "accept",+ "connection",+ "content-length",+ "content-type",+ "cookie",+ "host",+ "mcp-protocol-version",+ "mcp-session-id",+ "transfer-encoding",+ }+)+_LOCAL_SUFFIXES = (".localhost", ".local", ".lan", ".home.arpa", ".internal")+_PROTOCOL_VERSION = "2025-06-18"+++class ConnectorError(ValueError):+ """A sentence for the owner: what is wrong with this address and why."""+++@dataclass(frozen=True)+class ConnectorProbe:+ """What one handshake attempt learned about a server."""++ #: How the server wants to be signed in to, or ``none`` when it answered.+ auth: ConnectorAuth+ transport: Transport+ #: HTTP status of the decisive response.+ status: int+ #: RFC 9728 / RFC 8414 document the OAuth flow starts from.+ discovery_url: str | None = None+ #: False when the server signs in with OAuth but offers no Dynamic Client+ #: Registration, which a connector without a pre-registered client needs.+ registration: bool = True+ #: ``serverInfo.name`` from the initialize result, when the server answered.+ server_name: str | None = None+++# ----------------------------------------------------------------------+# Address and identity+# ----------------------------------------------------------------------+++def _is_local_host(host: str) -> bool:+ name = host.strip("[]").lower()+ if name == "localhost" or name.endswith(_LOCAL_SUFFIXES):+ return True+ try:+ ip = ipaddress.ip_address(name.split("%", 1)[0])+ except ValueError:+ # A single-label name ("nas", "homeassistant") only resolves on the+ # local network; anything with a dot is treated as public.+ return "." not in name+ return ip.is_loopback or ip.is_private or ip.is_link_local+++def normalize_connector_url(raw: str) -> str:+ """The canonical form of an address the owner typed, or a ConnectorError."""+ text = (raw or "").strip()+ if not text:+ raise ConnectorError("Enter the address of the MCP server.")+ if "://" not in text:+ text = "https://" + text+ try:+ parts = urlsplit(text)+ port = parts.port+ except ValueError as exc:+ raise ConnectorError("This is not a valid web address.") from exc+ scheme = parts.scheme.lower()+ if scheme not in ("https", "http"):+ raise ConnectorError("Use an https:// address.")+ if parts.username or parts.password:+ raise ConnectorError(+ "Leave the user name and password out of the address. "+ f"{PRODUCT_NAME} asks for sign-in details when you connect."+ )+ host = (parts.hostname or "").lower()+ if not host:+ raise ConnectorError("The address has no server name.")+ if scheme == "http" and not _is_local_host(host):+ raise ConnectorError(+ "Use an https:// address. Plain http is only accepted for a server "+ "on this computer or your local network."+ )+ netloc = f"[{host}]" if ":" in host else host+ if port is not None:+ netloc = f"{netloc}:{port}"+ return urlunsplit((scheme, netloc, parts.path or "/", parts.query, ""))+++def _slug(text: str) -> str:+ folded = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")+ slug = re.sub(r"[^a-z0-9]+", "-", folded.lower()).strip("-")+ return slug[:48].strip("-")+++def connector_id(name: str, url: str, taken: Iterable[str]) -> str:+ """A catalog id for a new connector that collides with nothing in ``taken``.++ Built from the display name, or the server's host when the name holds no+ usable characters. Tool names become ``<id>/<tool>``, so the id stays in+ the lowercase ``a-z 0-9 -`` alphabet the rest of the catalog uses.+ """+ host = (urlsplit(url).hostname or "").removeprefix("www.").removeprefix("mcp.")+ base = _slug(name) or _slug(host.split(".")[0]) or "connector"+ used = set(taken)+ if base not in used:+ return base+ n = 2+ while f"{base}-{n}" in used:+ n += 1+ return f"{base}-{n}"+++def display_name_for(name: str, url: str, probe: ConnectorProbe | None = None) -> str:+ """The name the owner typed, else the server's own, else its host."""+ typed = " ".join((name or "").split())[:80]+ if typed:+ return typed+ if probe is not None and probe.server_name:+ return probe.server_name.strip()[:80]+ host = (urlsplit(url).hostname or "connector").removeprefix("www.").removeprefix("mcp.")+ return host.split(".")[0].replace("-", " ").title() or "Connector"+++def normalize_header_name(raw: str | None) -> str:+ """The header a token travels in; ``Authorization`` (Bearer) by default."""+ name = (raw or "").strip() or "Authorization"+ if not _HEADER_NAME_RE.fullmatch(name):+ raise ConnectorError("A header name may only hold letters, digits and dashes.")+ if name.lower() in _RESERVED_HEADERS:+ raise ConnectorError(f"{name} is set by the connection itself; choose another header.")+ return name+++def _header_template(plugin_id: str, header_name: str) -> str:+ placeholder = f"${{plugin_{plugin_id}_access_token}}"+ if header_name.lower() == "authorization":+ return f"Authorization: Bearer {placeholder}"+ return f"{header_name}: {placeholder}"+++# ----------------------------------------------------------------------+# Probe+# ----------------------------------------------------------------------+++def _initialize_body() -> dict[str, Any]:+ return {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": _PROTOCOL_VERSION,+ "capabilities": {},+ "clientInfo": {"name": PRODUCT_NAME, "version": "1.0"},+ },+ }+++def _same_host_only(origin_host: str):+ """Response hook: a redirect may change the path, never the host."""++ async def _check(response: httpx.Response) -> None:+ if not response.has_redirect_location:+ return+ location = response.headers.get("location") or ""+ target = response.url.join(location)+ if (target.host or "").lower() != origin_host or (+ response.url.scheme == "https" and target.scheme != "https"+ ):+ raise ConnectorError(+ "The server redirected to a different address. Enter the final "+ "MCP address instead."+ )++ return _check+++async def _read_limited(response: httpx.Response) -> bytes:+ """Body bytes up to the cap; an SSE reply stops after its first event."""+ chunks: list[bytes] = []+ size = 0+ streaming = "text/event-stream" in response.headers.get("content-type", "")+ async for chunk in response.aiter_bytes():+ chunks.append(chunk)+ size += len(chunk)+ if size >= _MAX_BODY_BYTES:+ break+ if streaming and b"\n\n" in b"".join(chunks).replace(b"\r\n", b"\n"):+ break+ return b"".join(chunks)[:_MAX_BODY_BYTES]+++def _jsonrpc_payload(body: bytes, content_type: str) -> Mapping[str, Any] | None:+ """The JSON-RPC message in a JSON or SSE initialize reply, if there is one."""+ text = body.decode("utf-8", "replace")+ candidates: list[str] = []+ if "text/event-stream" in content_type:+ candidates = [+ line[5:].strip()+ for line in text.replace("\r\n", "\n").split("\n")+ if line.startswith("data:")+ ]+ else:+ candidates = [text]+ for candidate in candidates:+ try:+ parsed = json.loads(candidate)+ except ValueError: # not JSON: try the next SSE data line+ continue+ if isinstance(parsed, Mapping) and parsed.get("jsonrpc") == "2.0":+ return parsed+ return None+++def _resource_metadata_hint(www_authenticate: str) -> str | None:+ match = re.search(r'resource_metadata\s*=\s*"([^"]+)"', www_authenticate or "")+ return match.group(1) if match else None+++def _well_known(url: str, suffix: str) -> list[str]:+ """RFC 9728/8414 locations for ``url``: path-inserted first, then the root."""+ parts = urlsplit(url)+ path = parts.path.rstrip("/")+ out = []+ if path:+ out.append(urlunsplit((parts.scheme, parts.netloc, f"/.well-known/{suffix}{path}", "", "")))+ out.append(urlunsplit((parts.scheme, parts.netloc, f"/.well-known/{suffix}", "", "")))+ return out+++async def _get_json(client: httpx.AsyncClient, url: str) -> Mapping[str, Any] | None:+ try:+ response = await client.get(url, headers={"Accept": "application/json"})+ except ConnectorError:+ raise+ except httpx.HTTPError as exc:+ log.debug("custom connector: %s unreadable: %s", url, type(exc).__name__)+ return None+ if response.status_code != 200:+ return None+ try:+ parsed = response.json()+ except ValueError: # a non-JSON answer is not an MCP endpoint+ return None+ return parsed if isinstance(parsed, Mapping) else None+++def _is_auth_server(meta: Mapping[str, Any] | None) -> bool:+ return bool(+ meta+ and isinstance(meta.get("authorization_endpoint"), str)+ and isinstance(meta.get("token_endpoint"), str)+ )+++async def _discover_oauth(+ client: httpx.AsyncClient, url: str, www_authenticate: str+) -> tuple[str, bool] | None:+ """``(discovery_url, has_registration)`` when the server signs in with OAuth.++ Follows the MCP authorization spec: the 401's ``resource_metadata`` hint+ first, then the protected-resource well-known locations, then the older+ servers that publish only authorization-server metadata on their host.+ The discovery URL handed back is exactly what ``HostedMcpDcrHandler``+ starts from, so the probe and the later sign-in read the same document.+ """+ from jarvis.marketplace.auth.oauth_dcr import _well_known_candidates++ host = (urlsplit(url).hostname or "").lower()+ candidates: list[str] = []+ hint = _resource_metadata_hint(www_authenticate)+ if hint and (urlsplit(hint).hostname or "").lower() == host:+ candidates.append(hint)+ candidates += [c for c in _well_known(url, "oauth-protected-resource") if c not in candidates]++ for candidate in candidates:+ meta = await _get_json(client, candidate)+ if meta is None:+ continue+ if _is_auth_server(meta):+ return candidate, bool(meta.get("registration_endpoint"))+ servers = meta.get("authorization_servers")+ if not isinstance(servers, list) or not servers or not isinstance(servers[0], str):+ continue+ for as_url in _well_known_candidates(servers[0]):+ as_meta = await _get_json(client, as_url)+ if _is_auth_server(as_meta):+ return candidate, bool(as_meta and as_meta.get("registration_endpoint"))+ # The resource names an auth server nobody can read: the sign-in flow+ # would fail the same way, so say OAuth without registration.+ return candidate, False++ for candidate in _well_known(url, "oauth-authorization-server"):+ meta = await _get_json(client, candidate)+ if _is_auth_server(meta):+ return candidate, bool(meta and meta.get("registration_endpoint"))+ return None+++async def _auth_probe(+ client: httpx.AsyncClient, url: str, response: httpx.Response, transport: Transport+) -> ConnectorProbe:+ found = await _discover_oauth(client, url, response.headers.get("www-authenticate", ""))+ if found is None:+ return ConnectorProbe(auth="token", transport=transport, status=response.status_code)+ discovery_url, registration = found+ return ConnectorProbe(+ auth="oauth",+ transport=transport,+ status=response.status_code,+ discovery_url=discovery_url,+ registration=registration,+ )+++async def _end_session(client: httpx.AsyncClient, url: str, response: httpx.Response) -> None:+ """Close the session a successful initialize opened. Best effort only."""+ session = response.headers.get("mcp-session-id")+ if not session:+ return+ try:+ await client.delete(url, headers={"Mcp-Session-Id": session})+ except (httpx.HTTPError, ConnectorError) as exc:+ # The server times the session out on its own; a probe never waits.+ log.debug("custom connector: session close skipped: %s", type(exc).__name__)+++def _web_page() -> ConnectorError:+ return ConnectorError(+ "This address shows a web page, not an MCP server. Use the address the "+ "provider gives for MCP; it often ends in /mcp."+ )+++def _unexpected_status(status: int) -> ConnectorError:+ return ConnectorError(+ f"The server answered HTTP {status}. Check that this is the address "+ "where it accepts MCP requests; it often ends in /mcp."+ )+++async def probe_connector(+ url: str,+ *,+ headers: Mapping[str, str] | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+) -> ConnectorProbe:+ """Send one MCP ``initialize`` to ``url`` and report what the server wants.++ With ``headers`` the probe doubles as a credential check: a server that+ answers reports ``auth="none"``, one that refuses reports what it asks+ for instead. Raises ``ConnectorError`` with a readable sentence when the+ address is unreachable or does not speak MCP.+ """+ host = (urlsplit(url).hostname or "").lower()+ request_headers = {+ "Accept": "application/json, text/event-stream",+ "Content-Type": "application/json",+ "User-Agent": f"{PRODUCT_NAME}/1.0",+ **dict(headers or {}),+ }+ try:+ async with httpx.AsyncClient(+ timeout=_PROBE_TIMEOUT_S,+ follow_redirects=True,+ max_redirects=_MAX_REDIRECTS,+ transport=transport,+ event_hooks={"response": [_same_host_only(host)]},+ ) as client:+ async with client.stream(+ "POST", url, json=_initialize_body(), headers=request_headers+ ) as response:+ status = response.status_code+ content_type = response.headers.get("content-type", "").lower()+ body = await _read_limited(response) if 200 <= status < 300 else b""+ if 200 <= status < 300:+ message = _jsonrpc_payload(body, content_type)+ if message is None:+ if "text/html" in content_type:+ raise _web_page()+ raise ConnectorError("The server answered, but not with an MCP handshake.")+ await _end_session(client, url, response)+ if isinstance(message.get("error"), Mapping):+ reason = str(message["error"].get("message", ""))[:200]+ raise ConnectorError(f"The server refused the MCP handshake: {reason}")+ result = message.get("result")+ info = result.get("serverInfo") if isinstance(result, Mapping) else None+ name = info.get("name") if isinstance(info, Mapping) else None+ return ConnectorProbe(+ auth="none",+ transport="http",+ status=status,+ server_name=name if isinstance(name, str) and name.strip() else None,+ )+ if status in (401, 403):+ return await _auth_probe(client, url, response, "http")+ if status in (404, 405, 406):+ # Older servers speak the HTTP+SSE transport: the address is a+ # GET event stream, and POSTs go elsewhere.+ return await _probe_sse(client, url, dict(headers or {}))+ raise _unexpected_status(status)+ except ConnectorError:+ raise+ except httpx.TooManyRedirects as exc:+ raise ConnectorError("The server redirects in a loop.") from exc+ except httpx.TimeoutException as exc:+ seconds = int(_PROBE_TIMEOUT_S)+ raise ConnectorError(f"{host} did not answer within {seconds} seconds.") from exc+ except httpx.HTTPError as exc:+ raise ConnectorError(+ f"{PRODUCT_NAME} could not reach {host}. Check the address and your connection."+ ) from exc+++async def _probe_sse(+ client: httpx.AsyncClient, url: str, headers: dict[str, str]+) -> ConnectorProbe:+ async with client.stream(+ "GET",+ url,+ headers={"Accept": "text/event-stream", "User-Agent": f"{PRODUCT_NAME}/1.0", **headers},+ ) as response:+ status = response.status_code+ content_type = response.headers.get("content-type", "").lower()+ if status == 200 and "text/event-stream" in content_type:+ return ConnectorProbe(auth="none", transport="sse", status=status)+ if status in (401, 403):+ return await _auth_probe(client, url, response, "sse")+ if status == 200 and "text/html" in content_type:+ raise _web_page()+ raise _unexpected_status(status)+++# ----------------------------------------------------------------------+# Decision and catalog entry+# ----------------------------------------------------------------------+++def resolve_auth(choice: AuthChoice, probe: ConnectorProbe) -> ConnectorAuth:+ """The sign-in the connector will use, given the owner's pick and the probe."""+ if choice == "auto":+ if probe.auth == "oauth" and not probe.registration:+ raise ConnectorError(+ "This server signs in with OAuth but does not let new apps register "+ "themselves, so a custom connector cannot complete its sign-in. If the "+ "provider offers an API key or access token, choose \"Access token\" "+ "under Advanced settings."+ )+ return probe.auth+ if choice == "oauth":+ if probe.auth == "none":+ raise ConnectorError(+ "This server answered without any sign-in, so there is no OAuth "+ "login to start. Choose \"Detect automatically\"."+ )+ if probe.auth != "oauth":+ raise ConnectorError("This server publishes no OAuth sign-in. Try \"Access token\".")+ if not probe.registration:+ return resolve_auth("auto", probe)+ return "oauth"+ if choice == "none" and probe.auth != "none":+ raise ConnectorError(+ "This server asks for sign-in before it answers. Choose \"Detect "+ "automatically\" or \"Access token\"."+ )+ return choice+++def build_connector_spec(+ *,+ plugin_id: str,+ display_name: str,+ url: str,+ auth: ConnectorAuth,+ probe: ConnectorProbe,+ header_name: str = "Authorization",+) -> PluginSpec:+ """The catalog entry for a custom connector."""+ host = urlsplit(url).hostname or url+ mcp_server: dict[str, Any] = {"transport": probe.transport, "url": url}+ if auth == "oauth":+ auth_block: dict[str, Any] = {+ "mode": "hosted_mcp_oauth_dcr",+ "discovery_url": probe.discovery_url,+ "mcp_url": url,+ "refresh_supported": True,+ }+ mcp_server["auth_header_template"] = _header_template(plugin_id, "Authorization")+ longevity = "self_renewing"+ elif auth == "token":+ header_label = (+ "Authorization header (as a Bearer token)"+ if header_name.lower() == "authorization"+ else f"{header_name} header"+ )+ auth_block = {+ "mode": "pat_paste",+ # No page is known that issues the key; the dialog hides the link.+ "token_creation_url": "",+ "token_prefix": "",+ "validation_endpoint": url,+ "validation_method": "mcp_initialize",+ "instruction_md": (+ f"Use the API key or access token the provider of {display_name} "+ f"gave you. {PRODUCT_NAME} sends it in the {header_label}."+ ),+ }+ mcp_server["auth_header_template"] = _header_template(plugin_id, header_name)+ longevity = "permanent"+ else:+ auth_block = {"mode": "hosted_mcp_open", "mcp_url": url}+ longevity = "permanent"+ return PluginSpec.model_validate(+ {+ "id": plugin_id,+ "display_name": display_name,+ "description": f"MCP server at {host}",+ "category": CUSTOM_CATEGORY,+ "source": LOCAL_SOURCE,+ "logo_slug": "",+ "featured": False,+ "longevity": longevity,+ "auth": auth_block,+ "mcp_server": mcp_server,+ }+ )+++def connector_url(spec: PluginSpec) -> str | None:+ """The server address of a catalog entry, for duplicate checks."""+ mcp = spec.mcp_server or {}+ url = mcp.get("url")+ return str(url) if isinstance(url, str) and url else None+++def connector_auth_headers(spec: PluginSpec, token: str) -> dict[str, str]:+ """The header a pasted token travels in, built from the entry's template."""+ from jarvis.marketplace.mcp_bridge import _resolve_placeholders, _token_replacements++ template = (spec.mcp_server or {}).get("auth_header_template")+ if not template:+ return {"Authorization": f"Bearer {token}"}+ resolved = _resolve_placeholders(str(template), _token_replacements(spec.id, token))+ key, sep, value = resolved.partition(":")+ return {key.strip(): value.strip()} if sep else {}+++__all__ = [+ "CUSTOM_CATEGORY",+ "AuthChoice",+ "ConnectorAuth",+ "ConnectorError",+ "ConnectorProbe",+ "build_connector_spec",+ "connector_auth_headers",+ "connector_id",+ "connector_url",+ "display_name_for",+ "normalize_connector_url",+ "normalize_header_name",+ "probe_connector",+ "resolve_auth",+]diff --git a/jarvis/marketplace/mcp_bridge.py b/jarvis/marketplace/mcp_bridge.pyindex 77aff6b764..5b50d6f244 100644--- a/jarvis/marketplace/mcp_bridge.py+++ b/jarvis/marketplace/mcp_bridge.py@@ -12,7 +12,8 @@ spec + token into a claude-cli `mcpServers` entry:* ``transport: "stdio"`` -> ``{"command", "args", "env"}`` (token resolvedinto the env_template / argv placeholders).* ``transport: "http"`` -> ``{"type": "http", "url", "headers"}`` (token- resolved into the Authorization bearer header).+ resolved into the Authorization bearer header); ``"sse"`` likewise with+ ``"type": "sse"``.* ``transport: "rest_wrapper"`` (or anything else) -> skipped: it is not areal MCP server claude-cli can speak to.@@ -69,7 +70,8 @@ def _http_entry(spec: dict[str, Any], repl: dict[str, str]) -> dict[str, Any] |url = spec.get("url")if not url:return None- entry: dict[str, Any] = {"type": "http", "url": str(url)}+ kind = "sse" if str(spec.get("transport") or "").lower() == "sse" else "http"+ entry: dict[str, Any] = {"type": kind, "url": str(url)}header_template = spec.get("auth_header_template")if header_template:resolved = _resolve_placeholders(str(header_template), repl)@@ -117,10 +119,10 @@ def assemble_claude_mcp_servers(entry.setdefault("env", {})["JARVIS_CONNECTOR_AUTH_TYPE"] = ("oauth" if tokens.extra.get("client_id") else "pat")- elif transport == "http":+ elif transport in ("http", "sse"):entry = _http_entry(spec, repl)else:- # rest_wrapper / sse / unknown -> not a claude-cli MCP server+ # rest_wrapper / unknown -> not a claude-cli MCP serverentry = Noneif entry is not None:diff --git a/jarvis/marketplace/plugin_mcp.py b/jarvis/marketplace/plugin_mcp.pyindex cf79aab06a..f82d5dc90b 100644--- a/jarvis/marketplace/plugin_mcp.py+++ b/jarvis/marketplace/plugin_mcp.py@@ -23,8 +23,9 @@ def plugin_to_mcp_server_spec("""Return (MCPServerSpec, env_overrides) for a connected plugin, or None.None when the plugin has no mcp_server block or an MCP-incompatible- transport (rest_wrapper / unknown). stdio + http are supported — the same- two transports the worker bridge speaks.+ transport (rest_wrapper / unknown). stdio, http and sse are supported —+ the same transports the worker bridge speaks; sse only reaches older+ remote servers a custom connector was pointed at."""spec = plugin.mcp_serverif not spec:@@ -32,7 +33,7 @@ def plugin_to_mcp_server_spec(repl = _token_replacements(plugin.id, tokens.access)transport = str(spec.get("transport") or "").lower()- if transport == "http":+ if transport in ("http", "sse"):url = spec.get("url")if not url:return None@@ -48,7 +49,7 @@ def plugin_to_mcp_server_spec(display=plugin.display_name,description=plugin.description,install_command=[],- transport="http",+ transport="sse" if transport == "sse" else "http",url=str(url),headers=headers,)diff --git a/jarvis/mcp/client.py b/jarvis/mcp/client.pyindex 2b428913d2..d223d17df8 100644--- a/jarvis/mcp/client.py+++ b/jarvis/mcp/client.py@@ -189,10 +189,19 @@ class MCPClient:elif self.spec.transport == "sse":from mcp.client.sse import sse_client- command, args, _env = self._resolve_install_command()- # install_command for SSE transport = [url] (by convention)- url = args[0] if args else command- read, write = await stack.enter_async_context(sse_client(url))+ headers: dict[str, str] = {}+ if self.spec.url:+ # Marketplace connectors name the stream and its auth+ # header the same way an http server does.+ url = self.spec.url+ headers = self._resolve_headers()+ else:+ command, args, _env = self._resolve_install_command()+ # install_command for SSE transport = [url] (by convention)+ url = args[0] if args else command+ read, write = await stack.enter_async_context(+ sse_client(url, headers=headers or None)+ )elif self.spec.transport == "http":from mcp.client.streamable_http import streamablehttp_clientdiff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.pyindex 7b17062087..87142d3cec 100644--- a/jarvis/platform/open_path.py+++ b/jarvis/platform/open_path.py@@ -274,19 +274,18 @@ def _open_url_windows(url: str) -> bool:URL in the browser's normal, visible profile. Falls back across candidates andfinally to ShellExecute. Returns True once a launcher is dispatched."""- host = urlparse(url).netloc+ host = urlparse(url).hostnamefor exe in _windows_browser_candidates():try:subprocess.Popen( # noqa: S603[exe, url], creationflags=NO_WINDOW_CREATIONFLAGS, close_fds=True)- # Log only scheme://host at INFO — the full URL carries the OAuth- # ``state`` (a CSRF token) and ephemeral redirect_uri; keep it at DEBUG.+ # Never log URL credentials, including one-time pairing fragments.log.info("open_url: launched %s -> %s", exe, host)- log.debug("open_url: full URL %s", url)+ log.debug("open_url: browser launch completed")return Trueexcept OSError as exc:- log.warning("open_url: %s failed (%s); trying next candidate", exe, exc)+ log.warning("open_url: %s failed (%s); trying next candidate", exe, type(exc).__name__)continue# Last resort: hand the URL to the OS association. It may be a UWP handler with# no classic exe — but it is also the path that silently opens nothing for a@@ -299,7 +298,7 @@ def _open_url_windows(url: str) -> bool:)return True # best-effort; ShellExecute may open nothing for a dead handlerexcept OSError as exc:- log.warning("open_url: ShellExecute fallback failed for %s: %s", host, exc)+ log.warning("open_url: ShellExecute fallback failed for %s: %s", host, type(exc).__name__)return False@@ -345,7 +344,7 @@ def _run_opener_checked(argv: list[str]) -> bool:capture_output=True,)except (OSError, subprocess.TimeoutExpired) as exc:- log.warning("open_url: opener %r failed: %s", argv[0], exc)+ log.warning("open_url: opener %r failed: %s", argv[0], type(exc).__name__)return Falsereturn proc.returncode == 0@@ -355,10 +354,10 @@ def _open_url_macos(url: str) -> bool:``open -a <App>`` fallbacks if the default association is broken. See:func:`open_url`. Honest: returns False if nothing opened."""- host = urlparse(url).netloc+ host = urlparse(url).hostnameif _run_opener_checked(["open", url]):log.info("open_url: macOS launched default browser -> %s", host)- log.debug("open_url: full URL %s", url)+ log.debug("open_url: browser launch completed")return Truefor app in _MACOS_BROWSER_APPS:if _run_opener_checked(["open", "-a", app, url]):@@ -375,10 +374,10 @@ def _open_url_linux(url: str) -> bool:opened. The direct-binary launch is fire-and-forget (the browser keeps running)so it mirrors the Windows direct launch — success means the process started."""- host = urlparse(url).netloc+ host = urlparse(url).hostnameif _run_opener_checked(["xdg-open", url]):log.info("open_url: Linux launched default browser -> %s", host)- log.debug("open_url: full URL %s", url)+ log.debug("open_url: browser launch completed")return Truefor binname in _LINUX_BROWSER_BINS:exe = shutil.which(binname)@@ -391,7 +390,7 @@ def _open_url_linux(url: str) -> bool:log.info("open_url: Linux opened via %s -> %s", binname, host)return Trueexcept OSError as exc:- log.warning("open_url: %s failed (%s); trying next", binname, exc)+ log.warning("open_url: %s failed (%s); trying next", binname, type(exc).__name__)continuelog.warning("open_url: Linux found no browser to open %s", host)return Falsediff --git a/jarvis/plugins/brain/ollama.py b/jarvis/plugins/brain/ollama.pyindex a9f123a7e9..2d6687038f 100644--- a/jarvis/plugins/brain/ollama.py+++ b/jarvis/plugins/brain/ollama.py@@ -173,6 +173,15 @@ class OllamaBrain:# image path so one turn never probes the same download twice.self._caps_cache: dict[str, set[str] | None] = {}self.supports_vision = _declared_vision_support(self._model)+ if self._model:+ from jarvis.brain.model_catalog import model_capabilities++ self.supports_tools = model_capabilities("ollama", self._model)["tools"] is not False+ # Tool fitting and history compaction happen before complete().+ # Publish an explicit local context limit before either budgets.+ options = self._model_options(self._model)+ if options is not None and options.num_ctx:+ self.context_window = options.num_ctxdef can_call_tools(self) -> bool:return self.supports_tools@@ -206,6 +215,7 @@ class OllamaBrain:api_key=self._credential or "ollama",base_url=f"{root}/v1",timeout=CLIENT_TIMEOUT,+ max_retries=0,)return self._client@@ -231,6 +241,16 @@ class OllamaBrain:always overrides this."""if self._model:+ if need_tools:+ caps = await self._capabilities(self._model, self._resolve_root())+ if caps is not None:+ self.supports_tools = "tools" in caps+ if not self.supports_tools:+ raise RuntimeError(+ f"The selected Ollama model '{self._model}' does not support tools. "+ "Choose a tool-capable model for this agent. "+ "No other provider was called."+ )return self._modelprofile = (need_tools, need_vision)if profile in self._discovered:@@ -248,12 +268,15 @@ class OllamaBrain:f"Ollama not reachable at {root} — is it running? Start it ""(or install from https://ollama.com/download), then retry.") from exc+ from jarvis.brain.ollama_inventory import is_hidden_alias+local = [mfor m in modelsif (name := str(m.get("name") or "").strip())and not name.endswith(":cloud")and not m.get("remote")+ and not is_hidden_alias(name)]if not local:raise RuntimeError(@@ -287,7 +310,11 @@ class OllamaBrain:)return nameif need_vision:- self.supports_vision = False+ if any(str(row.get("name")).strip() not in self._caps_cache for row in local):+ raise RuntimeError(+ "Ollama could not report image capabilities for the downloaded models. "+ "Check the server connection and retry; no image was sent to a model."+ )raise RuntimeError(f"None of the models downloaded at {root} can see images — run: "f"ollama pull {RECOMMENDED_VISION_PULL} (a multimodal model), "@@ -324,9 +351,11 @@ class OllamaBrain:caps = resp.json().get("capabilities")if isinstance(caps, list):caps_set = {str(c) for c in caps}- except Exception: # noqa: BLE001 — probe glitch must not block the pick+ except Exception: # noqa: BLE001 — retry unavailable metadata on the next turn+ log.debug("ollama: capability lookup failed for %s", name, exc_info=True)caps_set = None- self._caps_cache[name] = caps_set+ if caps_set is not None:+ self._caps_cache[name] = caps_setreturn caps_setasync def _pinned_model_can_see(self, model: str) -> bool:@@ -351,7 +380,16 @@ class OllamaBrain:# silently swap it — but we also refuse to answer about a picture# it never saw. The caller degrades honestly (Screen Context says# it cannot look; the CU planner skips this brain).- self.supports_vision = False+ # An unavailable probe says nothing about model capabilities.+ # Keep the provider eligible for a later retry after recovery.+ caps = self._caps_cache.get(model)+ if caps is None:+ raise RuntimeError(+ "Ollama could not verify this model's image capability. "+ "Check the server connection and retry; no image was sent to the model."+ )+ if caps is not None:+ self.supports_vision = "vision" in capsraise RuntimeError(f"The configured Ollama model '{model}' cannot see images. Pick a "f"multimodal model on the Ollama card (ollama pull "@@ -390,7 +428,9 @@ class OllamaBrain:return Noneif provider is None:return None- return provider.models.get(model) or provider.models.get(f"{model}:latest")+ return (provider.models.get(model)+ or provider.models.get(model.removesuffix(":latest"))+ or provider.models.get(f"{model}:latest"))async def _apply_model_options(self, model: str, req: BrainRequest) -> tuple[str, BrainRequest]:"""Turn the per-model options into ``(model to stream, request)``.diff --git a/jarvis/society/companion.py b/jarvis/society/companion.pyindex 064fb5cc57..28590e5c10 100644--- a/jarvis/society/companion.py+++ b/jarvis/society/companion.py@@ -13,6 +13,10 @@ AccessoryId = Annotated[str, StringConstraints(pattern=r"^[a-z0-9_]{1,40}$")]# for a drawn one). Open-ended like accessory ids: a pet deleted later or# missing on another machine shows the shape instead, it never breaks the look.PetId = Annotated[str, StringConstraints(pattern=r"^[a-z0-9][a-z0-9-]{0,31}$")]+HexColor = Annotated[str, StringConstraints(pattern=r"^#[0-9a-fA-F]{6}$")]+# Effect ids stay open like accessory ids: a design saved by a newer build keeps+# its colours in an older one, which simply draws no effect it does not know.+SkinEffect = Annotated[str, StringConstraints(pattern=r"^[a-z]{1,20}$")]#: Mirrors ``COMPANION_SHAPES`` / ``COMPANION_COLORS`` in the frontend's#: ``components/society/companion/appearance.ts`` (parity test pins both).@@ -27,6 +31,24 @@ COMPANION_COLORS: Final[tuple[str, ...]] = ()+class CompanionSkin(BaseModel):+ """A colour design worn instead of the flat colour (mirrors ``skinSchema`` in+ the frontend's ``components/society/companion/skins.ts``).++ ``color`` on the appearance stays the design's blended colour, so every+ surface that knows only one colour (chat bubbles, thinking dots) still fits.+ """++ model_config = ConfigDict(extra="forbid", strict=True)++ colors: list[HexColor] = Field(min_length=2, max_length=4)+ pattern: Literal["linear", "radial"] = "linear"+ #: CSS convention: 0 points up, 90 to the right.+ angle: int = Field(default=135, ge=0, le=359)+ effect: SkinEffect = "none"+ name: str = Field(default="", max_length=40, pattern=r"^[^\x00-\x1f\x7f]*$")++class CompanionAppearance(BaseModel):"""One identity for the profile and its presentation-only world follower."""@@ -39,6 +61,8 @@ class CompanionAppearance(BaseModel):accessories: dict[AccessorySlot, AccessoryId] = Field(default_factory=dict)#: Wear this pet instead of the shape, everywhere the agent appears.pet: PetId | None = None+ #: A colour design (gradient + effect) instead of the flat colour.+ skin: CompanionSkin | None = NonesizeM: float = Field(default=0.5, ge=0.25, le=0.8)followDistanceM: float = Field(default=1.0, ge=0.5, le=2.0)@@ -60,6 +84,8 @@ def _bare(look: dict[str, Any]) -> dict[str, Any]:look.pop("accessories", None)if look.get("pet") is None:look.pop("pet", None)+ if look.get("skin") is None:+ look.pop("skin", None)return lookdiff --git a/jarvis/society/design_library.py b/jarvis/society/design_library.pynew file mode 100644index 0000000000..dc49db6e1f--- /dev/null+++ b/jarvis/society/design_library.py@@ -0,0 +1,115 @@+"""The person's saved companion designs: colour skins kept for reuse.++A design is a :class:`~jarvis.society.companion.CompanionSkin` (colours, how+they lie on the body, an effect) the person saved from the look dialog or+imported from a design code, a CSS gradient or a picture. Any agent can then+wear it with one click. One small JSON file in the user data folder; an entry+that no longer validates (hand-edited, or written by a newer build with a field+this one does not know) is skipped, never fatal.+"""++from __future__ import annotations++import json+import os+import secrets+import threading+import time+from pathlib import Path+from typing import Any++from loguru import logger+from pydantic import ValidationError++from jarvis.society.companion import CompanionSkin++#: Plenty for a personal collection, small enough to list in one answer.+MAX_DESIGNS = 60++_lock = threading.Lock()+++def _path() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "society" / "designs.json"+++def _read() -> list[dict[str, Any]]:+ path = _path()+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError: # nothing saved yet+ return []+ except (OSError, ValueError) as exc:+ logger.warning("designs: unreadable {}: {}", path, exc)+ return []+ rows = raw.get("designs") if isinstance(raw, dict) else None+ designs: list[dict[str, Any]] = []+ for row in rows if isinstance(rows, list) else []:+ if not isinstance(row, dict) or not isinstance(row.get("id"), str):+ continue+ try:+ skin = CompanionSkin.model_validate(row.get("skin")).model_dump()+ except ValidationError as exc:+ logger.warning(+ "designs: skipping invalid design {}: {}", row.get("id"), exc.errors()[:1]+ )+ continue+ created = row.get("created")+ designs.append({+ "id": row["id"],+ "skin": skin,+ "created": created if isinstance(created, (int, float)) else 0,+ })+ return designs[:MAX_DESIGNS]+++def _write(designs: list[dict[str, Any]]) -> None:+ path = _path()+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(".json.tmp")+ tmp.write_text(json.dumps({"designs": designs}, indent=2), encoding="utf-8")+ os.replace(tmp, path)+++def list_designs() -> list[dict[str, Any]]:+ """Saved designs, newest first."""+ with _lock:+ return _read()+++def save_design(skin: CompanionSkin) -> dict[str, Any]:+ """Store ``skin`` as a new design at the front; the oldest drop off past the cap.++ Saving the same colours, layout and effect again moves the existing entry+ to the front under the new name instead of adding a duplicate.+ """+ entry = skin.model_dump()+ with _lock:+ designs = _read()+ same = next((d for d in designs if _look(d["skin"]) == _look(entry)), None)+ design = {+ "id": same["id"] if same else f"d{secrets.token_hex(6)}",+ "skin": entry,+ "created": time.time(),+ }+ designs = [design, *(d for d in designs if d is not same)][:MAX_DESIGNS]+ _write(designs)+ return design+++def delete_design(design_id: str) -> bool:+ """Remove one saved design; False when it was not there."""+ with _lock:+ designs = _read()+ kept = [d for d in designs if d["id"] != design_id]+ if len(kept) == len(designs):+ return False+ _write(kept)+ return True+++def _look(skin: dict[str, Any]) -> tuple[Any, ...]:+ colors = tuple(c.lower() for c in skin["colors"])+ return (colors, skin["pattern"], skin["angle"], skin["effect"])diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex b13aa8255a..265dccd065 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -33,6 +33,7 @@ from filelock import FileLock, Timeoutfrom jarvis.core.config import DATA_DIR, JarvisConfig, load_configfrom jarvis.core.instance import current_instancefrom jarvis.core.process_utils import drop_inherited_electron_node_mode, ensure_standard_streams+from jarvis.ui.section_windows import SECTION_WINDOW_TITLES, WINDOW_GROUPS, section_windowif TYPE_CHECKING:from jarvis.ui.desktop_background import BackgroundStatus@@ -98,9 +99,8 @@ TEXT_SELECTABLE: dict[str, Any] = {"text_select": True}# names, NOT the wake-word brand — the product/window title is a compatibility# contract (see ``jarvis/core/branding.py``), only agent names are dynamic.DETACHABLE_VIEWS: dict[str, str] = {- "agentic-ide": "Agents",- "agentic-ide-classic": "Agents",- "chat-workspace": "Agents",+ **SECTION_WINDOW_TITLES,+ **{tab: SECTION_WINDOW_TITLES[owner] for owner, tabs in WINDOW_GROUPS.items() for tab in tabs},"chats": "Voice",# The Voice hub family (one VoiceHubView with internal tabs). Each id keeps# its own label so two detached voice windows can never share a title —@@ -1958,6 +1958,7 @@ class DesktopApp:# pywebview event hooks, the tray bridge) — never from the asyncio# loop, and never from the GUI MainThread.self._detached_windows: dict[str, Any] = {}+ self._detached_open_lock = threading.Lock()self._shutdown_done = Falseself._tray: Any = Noneself._user_requested_quit = False@@ -5393,15 +5394,13 @@ class DesktopApp:def window_command(self, action: str, view: str | None) -> dict[str, Any]:"""Minimize, maximize or close one live window. Worker-thread safe.- A detached view targets that window. Anything else targets the main+ A detached view targets only that window. An omitted view targets the mainwindow. Maximize toggles, using the real zoomed state on Windows whenthe frame hook can read it."""from jarvis.ui.window_command import run_window_command- window = self._detached_windows.get(view) if view else None- if window is None:- window = self._window+ window = self._detached_windows.get(section_window(view)) if view else self._windowmaximized: bool | None = Noneif sys.platform == "win32" and window is not None:try:@@ -5419,14 +5418,12 @@ class DesktopApp:def set_window_zoom(self, factor: float, view: str | None) -> dict[str, Any]:"""Zoom one live window's page. Worker-thread safe.- A detached view targets that window. Anything else targets the main+ A detached view targets only that window. An omitted view targets the mainwindow. See ``jarvis.ui.window_zoom`` for the per-engine details."""from jarvis.ui.window_zoom import set_window_zoom- window = self._detached_windows.get(view) if view else None- if window is None:- window = self._window+ window = self._detached_windows.get(section_window(view)) if view else self._windowreturn set_window_zoom(window, factor)def _arm_window_frame(self, window: Any) -> None:@@ -5501,8 +5498,19 @@ class DesktopApp:honest degrade on hosts whose webview backend cannot create runtimewindows."""+ # Serialize check/create/register: two tabs must not open duplicate owners.+ lock = getattr(self, "_detached_open_lock", None)+ if lock is None: # Lightweight test/legacy hosts that bypass __init__.+ lock = self._detached_open_lock = threading.Lock()+ with lock:+ return self._open_detached_window(view, query)++ def _open_detached_window(self, view: str, query: str) -> dict[str, Any]:+ requested = view+ view = section_window(view)suffix = f"&{query}" if query else ""- fallback = f"/?view={view}&solo=1{suffix}"+ identity = f"&window={view}" if requested != view else ""+ fallback = f"/?view={requested}&solo=1{identity}{suffix}"if view not in DETACHABLE_VIEWS:return {"ok": False, "reason": "unknown_view"}existing = self._detached_windows.get(view)@@ -5662,6 +5670,7 @@ class DesktopApp:window's ``closed`` hook, so this path and the user's own X on thewindow behave identically."""+ view = section_window(view)window = self._detached_windows.get(view)if window is None:return {"ok": False, "reason": "not_detached"}diff --git a/jarvis/ui/pets/context_menu.py b/jarvis/ui/pets/context_menu.pynew file mode 100644index 0000000000..f444bcfa91--- /dev/null+++ b/jarvis/ui/pets/context_menu.py@@ -0,0 +1,56 @@+"""Preferences and translated labels for the native pet context menu."""++from __future__ import annotations++import logging+import sys+import tomllib+from pathlib import Path++LABELS = {+ "en": ("Open app", "Reset position", "Hide pet"),+ "de": ("App öffnen", "Position zurücksetzen", "Ausblenden"), # i18n-allow+ "es": ("Abrir la aplicación", "Restablecer posición", "Ocultar mascota"),+ "zh": ("打开应用", "重置位置", "隐藏宠物"),+}+++def appearance(path: Path | None = None) -> str:+ """Use the current app appearance, including the OS-following setting."""+ from jarvis.core.config import DEFAULT_CONFIG_FILE+ from jarvis.ui.theme import resolve_theme++ try:+ source = DEFAULT_CONFIG_FILE if path is None else path+ data = tomllib.loads(source.read_text(encoding="utf-8-sig"))+ configured = str(data.get("ui", {}).get("theme", "dark"))+ except FileNotFoundError:+ configured = "dark" # Fresh installs use the product default.+ except (OSError, ValueError, AttributeError, TypeError):+ logging.getLogger(__name__).debug("Pet menu appearance unavailable", exc_info=True)+ configured = "dark"+ return resolve_theme(configured)+++def preferences(path: Path | None = None) -> tuple[tuple[str, str, str], str]:+ """Read on opening, so language and shortcut edits apply without a restart."""+ from jarvis.core.config import DEFAULT_CONFIG_FILE, TriggerConfig++ language = "en"+ shortcut = TriggerConfig.model_fields["hotkey_pet_toggle"].default+ try:+ source = DEFAULT_CONFIG_FILE if path is None else path+ data = tomllib.loads(source.read_text(encoding="utf-8-sig"))+ language = str(data.get("ui", {}).get("language", "en")).lower()+ shortcut = data.get("trigger", {}).get("hotkey_pet_toggle", shortcut)+ except FileNotFoundError:+ # Fresh installs and isolated native previews use the product defaults.+ pass+ except (OSError, ValueError, AttributeError, TypeError):+ logging.getLogger(__name__).debug("Pet menu preferences unavailable", exc_info=True)+ names = {"alt": "Alt", "ctrl": "Ctrl", "shift": "Shift", "win": "Win"}+ if sys.platform == "darwin":+ names.update(alt="Option", win="Command", ctrl="Control")+ combo = "+".join(names.get(key.strip().lower(), key.strip().upper())+ for key in str(shortcut or "").split("+") if key.strip())+ return LABELS.get(language, LABELS["en"]), combodiff --git a/jarvis/ui/pets/menu_renderer.py b/jarvis/ui/pets/menu_renderer.pynew file mode 100644index 0000000000..7119e4afd3--- /dev/null+++ b/jarvis/ui/pets/menu_renderer.py@@ -0,0 +1,184 @@+"""The app's neutral popover, Inter labels and compact keyboard hints in RGBA."""++from __future__ import annotations++import functools+import math+import os+from dataclasses import dataclass+from pathlib import Path++from PIL import Image, ImageColor, ImageDraw, ImageFont++from jarvis.ui.theme import POPOVER_COLORS++PADDING = 8+ROW_HEIGHT = 36+SEPARATOR_HEIGHT = 8+++@dataclass(frozen=True)+class MenuEntry:+ label: str+ shortcut: str = ""+ enabled: bool = True+ icon: str = "open"++[email protected]_cache(maxsize=32)+def _font(px: int, mono: bool = False, cjk: bool = False):+ assets = Path(__file__).resolve().parents[1] / "web" / "dist" / "assets"+ pattern = (+ "jetbrains-mono-latin-500-normal-*.woff2" if mono else "inter-latin-wght-normal-*.woff2"+ )+ candidates = list(assets.glob(pattern))+ if cjk:+ candidates = [+ Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts" / "msyh.ttc",+ Path("/System/Library/Fonts/PingFang.ttc"),+ Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),+ ] + candidates+ for path in candidates:+ try:+ font = ImageFont.truetype(str(path), px)+ if not mono and not cjk:+ try:+ font.set_variation_by_axes([500])+ except (OSError, AttributeError):+ # Static font builds already carry their intended weight.+ pass+ return font+ except OSError:+ # Some FreeType builds lack WOFF2; the system UI face is the fallback.+ continue+ from ui.orb.pet_cards import font as system_font++ return system_font("regular", px)+++def row_bounds(entries: list[MenuEntry | None]) -> list[tuple[int, int]]:+ y = PADDING+ bounds = []+ for entry in entries:+ height = SEPARATOR_HEIGHT if entry is None else ROW_HEIGHT+ bounds.append((y, y + height))+ y += height+ return bounds+++def menu_size(entries: list[MenuEntry | None], scale: float = 1.0) -> tuple[int, int]:+ width = 240.0+ for entry in entries:+ if entry is None:+ continue+ face = _font(14, cjk=any(ord(c) > 0x2E80 for c in entry.label))+ hint = float(_font(12, mono=True).getlength(entry.shortcut)) if entry.shortcut else 0+ width = max(+ width, 40 + float(face.getlength(entry.label)) + (hint + 28 if hint else 0) + 16+ )+ width = math.ceil(width / 4) * 4+ bounds = row_bounds(entries)+ height = (bounds[-1][1] if bounds else PADDING) + PADDING+ return round(width * scale), round(height * scale)+++def hit_test(entries: list[MenuEntry | None], x: float, y: float, width: float) -> int | None:+ if not PADDING <= x < width - PADDING:+ return None+ for index, (top, bottom) in enumerate(row_bounds(entries)):+ entry = entries[index]+ if top <= y < bottom and entry is not None and entry.enabled:+ return index+ return None+++def _icon(draw, name, x, y, scale, color):+ def line(points):+ draw.line(+ [(round(x + a * scale), round(y + b * scale)) for a, b in points],+ fill=color,+ width=max(1, round(1.5 * scale)),+ joint="curve",+ )++ if name == "open":+ line([(9, 2), (14, 2), (14, 7)])+ line([(7, 9), (14, 2)])+ line([(6, 3), (2, 3), (2, 14), (13, 14), (13, 10)])+ elif name == "reset":+ box = [+ round(x + 3 * scale),+ round(y + 3 * scale),+ round(x + 14 * scale),+ round(y + 14 * scale),+ ]+ draw.arc(box, 210, 510, fill=color, width=max(1, round(1.5 * scale)))+ line([(2, 2), (2, 7), (7, 7)])+ else:+ line([(1, 8), (4, 4), (8, 3), (12, 4), (15, 8), (12, 12), (8, 13), (4, 12), (1, 8)])+ line([(2, 2), (14, 14)])+++def render_menu(+ entries: list[MenuEntry | None],+ theme: str = "dark",+ *,+ selected: int | None = None,+ keyboard: bool = False,+ scale: float = 1.0,+) -> Image.Image:+ """Render exactly the pixels used by the desktop popup (also usable in previews)."""+ colors = POPOVER_COLORS.get(theme, POPOVER_COLORS["dark"])+ size = menu_size(entries, scale)+ zoom = scale * 3+ width, height = menu_size(entries)+ image = Image.new("RGBA", (round(width * zoom), round(height * zoom)))+ draw = ImageDraw.Draw(image)++ def rect(box, radius, fill, outline=None):+ draw.rounded_rectangle(+ tuple(round(v * zoom) for v in box),+ round(radius * zoom),+ fill=fill,+ outline=outline,+ width=max(1, round(zoom)),+ )++ rect((0.5, 0.5, width - 0.5, height - 0.5), 12, colors["background"], colors["border"])+ for index, (top, bottom) in enumerate(row_bounds(entries)):+ entry = entries[index]+ if entry is None:+ draw.line(+ (+ round(16 * zoom),+ round((top + 4) * zoom),+ round((width - 16) * zoom),+ round((top + 4) * zoom),+ ),+ fill=colors["border"],+ width=max(1, round(zoom)),+ )+ continue+ if index == selected and entry.enabled:+ fill = colors["hover"]+ if keyboard:+ bg, accent = (+ ImageColor.getrgb(colors["background"]),+ ImageColor.getrgb(colors["accent"]),+ )+ fill = tuple(round(a * 0.88 + b * 0.12) for a, b in zip(bg, accent, strict=True))+ rect((8, top, width - 8, bottom), 8, fill)+ ink = colors["foreground"] if entry.enabled else colors["faint"]+ middle = (top + bottom) / 2+ _icon(draw, entry.icon, 16 * zoom, (middle - 8) * zoom, zoom, colors["muted"])+ face = _font(round(14 * zoom), cjk=any(ord(c) > 0x2E80 for c in entry.label))+ draw.text((40 * zoom, middle * zoom), entry.label, font=face, fill=ink, anchor="lm")+ if entry.shortcut:+ draw.text(+ ((width - 16) * zoom, middle * zoom),+ entry.shortcut,+ font=_font(round(12 * zoom), mono=True),+ fill=colors["muted"],+ anchor="rm",+ )+ return image.resize(size, Image.Resampling.LANCZOS)diff --git a/jarvis/ui/section_windows.py b/jarvis/ui/section_windows.pynew file mode 100644index 0000000000..74528d1237--- /dev/null+++ b/jarvis/ui/section_windows.py@@ -0,0 +1,30 @@+"""Section families that share one desktop window and its native identity."""++WINDOW_GROUPS: dict[str, tuple[str, ...]] = {+ "agentic-ide": ("agentic-ide", "agentic-ide-classic", "chat-workspace"),+ "settings": (+ "settings", "taskbar", "languages", "profile", "agent-instructions",+ "socials", "apikeys", "telephony", "telephony-setup", "computers",+ "appshots", "shortcuts", "pets", "costs", "feedback",+ ),+ "plugins": ("plugins", "mcps", "skills"),+ "clis": ("clis", "cli-test-hub"),+}++SECTION_WINDOW_TITLES = {+ "agentic-ide": "Agentic IDE",+ "agents": "Agents",+ "settings": "Settings",+ "plugins": "Plugins",+ "clis": "CLIs",+ "docs": "Docs",+ "memory": "Wiki",+ "board": "Board",+ "sessions": "Sessions",+ "marketplace": "Marketplace",+}+++def section_window(view: str) -> str:+ """Resolve a tab to its owning window without changing its navigation id."""+ return next((owner for owner, tabs in WINDOW_GROUPS.items() if view in tabs), view)diff --git a/jarvis/ui/theme.py b/jarvis/ui/theme.pyindex 41f593a6ac..12e117d976 100644--- a/jarvis/ui/theme.py+++ b/jarvis/ui/theme.py@@ -56,6 +56,20 @@ HOLDING_PAGE_MUTED: dict[str, str] = {_DEFAULT_THEME: Theme = "dark"+# Native popup tokens, matching index.css and docs/BRAND.md.+POPOVER_COLORS = {+ "dark": {+ "background": "#1c1c1c", "hover": "#262626", "border": "#383838",+ "foreground": "#fafafa", "muted": "#a1a1a1", "faint": "#7a7a7a",+ "accent": "#3d8bff",+ },+ "light": {+ "background": "#ffffff", "hover": "#f5f5f5", "border": "#dbdbdb",+ "foreground": "#171717", "muted": "#545454", "faint": "#6b6b6b",+ "accent": "#096cdc",+ },+}+def detect_os_theme() -> Theme | None:"""The desktop's own light/dark preference, or ``None`` if unknowable.diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex a7b32ec0da..4cb09da1e5 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -536,6 +536,37 @@ class ActiveAccountRequest(BaseModel):)+class SwitchSeatRequest(BaseModel):+ """Which subscription a coding CLI and all of its running agents move to."""++ agent: str = Field(+ description=(+ "Coding CLI to switch. GET /api/agent-accounts for the CLIs this "+ "build can switch."+ )+ )+ account_id: str = Field(description="Id of a stored subscription of that agent.")+++class AutoSwitchRequest(BaseModel):+ """When running work moves off a subscription that is running out."""++ enabled: bool | None = Field(+ default=None,+ description="Move work to the next subscription automatically. Omit to keep.",+ )+ at_percent: float | None = Field(+ default=None,+ ge=50,+ le=100,+ description=(+ "Spent share of a plan limit at which its work moves on, e.g. 97 "+ "for three percent left. A refused request always moves the work. "+ "Omit to keep."+ ),+ )++class ActivateWorkspaceRequest(BaseModel):"""Which workspace should be on screen."""@@ -3325,6 +3356,72 @@ async def set_active_account(req: ActiveAccountRequest) -> dict:}+ "/accounts/switch",+ summary="Switch a coding CLI and its running agents to another subscription",+)+async def switch_seat(req: SwitchSeatRequest) -> dict:+ """Make one subscription the active seat AND move the running agents onto it.++ Every pane of that CLI follows: an idle agent is restarted on the new seat+ at once and continues its own conversation (the conversation is carried+ into the new seat's history); an agent in the middle of a turn moves the+ moment the turn ends. Panes already signed in as the same login stay put.+ New panes, chat threads and agents start on the new seat from now on.+ """+ from jarvis import agent_accounts+ from jarvis.agentic_ide import seat_switch++ if req.agent not in agent_accounts.platforms():+ raise HTTPException(status_code=422, detail=f"{req.agent} has no switchable subscriptions.")+ registry = get_registry()+ try:+ event = await seat_switch.switch_seat(registry, req.agent, req.account_id)+ except agent_accounts.AccountError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ seat_switch.start(registry)+ display = AGENT_DISPLAY.get(req.agent, req.agent)+ parts = [f"{display} now runs on {event.to_label}."]+ if event.moved:+ parts.append(f"{event.moved} agent(s) moved with their conversations.")+ if event.queued:+ parts.append(f"{event.queued} working agent(s) follow when their turn ends.")+ return {+ "ok": True,+ "agent": req.agent,+ "active_account": event.to_account,+ "active_label": event.to_label,+ "moved": event.moved,+ "queued": event.queued,+ "message": " ".join(parts),+ }++[email protected]("/accounts/auto-switch", summary="Automatic subscription switching")+async def get_auto_switch() -> dict:+ """Whether work moves to the next subscription on its own, and what happened.++ ``at_percent`` is the spent share at which a seat's work moves on;+ ``exhausted`` lists seats out of rotation until they refill; ``events``+ the most recent switches, newest first.+ """+ from jarvis.agentic_ide import seat_switch++ return {"ok": True, **await asyncio.to_thread(seat_switch.status)}++[email protected]("/accounts/auto-switch", summary="Change automatic subscription switching")+async def set_auto_switch(req: AutoSwitchRequest) -> dict:+ """Turn automatic switching on or off, or move its threshold."""+ from jarvis import agent_accounts+ from jarvis.agentic_ide import seat_switch++ await asyncio.to_thread(+ lambda: agent_accounts.set_auto_switch(enabled=req.enabled, at_percent=req.at_percent)+ )+ return {"ok": True, **await asyncio.to_thread(seat_switch.status)}++@router.post("/terminals", summary="Open one more terminal")async def add_terminal(req: AddTerminalRequest) -> dict:"""Add a terminal to the running workspace, beside or below another one.@@ -3425,9 +3522,13 @@ def put_offload_on_quit(req: OffloadOnQuitRequest) -> dict:if req.computer_id:try:- get_service().get(req.computer_id)+ chosen = get_service().get(req.computer_id)except ComputerError as exc:raise HTTPException(status_code=404, detail=exc.message) from exc+ if not chosen.enabled:+ raise HTTPException(+ status_code=409, detail="This computer is switched off. Switch it on first."+ )offload_on_quit.set_target(req.computer_id)return {"computer_id": offload_on_quit.target()}diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.pyindex 6f0749714a..0c3d80d775 100644--- a/jarvis/ui/web/computers_routes.py+++ b/jarvis/ui/web/computers_routes.py@@ -6,6 +6,11 @@GET /api/computers/identity Jarvis's public key + fingerprintGET /api/computers/providers provider catalog (SSH guides, API)POST /api/computers/test try a login without saving+ GET /api/computers/ssh-hosts servers in this PC's ~/.ssh/config+ GET /api/computers/tailscale tailnet peers + address suggestions+ GET /api/computers/placement "Automatic" switch + this PC's share+ PUT /api/computers/placement change them+ POST /api/computers/placement/pick the machine a new workspace goes toPUT /api/computers/{id}/credentials switch the login methodGET /api/computers/cloud hosting providers + token statePUT /api/computers/cloud/{provider}/token save an API token (keyring)@@ -15,7 +20,12 @@GET /api/computers/local Multipass state + instancesPOST /api/computers/local create a local VM (background)GET /api/computers/{id} one computer- PATCH /api/computers/{id} rename / edit address+ PATCH /api/computers/{id} rename / edit address / switch on-off+ POST /api/computers/{id}/routes add another address (same identity)+ PUT /api/computers/{id}/routes/order set the preferred order of addresses+ DELETE /api/computers/{id}/routes/{route} forget one address+ POST /api/computers/{id}/github share this PC's GitHub login there+ DELETE /api/computers/{id}/github remove it againDELETE /api/computers/{id} remove (optionally destroy the VM)POST /api/computers/{id}/check connect and read vitalsPOST /api/computers/{id}/run run one shell command@@ -42,7 +52,15 @@ from typing import Any, Literalfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from jarvis.computers import cloud, identity, local_vm, providers, toolbox+from jarvis.computers import (+ cloud,+ github_access,+ identity,+ local_vm,+ placement,+ providers,+ toolbox,+)from jarvis.computers.models import Computerfrom jarvis.computers.service import ComputerError, get_service@@ -81,6 +99,8 @@ class AddServerBody(BaseModel):private_key: str | None = Field(default=None, max_length=32_000)passphrase: str | None = Field(default=None, max_length=1024)provider: str = Field(default="generic", max_length=40)+ #: A ``Host`` alias from this PC's ``~/.ssh/config`` (``GET /ssh-hosts``).+ ssh_alias: str | None = Field(default=None, max_length=253)class TestBody(BaseModel):@@ -94,6 +114,7 @@ class TestBody(BaseModel):private_key: str | None = Field(default=None, max_length=32_000)passphrase: str | None = Field(default=None, max_length=1024)provider: str = Field(default="generic", max_length=40)+ ssh_alias: str | None = Field(default=None, max_length=253)class CredentialsBody(BaseModel):@@ -109,6 +130,24 @@ class UpdateBody(BaseModel):host: str | None = Field(default=None, max_length=253)port: int | None = Field(default=None, ge=1, le=65535)username: str | None = Field(default=None, max_length=64)+ enabled: bool | None = None+ placement_weight: int | None = Field(default=None, ge=0, le=3)+++class RouteBody(BaseModel):+ host: str = Field(min_length=1, max_length=253)+ port: int = Field(default=22, ge=1, le=65535)+ label: str | None = Field(default=None, max_length=40)+ source: Literal["manual", "tailscale", "ssh_config"] = "manual"+++class RouteOrderBody(BaseModel):+ route_ids: list[str] = Field(min_length=1, max_length=8)+++class PlacementBody(BaseModel):+ enabled: bool | None = None+ local_weight: int | None = Field(default=None, ge=0, le=3)class RunBody(BaseModel):@@ -178,6 +217,7 @@ async def add_computer(body: AddServerBody) -> dict[str, Any]:private_key=body.private_key,passphrase=body.passphrase,provider=body.provider,+ ssh_alias=body.ssh_alias,)except ComputerError as exc:raise _fail(exc) from exc@@ -195,9 +235,51 @@ async def test_computer(body: TestBody) -> dict[str, Any]:password=body.password,private_key=body.private_key,passphrase=body.passphrase,+ ssh_alias=body.ssh_alias,)[email protected]("/ssh-hosts")+def list_ssh_hosts() -> dict[str, Any]:+ """Servers this PC's own ``ssh`` knows (``~/.ssh/config``, ``known_hosts``)."""+ return {"hosts": get_service().ssh_config_hosts()}++[email protected]("/tailscale")+async def tailscale_status() -> dict[str, Any]:+ """This PC's tailnet and the Tailscale addresses each computer could add."""+ return await get_service().tailscale_status()+++def _placement_view() -> dict[str, Any]:+ from dataclasses import asdict++ return asdict(placement.load())++[email protected]("/placement")+def get_placement() -> dict[str, Any]:+ return _placement_view()++[email protected]("/placement")+def put_placement(body: PlacementBody) -> dict[str, Any]:+ current = placement.load()+ placement.save(+ placement.PlacementSettings(+ enabled=current.enabled if body.enabled is None else body.enabled,+ local_weight=current.local_weight if body.local_weight is None else body.local_weight,+ )+ )+ return _placement_view()++[email protected]("/placement/pick")+def pick_placement() -> dict[str, Any]:+ """Where "Automatic" sends the next new workspace (``null`` = this PC)."""+ return {"computer_id": placement.pick(placement.load(), get_service().all())}++@router.get("/providers")def list_providers() -> dict[str, Any]:"""Every place a computer can come from, with how to reach it there."""@@ -344,6 +426,49 @@ def update_computer(computer_id: str, body: UpdateBody) -> dict[str, Any]:raise _fail(exc) from exc[email protected]("/{computer_id}/routes")+async def add_route(computer_id: str, body: RouteBody) -> dict[str, Any]:+ try:+ computer = await get_service().add_route(+ computer_id, host=body.host, port=body.port, label=body.label, source=body.source+ )+ except ComputerError as exc:+ raise _fail(exc) from exc+ return _row(computer)++[email protected]("/{computer_id}/routes/order")+def order_routes(computer_id: str, body: RouteOrderBody) -> dict[str, Any]:+ try:+ return _row(get_service().order_routes(computer_id, body.route_ids))+ except ComputerError as exc:+ raise _fail(exc) from exc++[email protected]("/{computer_id}/routes/{route_id}")+def remove_route(computer_id: str, route_id: str) -> dict[str, Any]:+ try:+ return _row(get_service().remove_route(computer_id, route_id))+ except ComputerError as exc:+ raise _fail(exc) from exc++[email protected]("/{computer_id}/github")+async def share_github(computer_id: str) -> dict[str, Any]:+ try:+ return _row(await github_access.share(computer_id))+ except ComputerError as exc:+ raise _fail(exc) from exc++[email protected]("/{computer_id}/github")+async def unshare_github(computer_id: str) -> dict[str, Any]:+ try:+ return _row(await github_access.unshare(computer_id))+ except ComputerError as exc:+ raise _fail(exc) from exc++@router.delete("/{computer_id}")async def remove_computer(computer_id: str, destroy_vm: bool = False) -> dict[str, Any]:try:diff --git a/jarvis/ui/web/custom_api_routes.py b/jarvis/ui/web/custom_api_routes.pyindex 195ffadef7..309fd13cbd 100644--- a/jarvis/ui/web/custom_api_routes.py+++ b/jarvis/ui/web/custom_api_routes.py@@ -8,6 +8,7 @@ from dataclasses import asdictfrom typing import Anyfrom uuid import uuid4+import httpxfrom fastapi import APIRouter, HTTPException, Requestfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.routing import APIRoute@@ -16,6 +17,8 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStrfrom jarvis.core.protocols import SupervisorToolRequestfrom jarvis.core.runtime_refs import get_supervisor_tool_gatewayfrom jarvis.marketplace.custom_api import ApiDefinition, CustomApiStore+from jarvis.marketplace.custom_api_discovery import ApiDiscoveryError, normalized_name+from jarvis.marketplace.custom_api_openapi import OpenApiImportErrorlog = logging.getLogger(__name__)@@ -60,6 +63,32 @@ class RunApiActionRequest(BaseModel):arguments: dict[str, Any] = Field(default_factory=dict)+class ConnectApiRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")+ id: str = Field(default_factory=lambda: uuid4().hex, pattern=r"^[a-f0-9]{32}$")+ name: str = Field(min_length=1, max_length=100)+ credential: SecretStr | None = Field(default=None, max_length=8192)+++class ConnectionSummary(BaseModel):+ id: str+ name: str+ website: str+ brand_id: str+ logo_data: str+ categories: list[str]+ action_count: int+ omitted_operations: int+ enabled: bool+ has_credential: bool+ tools_ready: bool+ status: str+++class ConnectionEnabledRequest(BaseModel):+ enabled: bool++def _registry(request: Request) -> Any:return getattr(request.app.state, "plugin_registry", None)@@ -92,6 +121,130 @@ async def _refresh(request: Request) -> None:log.warning("Custom API live refresh failed", exc_info=True)+async def _connection_summary(request: Request, definition: ApiDefinition) -> ConnectionSummary:+ status = await _status(request, definition)+ info = definition.connection+ return ConnectionSummary(+ id=definition.id,+ name=definition.name,+ website=info.website if info else definition.base_url,+ brand_id=info.brand_id if info else "",+ logo_data=info.logo_data if info else "",+ categories=info.categories if info else [],+ action_count=len(definition.actions),+ omitted_operations=info.omitted_operations if info else 0,+ enabled=definition.enabled,+ has_credential=status.has_credential,+ tools_ready=status.tools_ready,+ status=info.status if info else "configured",+ )++[email protected]("/connections", response_model=list[ConnectionSummary])+async def list_api_connections(request: Request) -> list[ConnectionSummary]:+ """List connected services without downloading every operation schema."""+ definitions = await asyncio.to_thread(_store(request).list)+ return [await _connection_summary(request, definition) for definition in definitions]++[email protected]("/connect", response_model=ConnectionSummary)+async def connect_api_by_name(body: ConnectApiRequest, request: Request) -> ConnectionSummary:+ """Add a service using its name and API key, or replace an existing key."""+ from jarvis.marketplace.custom_api_connect import verify_api_key++ store = _store(request)+ previous = await asyncio.to_thread(store.get, body.id)+ credential = body.credential.get_secret_value() if body.credential else None+ if credential is not None and (not credential.strip() or any(ord(c) < 32 for c in credential)):+ raise HTTPException(422, {"code": "invalid_key"})+ if previous is not None:+ if normalized_name(previous.name) != normalized_name(body.name):+ raise HTTPException(422, {"code": "connection_name_changed"})+ definition = previous+ if credential is None:+ return await _connection_summary(request, previous)+ else:+ if not credential:+ raise HTTPException(422, {"code": "key_required"})+ registry = _registry(request)+ discovery = getattr(request.app.state, "custom_api_discovery", None)+ if discovery is None:+ if registry is None:+ raise HTTPException(503, {"code": "not_ready"})+ discovery = registry.custom_apis.discovery()+ try:+ # The separate interface cannot receive the key, even accidentally.+ definition = await discovery.resolve(body.name)+ definition = definition.model_copy(update={"id": body.id})+ except ApiDiscoveryError as exc:+ raise HTTPException(422, {"code": exc.code, "suggestions": exc.suggestions}) from None+ except OpenApiImportError:+ log.info("Custom API description needs an unsupported authentication or schema feature")+ raise HTTPException(422, {"code": "unsupported_api"}) from None+ except TimeoutError:+ raise HTTPException(504, {"code": "discovery_timeout"}) from None+ except (ValueError, OSError, httpx.HTTPError):+ log.warning("Custom API documentation could not be resolved")+ raise HTTPException(503, {"code": "documentation_unavailable"}) from None+ try:+ verifier = getattr(request.app.state, "custom_api_verifier", verify_api_key)+ status = await verifier(definition, credential or "")+ if definition.connection is not None:+ definition.connection.status = status+ await asyncio.to_thread(+ store.save, definition, credential if definition.auth.mode != "none" else None+ )+ except ApiDiscoveryError as exc:+ raise HTTPException(422, {"code": exc.code}) from None+ except (ValueError, OSError, RuntimeError):+ log.warning("Custom API connection could not be saved")+ raise HTTPException(503, {"code": "storage_unavailable"}) from None+ await _refresh(request)+ return await _connection_summary(request, definition)++[email protected]("/connections/{api_id}", response_model=ConnectionSummary)+async def set_api_connection_enabled(+ api_id: str, body: ConnectionEnabledRequest, request: Request+) -> ConnectionSummary:+ """Pause or resume this service for Jarvis and its agents."""+ try:+ definition = await asyncio.to_thread(_store(request).get, api_id)+ if definition is None:+ raise HTTPException(404, "Connection not found")+ definition.enabled = body.enabled+ await asyncio.to_thread(_store(request).save, definition)+ except ValueError:+ raise HTTPException(422, {"code": "invalid_connection"}) from None+ await _refresh(request)+ return await _connection_summary(request, definition)++[email protected]("/connections/{api_id}/actions")+async def list_api_connection_actions(+ api_id: str, request: Request, query: str = ""+) -> dict[str, Any]:+ """Show the capabilities of one service without executing an API call."""+ try:+ definition = await asyncio.to_thread(_store(request).get, api_id)+ except ValueError:+ raise HTTPException(422, "Invalid connection") from None+ if definition is None:+ raise HTTPException(404, "Connection not found")+ words = query.casefold().split()+ actions = [+ a+ for a in definition.actions+ if all(w in f"{a.description} {a.id}".casefold() for w in words)+ ]+ return {+ "total": len(actions),+ "actions": [+ {"id": a.id, "description": a.description, "risk_tier": a.risk_tier} for a in actions+ ],+ }++@router.get("", response_model=list[ApiStatus])async def list_custom_apis(request: Request) -> list[ApiStatus]:"""List API definitions and local readiness without calling providers."""@@ -160,8 +313,10 @@ async def run_custom_api_action(if gateway is None:raise HTTPException(503, "Jarvis tool execution is not ready yet")result = await gateway.execute(- f"api_{api_id}_{action_id}",- body.arguments,+ f"api_{api_id}_call" if definition.connection else f"api_{api_id}_{action_id}",+ {"action": action_id, "arguments": body.arguments}+ if definition.connection+ else body.arguments,SupervisorToolRequest(trace_id=uuid4(),origin="custom-api-ui",diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsxindex b5e0a7fd43..ba7175d1a7 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/ComposerAddMenu.tsx@@ -2,6 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "reimport { createPortal } from "react-dom";import { Check, FolderOpen, Loader2, Paperclip, Plus, Search, X } from "lucide-react";import { useT } from "@/i18n";+import { requestPluginFocus } from "@/lib/customConnector";import { cn } from "@/lib/utils";import { BrandedSelect } from "@/components/ui/select";import { ToolChoiceIcon } from "./ToolChoiceChips";@@ -334,6 +335,8 @@ export function ComposerAddMenu({onClick={() => {if (!row.available) {close();+ // Land on this plugin's own page, not the top of the list.+ if (row.category === "plugins" && row.brand) requestPluginFocus(row.brand);onConnect(row);return;}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolChoices.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolChoices.tsindex 60bdd787b9..2a800fd05f 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolChoices.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolChoices.ts@@ -25,6 +25,8 @@ export interface ToolChoice {available: boolean;tool_names: string[];skill: string;+ /** A plugin the owner added (custom connector or upload). */+ user_added?: boolean;}export interface ToolSearchResult {@@ -44,13 +46,14 @@ export async function searchTools(/*** The Add menu lists connectors, not the skills and commands behind them.- * Disconnected plugins stay hidden until someone searches for them.+ * Disconnected plugins stay hidden until someone searches for them — except+ * the ones the owner added, which show with a Connect action.*/export function browseToolRows(items: ToolChoice[], query = ""): ToolChoice[] {const searching = Boolean(query.trim());return items.filter((row) => {if (row.category === "plugins" && row.id.startsWith("tool:")) return false;- if (row.category === "plugins" && !row.available && !searching) return false;+ if (row.category === "plugins" && !row.available && !searching && !row.user_added) return false;if (row.category === "skills" && isPluginOwnedSkill(row.skill || row.label || row.id)) return false;return true;});diff --git a/jarvis/ui/web/frontend/src/components/agentic/RunOnPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/RunOnPicker.tsxindex 3e55d568f3..62e832288d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/RunOnPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/RunOnPicker.tsx@@ -4,13 +4,40 @@* agents live in tmux there and keep working while this PC is off; the folder* is copied there first (new files that look like secrets stay here).*/-import { useEffect } from "react";-import { Laptop, Server } from "lucide-react";+import { useEffect, useState } from "react";+import { Laptop, Server, Shuffle } from "lucide-react";import { useComputerChoiceList } from "@/hooks/useComputers";+import { computersApi } from "@/lib/computersApi";import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";const RUN_ON_KEY = "jarvis.agenticIde.runOn.";+/** The picker's value for "let automatic placement choose" (Settings, Computers). */+export const RUN_ON_AUTO = "auto";++/** Whether automatic placement is switched on; one quiet fetch, off on any failure. */+function useAutoPlacement(wanted: boolean): { on: boolean; settled: boolean } {+ const [state, setState] = useState({ on: false, settled: !wanted });+ useEffect(() => {+ if (!wanted) return;+ let alive = true;+ const settle = (on: boolean) => {+ if (alive) setState({ on, settled: true });+ };+ try {+ void computersApi+ .placement()+ .then((settings) => settle(Boolean(settings?.enabled)))+ .catch(() => settle(false));+ } catch {+ settle(false); /* fetch unavailable: no automatic placement */+ }+ return () => {+ alive = false;+ };+ }, [wanted]);+ return state;+}/** The computer last chosen for a project's new workspaces; storage may be blocked. */export function storedRunOn(projectId: string | undefined): string | null {@@ -36,17 +63,27 @@ export function RunOnPicker({onChange,disabled,hideWhenNone = false,+ allowAuto = false,}: {value: string | null;onChange: (computerId: string | null) => void;disabled?: boolean;/** Show nothing (instead of a "Connect a server" hint) when no computer is connected. */hideWhenNone?: boolean;+ /** Offer "Automatic" (value {@link RUN_ON_AUTO}) when automatic placement is on. */+ allowAuto?: boolean;}) {const { computers, loaded } = useComputerChoiceList();const setActiveSection = useEventStore((state) => state.setActiveSection);- const usable = computers.filter((computer) => computer.health.status !== "provisioning");+ const usable = computers.filter(+ (computer) => computer.health.status !== "provisioning" && computer.enabled !== false,+ );+ const placement = useAutoPlacement(allowAuto);+ const auto = placement.on && usable.length > 0;const options = [+ ...(auto+ ? [{ id: RUN_ON_AUTO as string | null, name: "Automatic", detail: "Picks this PC or a computer by their shares", online: true, icon: Shuffle }]+ : []),{ id: null as string | null, name: "This computer", detail: "Stops when this PC sleeps or shuts down", online: true, icon: Laptop },...usable.map((computer) => ({id: computer.id as string | null,@@ -58,7 +95,12 @@ export function RunOnPicker({];// A remembered computer that has been removed since falls back to this PC,// rather than leaving no choice selected and failing on create.- const missing = loaded && value !== null && !usable.some((computer) => computer.id === value);+ const missing =+ loaded &&+ value !== null &&+ (value === RUN_ON_AUTO+ ? !allowAuto || (placement.settled && !auto)+ : !usable.some((computer) => computer.id === value));useEffect(() => { if (missing) onChange(null); }, [missing, onChange]);if (hideWhenNone && usable.length === 0) return null;@@ -88,7 +130,7 @@ export function RunOnPicker({<span className="min-w-0"><span className="flex items-center gap-2 text-sm font-medium text-foreground"><span className="truncate">{option.name}</span>- {option.id && (+ {option.id && option.id !== RUN_ON_AUTO && (<spanaria-hidden="true"className={cn("h-1.5 w-1.5 shrink-0 rounded-full", option.online ? "bg-accent" : "bg-foreground-faint")}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.test.tsxnew file mode 100644index 0000000000..6d8fdb90e6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.test.tsx@@ -0,0 +1,152 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import {+ fetchAgentAccounts,+ fetchAgentUsage,+ fetchAutoSwitch,+ switchSeat,+ updateAutoSwitch,+ type AgentAccount,+ type AutoSwitchState,+} from "@/lib/agentAccountsApi";+import { useEventStore } from "@/store/events";+import { SubscriptionsTab } from "./SubscriptionsTab";++vi.mock("@/lib/agentAccountsApi", async () => {+ const actual = await vi.importActual<typeof import("@/lib/agentAccountsApi")>("@/lib/agentAccountsApi");+ return {+ ...actual,+ fetchAgentAccounts: vi.fn(),+ fetchAgentUsage: vi.fn(),+ fetchAutoSwitch: vi.fn(),+ switchSeat: vi.fn(),+ updateAutoSwitch: vi.fn(),+ };+});++function account(id: string, extra: Partial<AgentAccount> = {}): AgentAccount {+ return {+ id,+ platform: "claude",+ label: `Seat ${id}`,+ config_dir: `/home/u/${id}`,+ builtin: false,+ connected: true,+ mode: "subscription",+ message: "",+ email: `${id}@example.com`,+ tier: null,+ ...extra,+ };+}++const ACCOUNTS = {+ platforms: [+ {+ platform: "claude",+ display_name: "Claude Code",+ active_account: "c1",+ accounts: [account("c1"), account("c2"), account("c3")],+ },+ ],+};++const STATE: AutoSwitchState = {+ enabled: true,+ at_percent: 97,+ watching: true,+ exhausted: [{ account_id: "c3", until: Date.now() / 1000 + 3600 }],+ events: [+ {+ at: Date.now() / 1000 - 60,+ platform: "claude",+ reason: "limit",+ to_account: "c1",+ to_label: "Seat c1",+ from_label: "Seat c3",+ moved: 2,+ queued: 0,+ },+ ],+};++beforeEach(() => {+ useEventStore.setState({ activeSection: "agentic-ide" });+ vi.mocked(fetchAgentAccounts).mockResolvedValue(ACCOUNTS);+ vi.mocked(fetchAgentUsage).mockResolvedValue({ accounts: [], ttl_seconds: 60, generated_at: 0 });+ vi.mocked(fetchAutoSwitch).mockResolvedValue(STATE);+});++afterEach(() => {+ cleanup();+ vi.mocked(fetchAgentAccounts).mockReset();+ vi.mocked(fetchAgentUsage).mockReset();+ vi.mocked(fetchAutoSwitch).mockReset();+ vi.mocked(switchSeat).mockReset();+ vi.mocked(updateAutoSwitch).mockReset();+});++async function rows() {+ render(<SubscriptionsTab />);+ await screen.findByTestId("auto-switch-bar");+ return screen.findAllByTestId("subscription-row");+}++describe("seat switching in the Subscriptions tab", () => {+ it("offers a one-click switch on every row except the active one", async () => {+ const [active, second, third] = await rows();+ expect(within(active).queryByTestId("seat-switch")).toBeNull();+ expect(within(second).getByTestId("seat-switch")).toBeTruthy();+ expect(within(third).getByTestId("seat-switch")).toBeTruthy();+ });++ it("moves the tool and its running agents with one click and says what happened", async () => {+ vi.mocked(switchSeat).mockResolvedValue({+ active_account: "c2",+ active_label: "Seat c2",+ moved: 2,+ queued: 1,+ message: "",+ });+ const [, second] = await rows();+ fireEvent.click(within(second).getByTestId("seat-switch"));+ await waitFor(() => expect(switchSeat).toHaveBeenCalledWith("claude", "c2"));+ const notice = await screen.findByTestId("seat-switch-notice");+ expect(notice.textContent).toContain("Seat c2");+ expect(notice.textContent).toContain("2");+ expect(notice.textContent).toContain("1");+ // The account list is read again so the Active badge follows.+ await waitFor(() => expect(vi.mocked(fetchAgentAccounts).mock.calls.length).toBeGreaterThan(1));+ });++ it("reports a failed switch instead of pretending", async () => {+ vi.mocked(switchSeat).mockRejectedValue(new Error("That account no longer exists."));+ const [, second] = await rows();+ fireEvent.click(within(second).getByTestId("seat-switch"));+ const notice = await screen.findByTestId("seat-switch-notice");+ expect(notice.textContent).toContain("That account no longer exists.");+ });++ it("marks a seat that is used up and shows the last automatic switch", async () => {+ const [, , third] = await rows();+ expect(within(third).getByTestId("seat-empty")).toBeTruthy();+ const event = await screen.findByTestId("seat-switch-event");+ expect(event.textContent).toContain("Seat c3");+ expect(event.textContent).toContain("Seat c1");+ });++ it("turns automatic switching off", async () => {+ vi.mocked(updateAutoSwitch).mockResolvedValue({ ...STATE, enabled: false });+ await rows();+ fireEvent.click(screen.getByTestId("auto-switch-toggle"));+ await waitFor(() => expect(updateAutoSwitch).toHaveBeenCalledWith({ enabled: false }));+ });++ it("draws no switching UI on a backend without the feature", async () => {+ vi.mocked(fetchAutoSwitch).mockResolvedValue(null);+ render(<SubscriptionsTab />);+ await screen.findAllByTestId("subscription-row");+ expect(screen.queryByTestId("auto-switch-bar")).toBeNull();+ expect(screen.queryByTestId("seat-switch")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.tsxnew file mode 100644index 0000000000..be34e5a636--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SeatSwitch.tsx@@ -0,0 +1,260 @@+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Loader2 } from "lucide-react";+import { fill, useT, useUiLanguage } from "@/i18n";+import {+ fetchAutoSwitch,+ switchSeat,+ updateAutoSwitch,+ type AutoSwitchState,+ type SeatSwitchEvent,+} from "@/lib/agentAccountsApi";+import { cn } from "@/lib/utils";+import { BrandedSelect } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { QuickTooltip } from "@/components/ui/tooltip";+import { useEventStore } from "@/store/events";+import type { SubscriptionRow } from "./subscriptionsModel";++/**+ * The switch state is local to the backend (no provider is asked), so it can+ * be polled more often than usage: an automatic switch should show up in the+ * panel within moments, not at the next usage tick.+ */+const POLL_MS = 15_000;+const POLL_JITTER_MS = 5_000;++/** The spent share at which work moves on, offered as "how much is left". */+const THRESHOLDS = [90, 95, 97, 99, 100] as const;++interface Notice {+ text: string;+ error?: boolean;+}++interface SeatSwitchValue {+ state: AutoSwitchState | null;+ /** The account a one-click switch is moving to right now. */+ pending: string | null;+ notice: Notice | null;+ switchTo: (platform: string, accountId: string, label: string) => Promise<void>;+ setAuto: (change: { enabled?: boolean; at_percent?: number }) => Promise<void>;+ toolName: (platform: string) => string;+}++const SeatSwitchContext = createContext<SeatSwitchValue | null>(null);++/**+ * One-click and automatic subscription switching for the Subscriptions tab.+ *+ * ``onSwitched`` re-reads the account list, so the Active badge follows a+ * switch at once — including one the backend made on its own.+ */+export function SeatSwitchProvider({+ children,+ onSwitched,+ toolNames,+}: {+ children: ReactNode;+ onSwitched: () => void;+ toolNames: Record<string, string>;+}) {+ const t = useT();+ const [state, setState] = useState<AutoSwitchState | null>(null);+ const [pending, setPending] = useState<string | null>(null);+ const [notice, setNotice] = useState<Notice | null>(null);+ const [revision, setRevision] = useState(0);+ const lastEvent = useRef<number | null>(null);+ const switched = useRef(onSwitched);+ switched.current = onSwitched;++ useEffect(() => {+ let alive = true;+ let timer: number | undefined;+ const tick = async () => {+ if (useEventStore.getState().activeSection === "agentic-ide") {+ try {+ const next = await fetchAutoSwitch();+ if (alive) {+ setState(next);+ const newest = next?.events[0]?.at ?? 0;+ // An automatic switch moved the badge: re-read the accounts. The+ // first reading only records where the history stands.+ if (lastEvent.current !== null && newest > lastEvent.current) switched.current();+ lastEvent.current = newest;+ }+ } catch {+ // Keep the last answer on screen; the next tick tries again.+ }+ }+ if (alive) timer = window.setTimeout(tick, POLL_MS + Math.random() * POLL_JITTER_MS);+ };+ void tick();+ return () => {+ alive = false;+ window.clearTimeout(timer);+ };+ }, [revision]);++ const switchTo = useCallback(+ async (platform: string, accountId: string, label: string) => {+ setPending(accountId);+ setNotice(null);+ try {+ const result = await switchSeat(platform, accountId);+ const parts = [fill(t("ide_side_panel.subscriptions.switch.done"), { label: result.active_label || label })];+ if (result.moved) parts.push(fill(t("ide_side_panel.subscriptions.switch.moved"), { n: result.moved }));+ if (result.queued) parts.push(fill(t("ide_side_panel.subscriptions.switch.queued"), { n: result.queued }));+ setNotice({ text: parts.join(" ") });+ switched.current();+ setRevision((value) => value + 1);+ } catch (err) {+ setNotice({ text: fill(t("ide_side_panel.subscriptions.switch.failed"), { error: (err as Error).message }), error: true });+ } finally {+ setPending(null);+ }+ },+ [t],+ );++ const setAuto = useCallback(async (change: { enabled?: boolean; at_percent?: number }) => {+ try {+ setState(await updateAutoSwitch(change));+ } catch (err) {+ setNotice({ text: fill(t("ide_side_panel.subscriptions.switch.failed"), { error: (err as Error).message }), error: true });+ }+ }, [t]);++ const toolName = useCallback((platform: string) => toolNames[platform] || platform, [toolNames]);+ const value = useMemo(+ () => ({ state, pending, notice, switchTo, setAuto, toolName }),+ [state, pending, notice, switchTo, setAuto, toolName],+ );+ return <SeatSwitchContext.Provider value={value}>{children}</SeatSwitchContext.Provider>;+}++function useSeatSwitch(): SeatSwitchValue | null {+ return useContext(SeatSwitchContext);+}++function clock(at: number, lang: string): string {+ return new Intl.DateTimeFormat(lang, { hour: "2-digit", minute: "2-digit" }).format(at * 1000);+}++function eventText(t: (key: string) => string, event: SeatSwitchEvent, tool: string, lang: string): string {+ const base = "ide_side_panel.subscriptions.switch";+ const vars = { time: clock(event.at, lang), tool, from: event.from_label, to: event.to_label };+ if (event.reason === "limit") return fill(t(`${base}.event_limit`), vars);+ if (event.reason === "threshold") return fill(t(`${base}.event_threshold`), vars);+ if (event.reason === "no_seat") return fill(t(`${base}.event_no_seat`), vars);+ if (event.reason === "refilled") return fill(t(`${base}.event_refilled`), vars);+ return fill(t(`${base}.event_manual`), vars);+}++/**+ * The bar under the tab header: whether work moves on by itself, when, and+ * the last thing that happened. Absent on a backend without the feature.+ */+export function AutoSwitchBar() {+ const t = useT();+ const lang = useUiLanguage();+ const seat = useSeatSwitch();+ const state = seat?.state;+ const options = useMemo(+ () =>+ THRESHOLDS.map((percent) => ({+ value: String(percent),+ label:+ percent >= 100+ ? t("ide_side_panel.subscriptions.switch.at_limit")+ : fill(t("ide_side_panel.subscriptions.switch.at_left"), { left: 100 - percent }),+ })),+ [t],+ );+ if (!seat || !state) return null;+ const latest = state.events[0];+ const current = THRESHOLDS.reduce((best, value) =>+ Math.abs(value - state.at_percent) < Math.abs(best - state.at_percent) ? value : best,+ );+ return (+ <div data-testid="auto-switch-bar" className="shrink-0 space-y-1.5 border-b border-border/60 px-3 py-2">+ <div className="flex min-h-7 items-center gap-2">+ <Switch+ id="auto-switch-toggle"+ data-testid="auto-switch-toggle"+ checked={state.enabled}+ onCheckedChange={(enabled) => void seat.setAuto({ enabled })}+ aria-label={t("ide_side_panel.subscriptions.switch.auto")}+ />+ <QuickTooltip content={t("ide_side_panel.subscriptions.switch.auto_tip")} side="bottom" className="min-w-0 flex-1">+ <label htmlFor="auto-switch-toggle" className="block cursor-pointer truncate text-[11.5px] text-foreground">+ {t("ide_side_panel.subscriptions.switch.auto")}+ </label>+ </QuickTooltip>+ <BrandedSelect+ value={String(current)}+ options={options}+ onValueChange={(value) => void seat.setAuto({ at_percent: Number(value) })}+ ariaLabel={t("ide_side_panel.subscriptions.switch.threshold")}+ disabled={!state.enabled}+ testId="auto-switch-threshold"+ className="h-7 w-auto shrink-0 text-[11px]"+ />+ </div>+ {seat.notice && (+ <p+ data-testid="seat-switch-notice"+ role="status"+ className={cn("text-[10.5px]", seat.notice.error ? "text-destructive" : "text-muted-foreground")}+ >+ {seat.notice.text}+ </p>+ )}+ {!seat.notice && latest && (+ <p data-testid="seat-switch-event" className="truncate text-[10.5px] text-muted-foreground" title={eventText(t, latest, seat.toolName(latest.platform), lang)}>+ {eventText(t, latest, seat.toolName(latest.platform), lang)}+ </p>+ )}+ </div>+ );+}++/**+ * One click: this subscription becomes the active one and every running agent+ * of the tool moves onto it, each continuing its own conversation. Shown on+ * every signed-in row that is not already active.+ */+export function SwitchSeatButton({ row }: { row: SubscriptionRow }) {+ const t = useT();+ const lang = useUiLanguage();+ const seat = useSeatSwitch();+ if (!seat?.state || row.active) return null;+ const { account } = row;+ const ids = new Set(row.seats.map((item) => item.id));+ const empty = seat.state.exhausted+ .filter((item) => ids.has(item.account_id))+ .reduce((latest, item) => Math.max(latest, item.until), 0);+ const busy = seat.pending !== null;+ const mine = seat.pending === account.id;+ const tool = seat.toolName(account.platform);+ return (+ <span className="flex shrink-0 items-center gap-1.5">+ {empty > 0 && (+ <span data-testid="seat-empty" className="text-[10px] tabular-nums text-muted-foreground">+ {fill(t("ide_side_panel.subscriptions.switch.empty_until"), { when: clock(empty, lang) })}+ </span>+ )}+ <QuickTooltip content={fill(t("ide_side_panel.subscriptions.switch.use_tip"), { tool })} side="bottom" className="inline-flex">+ <button+ type="button"+ data-testid="seat-switch"+ disabled={busy}+ onClick={() => void seat.switchTo(account.platform, account.id, account.email || account.label)}+ className="inline-flex h-6 items-center gap-1 rounded-md border border-border px-2 text-[11px] text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ >+ {mine && <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />}+ {mine ? t("ide_side_panel.subscriptions.switch.switching") : t("ide_side_panel.subscriptions.switch.use")}+ </button>+ </QuickTooltip>+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SubscriptionsTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SubscriptionsTab.tsxindex e7f8629c80..fd910a72d1 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SubscriptionsTab.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/subscriptions/SubscriptionsTab.tsx@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { QuickTooltip } from "@/components/ui/tooltip";import { useEventStore } from "@/store/events";+import { AutoSwitchBar, SeatSwitchProvider, SwitchSeatButton } from "./SeatSwitch";import { BankedResets } from "./BankedResets";import {groupSubscriptions,@@ -218,51 +219,54 @@ function SubscriptionLine({ row, now, revision, onUsage }: { row: SubscriptionRoconst tightest = tightestWindow(row.usage);return (<li data-testid="subscription-row" data-account={account.id} data-active={row.active || undefined}>- <button- type="button"- aria-expanded={open}- aria-controls={detailsId}- onClick={() => setOpen((value) => !value)}- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <ChevronRight- className={cn(- "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none",- open && "rotate-90",- )}- aria-hidden- />- <span className="flex min-w-0 flex-1 flex-col leading-tight">- <span className="flex min-w-0 items-center gap-1.5">- <span className="truncate text-[12.5px] font-medium text-foreground">{title}</span>- {row.active && (- <QuickTooltip content={t("ide_side_panel.subscriptions.active_tip")} side="bottom" className="inline-flex shrink-0">- <span className="rounded border border-border px-1 text-[9.5px] uppercase tracking-wide text-muted-foreground">- {t("ide_side_panel.subscriptions.active")}- </span>- </QuickTooltip>- )}- {account.warning && (- <QuickTooltip content={account.warning} side="bottom" className="inline-flex shrink-0">- <AlertTriangle- data-testid="subscription-warning"- className="h-3.5 w-3.5 text-warning"- aria-label={account.warning}- />- </QuickTooltip>+ <div className="flex items-center gap-1.5 pr-1">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={detailsId}+ onClick={() => setOpen((value) => !value)}+ className="flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ChevronRight+ className={cn(+ "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none",+ open && "rotate-90",)}+ aria-hidden+ />+ <span className="flex min-w-0 flex-1 flex-col leading-tight">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[12.5px] font-medium text-foreground">{title}</span>+ {row.active && (+ <QuickTooltip content={t("ide_side_panel.subscriptions.active_tip")} side="bottom" className="inline-flex shrink-0">+ <span className="rounded border border-border px-1 text-[9.5px] uppercase tracking-wide text-muted-foreground">+ {t("ide_side_panel.subscriptions.active")}+ </span>+ </QuickTooltip>+ )}+ {account.warning && (+ <QuickTooltip content={account.warning} side="bottom" className="inline-flex shrink-0">+ <AlertTriangle+ data-testid="subscription-warning"+ className="h-3.5 w-3.5 text-warning"+ aria-label={account.warning}+ />+ </QuickTooltip>+ )}+ </span>+ {subtitle && <span className="truncate text-[11px] text-muted-foreground">{subtitle}</span>}</span>- {subtitle && <span className="truncate text-[11px] text-muted-foreground">{subtitle}</span>}- </span>- {tightest && (- <span- data-testid="subscription-peak"- className={cn("shrink-0 text-[11px] tabular-nums", TEXT_TONE[tightest.severity] ?? TEXT_TONE.normal)}- >- {Math.round(tightest.percent)}%- </span>- )}- </button>+ {tightest && (+ <span+ data-testid="subscription-peak"+ className={cn("shrink-0 text-[11px] tabular-nums", TEXT_TONE[tightest.severity] ?? TEXT_TONE.normal)}+ >+ {Math.round(tightest.percent)}%+ </span>+ )}+ </button>+ <SwitchSeatButton row={row} />+ </div>{open && (<div id={detailsId} data-testid="subscription-details" className="pb-2 pl-7 pr-2 pt-1"><UsageDetails usage={row.usage} now={now} />@@ -300,51 +304,55 @@ export function SubscriptionsTab() {const { accounts, usage, error, loading, refresh, updateUsage, revision } = useSubscriptions();const now = useMinuteClock();const groups = groupSubscriptions(accounts, usage);+ const toolNames = Object.fromEntries(groups.map((group) => [group.platform, group.displayName]));return (- <div data-testid="ide-subscriptions-tab" className="flex h-full min-h-0 flex-col">- <div className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 px-3">- <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted-foreground">- {t("ide_side_panel.subscriptions.hint")}- </span>- <QuickTooltip content={t("ide_side_panel.subscriptions.refresh")} side="bottom" className="inline-flex shrink-0">- <button- type="button"- data-testid="subscriptions-refresh"- aria-label={t("ide_side_panel.subscriptions.refresh")}- disabled={loading}- onClick={refresh}- className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"- >- {loading ? (- <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />- ) : (- <RefreshCw className="h-3.5 w-3.5" aria-hidden />- )}- </button>- </QuickTooltip>- </div>- <div className="min-h-0 flex-1 overflow-y-auto">- {error && (- <p data-testid="subscriptions-error" className="mx-3 mt-3 text-[11.5px] text-destructive">- {fill(t("ide_side_panel.subscriptions.error"), { error })}- </p>- )}- {!accounts && !error && (- <div className="flex justify-center py-6">- <Loader2 className="h-4 w-4 animate-spin text-muted-foreground motion-reduce:animate-none" aria-hidden />+ <SeatSwitchProvider onSwitched={refresh} toolNames={toolNames}>+ <div data-testid="ide-subscriptions-tab" className="flex h-full min-h-0 flex-col">+ <div className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 px-3">+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted-foreground">+ {t("ide_side_panel.subscriptions.hint")}+ </span>+ <QuickTooltip content={t("ide_side_panel.subscriptions.refresh")} side="bottom" className="inline-flex shrink-0">+ <button+ type="button"+ data-testid="subscriptions-refresh"+ aria-label={t("ide_side_panel.subscriptions.refresh")}+ disabled={loading}+ onClick={refresh}+ className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"+ >+ {loading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />+ )}+ </button>+ </QuickTooltip>+ </div>+ <AutoSwitchBar />+ <div className="min-h-0 flex-1 overflow-y-auto">+ {error && (+ <p data-testid="subscriptions-error" className="mx-3 mt-3 text-[11.5px] text-destructive">+ {fill(t("ide_side_panel.subscriptions.error"), { error })}+ </p>+ )}+ {!accounts && !error && (+ <div className="flex justify-center py-6">+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground motion-reduce:animate-none" aria-hidden />+ </div>+ )}+ {accounts && groups.length === 0 && (+ <p data-testid="subscriptions-empty" className="mx-3 mt-3 text-[12px] text-muted-foreground">+ {t("ide_side_panel.subscriptions.empty")}+ </p>+ )}+ <div className="divide-y divide-border/60">+ {groups.map((group) => (+ <SubscriptionBlock key={group.platform} group={group} now={now} revision={revision} onUsage={updateUsage} />+ ))}</div>- )}- {accounts && groups.length === 0 && (- <p data-testid="subscriptions-empty" className="mx-3 mt-3 text-[12px] text-muted-foreground">- {t("ide_side_panel.subscriptions.empty")}- </p>- )}- <div className="divide-y divide-border/60">- {groups.map((group) => (- <SubscriptionBlock key={group.platform} group={group} now={now} revision={revision} onUsage={updateUsage} />- ))}</div></div>- </div>+ </SeatSwitchProvider>);}diff --git a/jarvis/ui/web/frontend/src/components/layout/DetachedViewPlaceholder.tsx b/jarvis/ui/web/frontend/src/components/layout/DetachedViewPlaceholder.tsxindex 46c0c775c2..a74294150d 100644--- a/jarvis/ui/web/frontend/src/components/layout/DetachedViewPlaceholder.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/DetachedViewPlaceholder.tsx@@ -4,7 +4,7 @@ import { AppWindow } from "lucide-react";import { EmptyState } from "@/components/layout/EmptyState";import { Button } from "@/components/ui/button";import { useT } from "@/i18n";-import type { SectionId } from "@/store/events";+import { useEventStore, type SectionId } from "@/store/events";/*** What a section shows in the MAIN window while it lives in its own detached@@ -26,15 +26,18 @@ export function DetachedViewPlaceholder({ view }: { view: SectionId }) {if (busy) return;setBusy(true);try {- await fetch(path, {+ const response = await fetch(path, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ view }),});+ const body = await response.json() as { ok?: boolean };+ if (!response.ok || !body.ok) throw new Error("Window operation was rejected");// No local state flip: the DetachedViewClosed WS event is the single// source of truth for the remount, same as a manual window close.- } catch {- /* backend unreachable — the buttons stay, the user can retry */+ } catch (error) {+ console.warn("Detached window operation failed", error);+ useEventStore.getState().pushToast("error", t(path.endsWith("reattach") ? "topbar.reattach_failed" : "topbar.detach_failed"));} finally {setBusy(false);}diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.settingsHub.test.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.settingsHub.test.tsxindex 27765dd4b4..9103a122fc 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.settingsHub.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.settingsHub.test.tsx@@ -10,6 +10,7 @@ vi.mock("@/views/ChatsSurface", () => ({ChatsSurface: () => <div data-testid="chats-surface" />,}));vi.mock("@/views/SettingsHubView", () => ({+ SettingsHubView: () => <div data-testid="standalone-settings" />,SettingsHubDialog: ({ onClose }: { onClose: () => void }) => (<button type="button" data-testid="settings-hub" onClick={onClose}>close</button>),@@ -25,6 +26,20 @@ afterEach(() => {});describe("MainView — every settings-hub id mounts the hub", () => {+ it("renders only the settings hub in its own window", async () => {+ useEventStore.setState({ activeSection: "profile", solo: true, detachedViews: ["settings"] });+ render(<MainView />);+ expect(await screen.findByTestId("standalone-settings")).toBeTruthy();+ expect(screen.queryByTestId("chats-surface")).toBeNull();+ expect(screen.queryByTestId("settings-hub")).toBeNull();+ });++ it("treats every settings tab as one detached window", async () => {+ useEventStore.setState({ activeSection: "apikeys", detachedViews: ["settings"] });+ render(<MainView />);+ expect(await screen.findByTestId("detached-view-placeholder")).toBeTruthy();+ expect(screen.queryByTestId("settings-hub")).toBeNull();+ });it.each(["settings","taskbar",diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex e517f713ad..ae44381978 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -14,6 +14,7 @@ import { cn } from "@/lib/utils";import { ViewErrorBoundary } from "@/components/ViewErrorBoundary";import { DetachedViewPlaceholder } from "@/components/layout/DetachedViewPlaceholder";import { SETTINGS_HUB_IDS } from "@/components/layout/navGroups";+import { detachedWindowFor } from "@/lib/sectionWindows";// Type-only, so the section's chunk stays split out of the entry bundle.import type { AgenticIdeViewProps } from "@/views/AgenticIdeView";// The default section is the one view that must be on screen the moment React@@ -65,6 +66,9 @@ function lazyPropView<P>(const SettingsHubDialog = lazyPropView<{ onClose: () => void }>(SETTINGS_HUB_IDS, () =>import("@/views/SettingsHubView").then((m) => ({ default: m.SettingsHubDialog })),);+const SettingsHubView = lazy(() =>+ import("@/views/SettingsHubView").then((m) => ({ default: m.SettingsHubView })),+);// The Agents section is the society (MASTERPLAN §4.1): stage + agents rail +// model cards. The board it replaced is the society's stage until the island// lands, loaded by SocietyView itself.@@ -85,7 +89,7 @@ const isSettingsHub = (section: string) =>// replacing it.const isOverlaySection = (section: string) => isPluginArea(section) || isSettingsHub(section);-const PluginsDialog = lazyPropView<{ onClose: () => void; area: PluginArea; onAreaChange: (area: PluginArea) => void }>(["plugins", "mcps", "skills"], () =>+const PluginsDialog = lazyPropView<{ onClose: () => void; area: PluginArea; standalone?: boolean; onAreaChange: (area: PluginArea) => void }>(["plugins", "mcps", "skills"], () =>import("@/views/PluginsDialog").then((m) => ({ default: m.PluginsDialog })),);// The prop type is named rather than inferred: inferring it from the loader's@@ -254,7 +258,10 @@ export function MainView() {isOverlaySection(active) ? "chats" : active,);if (!isOverlaySection(active) && backgroundSection !== active) setBackgroundSection(active);- const displayed = isOverlaySection(active) ? backgroundSection : active;+ const activeDetached = !solo ? detachedWindowFor(active, detachedViews) : undefined;+ const displayed = isOverlaySection(active) && !activeDetached ? backgroundSection : active;+ const displayedDetached = !solo ? detachedWindowFor(displayed, detachedViews) : undefined;+ const soloOverlay = solo && isOverlaySection(active);/** While a coding view lives in a detached solo window, THIS (non-solo)@@ -269,7 +276,7 @@ export function MainView() {detachedViews.some((v) => (CODING_SECTION_IDS as readonly string[]).includes(v));const stickyActive =- (CODING_SECTION_IDS as readonly string[]).includes(displayed) && !codingDetached;+ (CODING_SECTION_IDS as readonly string[]).includes(displayed) && !codingDetached && !soloOverlay;const [stickyMounted, setStickyMounted] = useState(stickyActive);useEffect(() => {if (stickyActive) setStickyMounted(true);@@ -280,13 +287,9 @@ export function MainView() {if (codingDetached) setStickyMounted(false);}, [codingDetached]);- if (codingDetached && (CODING_SECTION_IDS as readonly string[]).includes(displayed) && !isOverlaySection(active)) {- return <DetachedViewPlaceholder view={displayed} />;- }-return (<>- {stickyMounted && (+ {stickyMounted && !codingDetached && !soloOverlay && (<divclassName={cn("h-full w-full", !stickyActive && "hidden")}data-testid="sticky-agentic-ide"@@ -313,7 +316,7 @@ export function MainView() {</ViewErrorBoundary></div>)}- {!stickyActive && (+ {!stickyActive && !soloOverlay && (<ViewErrorBoundaryviewName={displayed}resetKey={displayed}@@ -322,23 +325,23 @@ export function MainView() {{/* Keyed on the active section so switching away from a still-loadingview cannot leave the previous section's fallback on screen. */}<Suspense key={displayed} fallback={<ViewLoadingFallback />}>- {codingDetached && (CODING_SECTION_IDS as readonly string[]).includes(displayed)- ? <DetachedViewPlaceholder view={displayed} />+ {displayedDetached+ ? <DetachedViewPlaceholder view={displayedDetached} />: <SwitchOnActiveSection active={displayed} />}</Suspense></ViewErrorBoundary>)}- {isPluginArea(active) && (+ {isPluginArea(active) && !activeDetached && (<ViewErrorBoundary viewName="plugins" resetKey="plugins" onRecover={() => setActive(backgroundSection)}><Suspense fallback={null}>- <PluginsDialog area={active} onAreaChange={setActive} onClose={() => setActive(backgroundSection)} />+ <PluginsDialog standalone={solo} area={active} onAreaChange={setActive} onClose={() => setActive(backgroundSection)} /></Suspense></ViewErrorBoundary>)}- {isSettingsHub(active) && (+ {isSettingsHub(active) && !activeDetached && (<ViewErrorBoundary viewName="settings" resetKey="settings" onRecover={() => setActive(backgroundSection)}><Suspense fallback={null}>- <SettingsHubDialog onClose={() => setActive(backgroundSection)} />+ {solo ? <SettingsHubView /> : <SettingsHubDialog onClose={() => setActive(backgroundSection)} />}</Suspense></ViewErrorBoundary>)}diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.test.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.test.tsxnew file mode 100644index 0000000000..4c414eae2d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.test.tsx@@ -0,0 +1,130 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SectionWindowButton } from "./SectionWindowButton";+import { useEventStore, type SectionId } from "@/store/events";+import { DETACHABLE_SECTIONS } from "@/lib/sectionWindows";++const bridge = vi.hoisted(() => ({ native: true }));+vi.mock("@/lib/embeddedDesktop", () => ({ hasEmbeddedDesktopBridge: () => bridge.native }));++beforeEach(() => {+ bridge.native = true;+ window.history.replaceState(null, "", "/");+ useEventStore.setState({ activeSection: "agents", solo: false, detachedViews: [], toasts: [] });+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });++describe("section windows", () => {+ it.each([...DETACHABLE_SECTIONS, "profile", "apikeys", "mcps", "skills", "cli-test-hub", "agentic-ide-classic", "chat-workspace"] as SectionId[])(+ "shows a text button on the detachable %s section", (activeSection) => {+ useEventStore.setState({ activeSection });+ render(<SectionWindowButton />);+ expect(screen.getByRole("button", { name: "Detach window" }).textContent).toBe("Detach window");+ },+ );+ it("waits for the desktop bridge before offering the IDE handoff", () => {+ bridge.native = false;+ useEventStore.setState({ activeSection: "agentic-ide" });+ render(<SectionWindowButton />);+ expect(screen.queryByRole("button")).toBeNull();+ bridge.native = true;+ act(() => window.dispatchEvent(new Event("jarvis-token-ready")));+ expect(screen.getByRole("button")).toBeTruthy();+ });+ it.each(["chats", "dictation", "dictionary", "voice-shortcuts", "voice-language", "voice-api-keys"] as SectionId[])(+ "leaves %s in the main window", (activeSection) => {+ useEventStore.setState({ activeSection });+ render(<SectionWindowButton />);+ expect(screen.queryByRole("button")).toBeNull();+ },+ );++ it("opens the selected settings tab and lets the backend own its family", async () => {+ useEventStore.setState({ activeSection: "profile" });+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button"));+ await waitFor(() => expect(screen.getByRole("button").hasAttribute("disabled")).toBe(false));+ expect(fetcher).toHaveBeenCalledWith("/api/window/detach", expect.objectContaining({ body: '{"view":"profile"}' }));+ });++ it("focuses the existing family owner after changing tabs", async () => {+ useEventStore.setState({ activeSection: "apikeys", detachedViews: ["settings"] });+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button", { name: "Show window" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledWith("/api/window/detach", expect.objectContaining({ body: '{"view":"settings"}' })));+ });++ it("restores main before returning a solo window after a tab change", async () => {+ window.history.replaceState(null, "", "/?view=apikeys&solo=1&window=settings");+ useEventStore.setState({ activeSection: "apikeys", solo: true });+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button", { name: "Back to main window" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));+ expect(fetcher.mock.calls[0][0]).toBe("/api/window/focus");+ expect(fetcher.mock.calls[1]).toEqual(["/api/window/reattach", expect.objectContaining({ body: '{"view":"settings"}' })]);+ });++ it("keeps return available after navigating to a section that cannot detach", async () => {+ window.history.replaceState(null, "", "/?view=dictation&solo=1&window=settings");+ useEventStore.setState({ activeSection: "dictation", solo: true });+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button", { name: "Back to main window" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledWith("/api/window/reattach", expect.objectContaining({ body: '{"view":"settings"}' })));+ });++ it("keeps the detached window open if main cannot be restored", async () => {+ window.history.replaceState(null, "", "/?view=agents&solo=1");+ useEventStore.setState({ activeSection: "agents", solo: true });+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: false }) });+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ await act(async () => fireEvent.click(screen.getByRole("button", { name: "Back to main window" })));+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(fetcher.mock.calls[0][0]).toBe("/api/window/focus");+ expect(useEventStore.getState().toasts.at(-1)?.message).toBe("Could not bring the view back");+ });++ it("keeps the current view usable and reports a rejected operation", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: false, reason: "no_live_window" }) }));+ render(<SectionWindowButton />);+ await act(async () => fireEvent.click(screen.getByRole("button")));+ expect(useEventStore.getState().activeSection).toBe("agents");+ expect(useEventStore.getState().toasts.at(-1)?.message).toBe("Could not open a separate window");+ expect(screen.getByRole("button").hasAttribute("disabled")).toBe(false);+ });++ it("opens a named browser tab synchronously without calling the native shell", () => {+ bridge.native = false;+ useEventStore.setState({ activeSection: "profile" });+ const open = vi.spyOn(window, "open").mockReturnValue(window);+ const fetcher = vi.fn();+ vi.stubGlobal("fetch", fetcher);+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button"));+ expect(open).toHaveBeenCalledWith("/?view=profile&solo=1&window=settings", "jarvis-section-settings");+ expect(fetcher).not.toHaveBeenCalled();+ });++ it("closes a browser pop-out and focuses its original main window", () => {+ bridge.native = false;+ useEventStore.setState({ solo: true });+ const focus = vi.fn();+ vi.stubGlobal("opener", { closed: false, location: { origin: window.location.origin }, focus });+ const close = vi.spyOn(window, "close").mockImplementation(() => {});+ render(<SectionWindowButton />);+ fireEvent.click(screen.getByRole("button", { name: "Back to main window" }));+ expect(focus).toHaveBeenCalledOnce();+ expect(close).toHaveBeenCalledOnce();+ expect(focus.mock.invocationCallOrder[0]).toBeLessThan(close.mock.invocationCallOrder[0]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.tsxnew file mode 100644index 0000000000..17616276f9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/SectionWindowButton.tsx@@ -0,0 +1,92 @@+import { useEffect, useRef, useState } from "react";+import { AppWindow, PanelLeftClose } from "lucide-react";+import { hasEmbeddedDesktopBridge } from "@/lib/embeddedDesktop";+import { useT } from "@/i18n";+import { DETACHABLE_SECTIONS, detachedWindowFor, sectionWindow, windowIdentity } from "@/lib/sectionWindows";+import { useEventStore } from "@/store/events";++/** Native windows are owned by the desktop shell; browsers use named tabs. */+export function SectionWindowButton() {+ const t = useT();+ const section = useEventStore((s) => s.activeSection);+ const solo = useEventStore((s) => s.solo);+ const detached = useEventStore((s) => s.detachedViews);+ const pending = useRef(false);+ const [busy, setBusy] = useState(false);+ const [embedded, setEmbedded] = useState(hasEmbeddedDesktopBridge);+ useEffect(() => {+ const ready = () => setEmbedded(hasEmbeddedDesktopBridge());+ window.addEventListener("jarvis-token-ready", ready);+ window.addEventListener("pywebviewready", ready);+ ready();+ return () => {+ window.removeEventListener("jarvis-token-ready", ready);+ window.removeEventListener("pywebviewready", ready);+ };+ }, []);+ const owner = sectionWindow(section);+ if (!solo && !DETACHABLE_SECTIONS.includes(owner)) return null;+ // Only the native registry can hand off the IDE's single PTY subscription.+ // A browser tab cannot safely keep a second terminal view alive.+ if (!solo && owner === "agentic-ide" && !embedded) return null;+ const existing = detachedWindowFor(section, detached);+ const label = t(solo ? "topbar.return_to_main" : existing ? "topbar.detach_focus" : "topbar.detach");+ const hint = solo ? t("topbar.return_to_main_hint") : existing ? label : t("topbar.detach_hint");++ async function onClick() {+ if (pending.current) return;+ const native = hasEmbeddedDesktopBridge();+ if (!native) {+ if (solo) {+ try {+ const parent = window.opener as Window | null;+ if (parent && !parent.closed && parent.location.origin === window.location.origin) {+ parent.focus();+ window.close();+ return;+ }+ } catch {+ // The opener may have navigated to another origin. Keep this tab as main.+ }+ window.location.assign(`/?view=${encodeURIComponent(section)}`);+ } else {+ // Synchronous with the gesture so popup blockers do not eat the tab.+ const opened = window.open(`/?view=${section}&solo=1&window=${owner}`, `jarvis-section-${owner}`);+ if (!opened) useEventStore.getState().pushToast("error", t("topbar.detach_failed"));+ }+ return;+ }+ pending.current = true;+ setBusy(true);+ try {+ const view = solo ? windowIdentity(window.location.search, section) : existing ?? section;+ if (solo) {+ // Restore main before closing the last detached window.+ const focus = await fetch("/api/window/focus", { method: "POST" });+ const body = await focus.json() as { ok?: boolean };+ if (!focus.ok || !body.ok) throw new Error("Main window could not be restored");+ }+ const response = await fetch(`/api/window/${solo ? "reattach" : "detach"}`, {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ view }),+ });+ const body = await response.json() as { ok?: boolean };+ if (!response.ok || !body.ok) throw new Error("Window operation was rejected");+ } catch (error) {+ console.warn("Section window operation failed", error);+ useEventStore.getState().pushToast("error", t(solo ? "topbar.reattach_failed" : "topbar.detach_failed"));+ } finally {+ pending.current = false;+ setBusy(false);+ }+ }++ const Icon = solo ? PanelLeftClose : AppWindow;+ return (+ <button type="button" title={hint} aria-label={label} disabled={busy}+ data-testid="detach-view-button" onClick={() => void onClick()}+ className="inline-flex h-8 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">+ <Icon aria-hidden className="h-4 w-4 shrink-0" />+ <span>{label}</span>+ </button>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsxindex 1c0398cb9c..6fcef52b5b 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx@@ -29,11 +29,11 @@ beforeEach(() => {afterEach(() => vi.restoreAllMocks());describe("TopBar caption buttons", () => {- it("carries no theme, restart or own-window toggles", () => {- useEventStore.setState({ activeSection: "agentic-ide" });+ it("offers a section window without theme or restart controls", () => {+ useEventStore.setState({ activeSection: "agents" });render(<TopBar />);expect(screen.queryByTestId("theme-toggle")).toBeNull();- expect(screen.queryByTestId("detach-view-button")).toBeNull();+ expect(screen.getByTestId("detach-view-button")).toBeTruthy();expect(screen.queryByTestId("section-nav-sidebar")).toBeNull();expect(screen.queryByRole("button", { name: /restart/i })).toBeNull();});diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsxindex 112408097f..eafaf64463 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx@@ -12,6 +12,8 @@ import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { CodingModeBadge } from "@/components/layout/CodingModeBadge";import { SectionNavButtons } from "@/components/layout/SectionNavButtons";+import { SectionWindowButton } from "@/components/layout/SectionWindowButton";+import { sectionWindow } from "@/lib/sectionWindows";import { IdeLayoutSwitch } from "@/components/agentic/threads/IdeLayoutSwitch";import { IDE_SECTIONS } from "@/lib/ideSections";import { openExternalUrl } from "@/lib/openExternal";@@ -77,6 +79,8 @@ const CHROME_ARMED = "bg-warning text-background";export function TopBar() {const chrome = useDesktopChrome();+ const solo = useEventStore((s) => s.solo);+ const section = useEventStore((s) => sectionWindow(s.activeSection));const controls = chrome.frameless ? chrome.controls : "none";return (@@ -94,6 +98,8 @@ export function TopBar() {<WindowControls controls={controls} maximized={chrome.maximized} onCommand={chrome.command} />)}<SectionNavButtons />+ {/* Modal hubs carry this action inside their own focus scope. */}+ {(solo || !["settings", "plugins"].includes(section)) && <SectionWindowButton />}<divclassName="pywebview-drag-region min-w-0 flex-1"onDoubleClick={() => {diff --git a/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsx b/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsxindex 4548a9cc4d..1470b60949 100644--- a/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsx@@ -5,6 +5,7 @@ import { hasEmbeddedDesktopBridge } from "@/components/voice/BrowserRealtimeContimport { useT } from "@/i18n";import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";+import { windowIdentity } from "@/lib/sectionWindows";export interface DesktopChrome {frameless: boolean;@@ -44,7 +45,7 @@ export function useDesktopChrome(): DesktopChrome & {const command = useCallback((action: "minimize" | "maximize" | "close") => {const solo = useEventStore.getState().solo;- const view = solo ? useEventStore.getState().activeSection : null;+ const view = solo ? windowIdentity(window.location.search, useEventStore.getState().activeSection) : null;void fetch("/api/window/command", {method: "POST",headers: { "Content-Type": "application/json" },diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsxindex 1ee4215d99..919c358433 100644--- a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx+++ b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx@@ -14,6 +14,8 @@ import {ACCESSORY_CATALOG, FACE_SLOTS, partDepth, resolveFill, smoothPath, symbolViewBox, wornAccessories,type AccessoryChoice, type AccessoryItem, type AccessoryPart,} from "./companion/accessories";+import { SkinDefs, SkinGlow, SkinOverlay } from "./companion/SkinLayers";+import type { CompanionSkin } from "./companion/skins";import "./agentSymbol.css";export type { SymbolShape } from "./companion/appearance";@@ -156,7 +158,7 @@ function ExpressiveEye({ side, cx, cy, rx, ry }: { side: "l" | "r"; cx: number;</g>;}-export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = false, accessories, expressive = false }: { shape: SymbolShape; color: string; size: number; eyes?: "dots" | "lines"; thinking?: boolean; accessories?: AccessoryChoice; expressive?: boolean }) {+export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = false, accessories, expressive = false, skin }: { shape: SymbolShape; color: string; size: number; eyes?: "dots" | "lines"; thinking?: boolean; accessories?: AccessoryChoice; expressive?: boolean; skin?: CompanionSkin }) {const eyeY = shape === "cloud" || shape === "triangle" ? 23 : shape === "drop" ? 25 : 17.2;const ink = companionEyeColors(color);const maskId = `agent-body-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;@@ -165,6 +167,9 @@ export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = falconst draw = (items: AccessoryItem[], regions = false) => items.map(item => <AccessoryItemShapes key={item.id} item={item} shape={shape} color={color} regions={regions} uid={maskId} />);const faceTransform = `translate(2 -0.6) rotate(-14 20 ${eyeY})`;const onFace = worn.filter(item => FACE_SLOTS.has(item.slot));+ // A design paints the body with its gradient; `color` stays its blend for everything else.+ const skinId = `${maskId}-skin`;+ const body = (fill: string) => <SymbolBody shape={shape} color={fill} />;return (<svg aria-hidden focusable="false" data-agent-symbol={shape} data-expressive={expressive ? "true" : undefined} data-thinking={thinking ? "true" : undefined} width={size} height={size} style={{ width: size, height: size, flexShrink: 0 }} viewBox={viewBox} className="society-agent-symbol block"><g className="agent-symbol-character">@@ -180,7 +185,9 @@ export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = fal<g clipPath={`url(#${clipId})`}><SymbolBody shape={shape} color={resolveFill(part.fill, color)} grow={part.w} /></g></g>;}))}- <g data-agent-body><SymbolBody shape={shape} color={color} /></g>+ {skin && <><SkinDefs id={skinId} skin={skin} /><SkinGlow id={skinId} skin={skin} body={body} /></>}+ <g data-agent-body data-skin={skin ? skin.effect : undefined}>{body(skin ? `url(#${skinId})` : color)}</g>+ {skin && <SkinOverlay id={skinId} skin={skin} body={body} />}{worn.some(item => item.regions) && <><mask id={maskId} maskUnits="userSpaceOnUse" x={-20} y={-20} width={80} height={84}><SymbolBody shape={shape} color="#ffffff" /></mask><g mask={`url(#${maskId})`}>{draw(worn, true)}</g>diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex 223914c372..02a30654df 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -104,7 +104,8 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {const matched = seat.provider.curated_models.filter((model) => matchesModel(seat, model, search, titles[index]));// Newest of each model line first; earlier versions fold away. Catalogs// with their own fold (OpenCode, OpenRouter) keep their order.- const ranked = collapsibleModels(seat) ? { current: matched, older: [] } : rankModels(matched);+ const ranked = seat.kind === "local" || collapsibleModels(seat)+ ? { current: matched, older: [] } : rankModels(matched);return { seat, title: titles[index], models: [...ranked.current, ...ranked.older], older: new Set(ranked.older) };}).filter((group) => group.models.length > 0).sort((a, b) =>modelGroupOrder(a.seat) - modelGroupOrder(b.seat) || a.title.localeCompare(b.title));diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.tsindex 7e8134c359..db5a96ca65 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.test.ts@@ -33,6 +33,16 @@ test("live labels retain model-specific effort metadata and duplicate ids collapexpect(modelEffort(seat, "small", "high")).toBe("low");});+test("agent model choices exclude only explicitly tool-incapable models", () => {+ const [seat] = modelSeats([option({ id: "ollama", runner: "brain", keyless: true,+ connected: true, cli_installed: null, models_source: "live" })], [], { ollama: [+ { id: "text-only", label: "Text", tools: false },+ { id: "custom-import", label: "Custom", tools: true },+ { id: "unknown", label: "Unknown", tools: null },+ ] });+ expect(seat.provider.curated_models.map((model) => model.id)).toEqual(["custom-import", "unknown"]);+});+test("free model detection does not infer price from labels, size or unrelated aliases", () => {for (const id of ["opencode/next-free", "openrouter/vendor/model:free", "opencode/big-pickle"]) {expect(isFreeOpenCodeModel({ id, label: "Model" })).toBe(true);diff --git a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.tsindex 21036319f6..10f3abaae2 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/modelChoices.ts@@ -39,7 +39,10 @@ export function modelSeats(options: ProviderOption[], providers: SocietyProvider// Installed CLIs without an account reader (such as OpenCode) own their login.const known = new Set(usable.filter((option) => option.connected).map((option) => option.id));return brainSeats(usable, providers, mergedLive, known).map((seat) => {- const models = [...new Map(seat.provider.curated_models.map((model) => [model.id, model])).values()];+ // Agents need tools. Unknown metadata remains selectable; a provider's+ // explicit refusal must not become the default for a newly created agent.+ const models = [...new Map(seat.provider.curated_models.filter((model) => model.tools !== false)+ .map((model) => [model.id, model])).values()];// The IDE can launch a CLI without a model override. Preserve that same// choice when the vendor keeps its catalog private or its discovery fails.// API/local seats still need their own model ids; an empty id is not one.diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.tsindex c57bfdd572..bee823d3f9 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts@@ -70,7 +70,7 @@ export function useModelMenuData(chatCatalog: AgentChatCatalog | null = null, ch}), [liveProviders]);const models = useQueries({ queries: liveProviders.map((provider) => ({queryKey: ["society", "model-menu", "live", provider.id],- queryFn: async (): Promise<CuratedModel[]> => (await fetchProviderModels(provider.id, { strict: true })).map((model) => ({ id: model.id, label: model.label ?? model.name ?? model.id })),+ queryFn: async (): Promise<CuratedModel[]> => (await fetchProviderModels(provider.id, { strict: true })).map((model) => ({ ...model, label: model.label ?? model.name ?? model.id })),initialData: saved?.live[provider.id], initialDataUpdatedAt: saved?.liveUpdatedAt?.[provider.id] ?? saved?.savedAt,enabled: Boolean(availableConnections), ...QUERY_POLICY, staleTime: 10 * 60_000, retry: false, refetchOnMount,})), combine });diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsxindex f5d2edbd62..93af80b720 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/AccessoryPicker.tsx@@ -75,7 +75,7 @@ export function AccessoryPicker({ value, onChange, agentId }: { value: Companiondata-locked={open ? undefined : "true"}className={`${tile} ${active ? "border-foreground bg-secondary" : open ? "border-border hover:bg-secondary" : "cursor-not-allowed border-dashed border-border"}`}><span className={open ? undefined : "opacity-35 grayscale"}>- <AgentSymbol shape={value.shape} color={value.color} eyes={value.eyes} accessories={{ ...worn, [slot]: id }} size={60} />+ <AgentSymbol shape={value.shape} color={value.color} eyes={value.eyes} skin={value.skin} accessories={{ ...worn, [slot]: id }} size={60} /></span>{!open && <span className="absolute bottom-1 left-1/2 inline-flex -translate-x-1/2 items-center gap-0.5 rounded-full bg-background/90 px-1.5 py-0.5 text-[10px] font-semibold text-foreground shadow-sm"><Lock size={9} aria-hidden />{t("society.level.lv").replace("{0}", String(at))}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsxindex 33c21caaa2..9159899a9c 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx@@ -12,6 +12,7 @@ import { advancePetTrail, createPetTrail, petDisplayPosition, recordOwner, typeimport { useWornPet } from "./companionPetStore";import { companionFlies, type CompanionPet } from "./petCompanions";import { PetModel, VoxelPet, type PetDrive } from "./PetModel";+import { advanceSkin, createSkinMaterial } from "./skinMaterial";class PetBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {state = { failed: false };@@ -59,6 +60,9 @@ const GIGI_LOOK: CompanionAppearance = {/** A cached authored mesh, with instance-owned materials and no extra canvas. */function ShapeModel({ appearance, lead = false }: { appearance: CompanionAppearance; lead?: boolean }) {const { scene } = useGLTF(lead ? gigiModel : companionModels);+ const reduced = useReducedMotion() ?? false;+ // The design by value: a freshly parsed but equal skin must not rebuild the material.+ const skinKey = appearance.skin ? JSON.stringify(appearance.skin) : "";const instance = useMemo(() => {const original = lead ? scene : scene.getObjectByName(appearance.shape);if (!original) throw new Error("Companion silhouette missing from asset");@@ -67,7 +71,10 @@ function ShapeModel({ appearance, lead = false }: { appearance: CompanionAppearaif (!lead) {const ink = companionEyeColors(appearance.color);// A soft vinyl sheen lets the light show the volume of each body.- const body = new MeshStandardMaterial({ color: appearance.color, roughness: 0.62 });+ let bodyMesh: Mesh | undefined;+ model.traverse(object => { if ((object as Mesh).isMesh && object.name.includes("Body")) bodyMesh ??= object as Mesh; });+ const body = appearance.skin ? createSkinMaterial(appearance.skin, bodyMesh?.geometry)+ : new MeshStandardMaterial({ color: appearance.color, roughness: 0.62 });const eyes = new MeshStandardMaterial({ color: ink.eye, roughness: 1 });const shine = new MeshStandardMaterial({ color: ink.highlight, roughness: 1 });materials.push(body, eyes, shine);@@ -81,8 +88,10 @@ function ShapeModel({ appearance, lead = false }: { appearance: CompanionAppeara});}return { model, materials };- }, [scene, lead, appearance.shape, appearance.color, appearance.eyes]);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- appearance.skin is read through skinKey+ }, [scene, lead, appearance.shape, appearance.color, appearance.eyes, skinKey]);useEffect(() => () => { instance.materials.forEach(material => material.dispose()); }, [instance]);+ useFrame((_, delta) => { if (!reduced && skinKey) advanceSkin(instance.materials[0]!, delta); });const wearing = !lead && wornAccessories(appearance.accessories).length > 0;// Gigi's authored body is 0.4 m; the symbol master is exactly 1 m.return <group scale={appearance.sizeM / (lead ? 0.4 : 1)}>diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsxindex f3ac534520..f0b1c03ed9 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx@@ -4,6 +4,7 @@ import { AgentSymbol } from "../AgentSymbol";import { AccessoryPicker } from "./AccessoryPicker";import { COMPANION_COLORS, COMPANION_SHAPES, type CompanionAppearance } from "./appearance";import { CompanionMark } from "./CompanionMark";+import { DesignPicker } from "./DesignPicker";import { PetSprite } from "@/components/pets/PetSprite";import { usePets } from "@/hooks/usePets";import gigiMark from "@/assets/gigi-companion-avatar.png";@@ -18,7 +19,8 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = falspreview3d?: boolean;}) {const t = useT();- const update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...patch });+ // Picking a plain colour takes the design off; the design picker sends both together.+ const update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...("color" in patch && !("skin" in patch) ? { skin: undefined } : {}), ...patch });const petsQuery = usePets();const pets = petsQuery.data?.pets ?? [];// The look is a shape or a pet; "Pet" stays chosen even before a pet exists to pick.@@ -59,7 +61,7 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = fals<div className="flex flex-wrap gap-2">{COMPANION_SHAPES.map(shape => <button key={shape} type="button"aria-label={t(`society.companion.shapes.${shape}`)} aria-pressed={value.shape === shape}onClick={() => update({ shape })} className={`grid h-12 w-12 place-items-center rounded-lg border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.shape === shape ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>- <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} accessories={value.accessories} size={36} />+ <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} accessories={value.accessories} skin={value.skin} size={36} /></button>)}</div></div><div className="flex items-center justify-between gap-3 text-sm"><span>{t("society.companion.eyes")}</span>@@ -81,6 +83,7 @@ export function CompanionEditor({ value, onChange, disabled = false, lead = fals<input type="color" aria-label={t("society.companion.custom_color")} value={value.color} onChange={e => update({ color: e.target.value })} className="aspect-square h-auto w-full rounded border border-border bg-background" /></div></div>}+ {!lead && kind === "shape" && <DesignPicker skin={value.skin} color={value.color} onChange={(skin, color) => update({ skin, color })} />}<label className="flex items-center justify-between gap-3 text-sm">{t("society.companion.visible")}<Switch checked={value.enabled} onCheckedChange={enabled => update({ enabled })} aria-label={t("society.companion.visible")} /></label>diff --git a/jarvis/ui/web/frontend/src/components/society/companion/DesignPicker.tsx b/jarvis/ui/web/frontend/src/components/society/companion/DesignPicker.tsxnew file mode 100644index 0000000000..bbdfdd29c7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/DesignPicker.tsx@@ -0,0 +1,170 @@+/**+ * Designs in the look dialog: ready-made gradients with effects (Galaxy,+ * Aurora, Holo …), the person's saved designs, and an editor for their own:+ * up to four colours, linear or radial, a direction and an effect. Designs+ * come in from a design code, a CSS gradient, hex colours or a picture, and go+ * out as a design code or into "My designs" for any agent to wear.+ */+import { useRef, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Check, Copy, ImageUp, Import, Minus, Plus, Save, X } from "lucide-react";+import { useT } from "@/i18n";+import {+ encodeDesignCode, parseDesignImport, sameSkin, skinBlend, skinCss, skinFromImage,+ SKIN_EFFECTS, SKIN_PATTERNS, SKIN_PRESETS, type CompanionSkin,+} from "./skins";++export interface SavedDesign { id: string; skin: CompanionSkin; created: number }++const DESIGNS_KEY = ["society", "designs"] as const;++async function fetchDesigns(): Promise<SavedDesign[]> {+ const res = await fetch("/api/society/designs", { cache: "no-store" });+ // A backend from before saved designs: nothing saved yet.+ if (res.status === 404) return [];+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return ((await res.json()) as { designs: SavedDesign[] }).designs;+}++const chip = (on: boolean) => `rounded-full border px-2.5 py-1 text-xs ${on ? "border-transparent bg-primary text-primary-foreground" : "border-border bg-background text-foreground hover:bg-secondary"}`;+const tile = (on: boolean) => `relative aspect-square w-full rounded-full border border-border ring-offset-2 ring-offset-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${on ? "ring-2 ring-foreground" : ""}`;++/** A lighter or darker twin of a colour, to start a design from the plain one. */+function shade(color: string, amount: number): string {+ const n = parseInt(color.slice(1), 16);+ const mix = (v: number) => Math.round(amount > 0 ? v + (255 - v) * amount : v * (1 + amount));+ return `#${[(n >> 16) & 255, (n >> 8) & 255, n & 255].map(v => mix(v).toString(16).padStart(2, "0")).join("")}`;+}++export function DesignPicker({ skin, color, onChange }: {+ skin: CompanionSkin | undefined; color: string;+ /** A design to wear (its blended colour comes along), or undefined for the plain colour. */+ onChange: (skin: CompanionSkin | undefined, color: string) => void;+}) {+ const t = useT();+ const client = useQueryClient();+ const designs = useQuery({ queryKey: DESIGNS_KEY, queryFn: fetchDesigns, staleTime: 60_000, retry: false });+ const [importing, setImporting] = useState(false);+ const [pasted, setPasted] = useState("");+ const [notice, setNotice] = useState<"" | "import_error" | "image_error" | "save_error" | "copied" | "saved">("");+ const file = useRef<HTMLInputElement>(null);+ const wear = (next: CompanionSkin | undefined) => { setNotice(""); onChange(next, next ? skinBlend(next.colors) : color); };+ const edit = (patch: Partial<CompanionSkin>) => skin && wear({ ...skin, ...patch });++ const save = useMutation({+ mutationFn: async (design: CompanionSkin) => {+ const res = await fetch("/api/society/designs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(design) });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return (await res.json()) as SavedDesign;+ },+ onSuccess: () => { setNotice("saved"); void client.invalidateQueries({ queryKey: DESIGNS_KEY }); },+ onError: () => setNotice("save_error"),+ });+ const remove = useMutation({+ mutationFn: async (id: string) => {+ const res = await fetch(`/api/society/designs/${encodeURIComponent(id)}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) throw new Error(`HTTP ${res.status}`);+ },+ onSettled: () => void client.invalidateQueries({ queryKey: DESIGNS_KEY }),+ });++ const applyImport = () => {+ const found = parseDesignImport(pasted);+ if (!found) { setNotice("import_error"); return; }+ wear(found); setImporting(false); setPasted("");+ };+ const fromPicture = async (picked: File | undefined) => {+ if (!picked) return;+ try {+ const found = await skinFromImage(picked);+ if (found) wear({ ...found, name: picked.name.replace(/\.[^.]+$/, "").slice(0, 40) }); else setNotice("image_error");+ } catch { setNotice("image_error"); } // An unreadable or unsupported file: say so, keep the look.+ finally { if (file.current) file.current.value = ""; }+ };+ const copyCode = async () => {+ if (!skin) return;+ try { await navigator.clipboard.writeText(encodeDesignCode(skin)); setNotice("copied"); }+ catch { setImporting(true); setPasted(encodeDesignCode(skin)); } // No clipboard: show the code to copy by hand.+ };++ const saved = designs.data ?? [];+ return <div className="grid gap-3" data-testid="design-picker">+ <div>+ <span className="block text-sm font-medium">{t("society.companion.design.title")}</span>+ <p className="mt-0.5 text-xs text-muted-foreground">{t("society.companion.design.hint")}</p>+ </div>+ <div className="grid w-full grid-cols-10 items-center gap-2" role="group" aria-label={t("society.companion.design.title")}>+ {SKIN_PRESETS.map(preset => {+ const label = t(`society.companion.design.presets.${preset.id}`);+ const look = { ...preset.skin, name: label };+ return <button key={preset.id} type="button" title={label} aria-label={label} aria-pressed={sameSkin(skin, look)}+ onClick={() => wear(look)} className={tile(sameSkin(skin, look))} style={{ background: skinCss(look) }} />;+ })}+ <button type="button" title={t("society.companion.design.create")} aria-label={t("society.companion.design.create")}+ onClick={() => wear({ colors: [shade(color, 0.45), color, shade(color, -0.45)], pattern: "linear", angle: 160, effect: "none", name: "" })}+ className={`${tile(false)} grid place-items-center bg-background text-muted-foreground hover:bg-secondary`}><Plus size={16} /></button>+ </div>+ {saved.length > 0 && <div>+ <span className="mb-1.5 block text-xs text-muted-foreground">{t("society.companion.design.mine")}</span>+ <div className="grid w-full grid-cols-10 items-center gap-2">{saved.map(design => {+ const label = design.skin.name || t("society.companion.design.custom");+ return <div key={design.id} className="group relative">+ <button type="button" title={label} aria-label={label} aria-pressed={sameSkin(skin, design.skin)}+ onClick={() => wear(design.skin)} className={tile(sameSkin(skin, design.skin))} style={{ background: skinCss(design.skin) }} />+ <button type="button" aria-label={t("society.companion.design.delete").replace("{0}", label)} onClick={() => remove.mutate(design.id)}+ className="absolute -right-1 -top-1 grid h-4 w-4 place-items-center rounded-full border border-border bg-popover text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100"><X size={10} /></button>+ </div>;+ })}</div>+ </div>}+ <div className="flex flex-wrap gap-1.5">+ <button type="button" className={chip(importing)} aria-pressed={importing} onClick={() => { setImporting(v => !v); setNotice(""); }}>+ <Import size={12} className="mr-1 inline" />{t("society.companion.design.import")}</button>+ <button type="button" className={chip(false)} onClick={() => file.current?.click()}>+ <ImageUp size={12} className="mr-1 inline" />{t("society.companion.design.from_image")}</button>+ <input ref={file} type="file" accept="image/*" className="hidden" aria-hidden tabIndex={-1} onChange={e => void fromPicture(e.target.files?.[0])} />+ {skin && <button type="button" className={chip(false)} onClick={() => wear(undefined)}>{t("society.companion.design.plain")}</button>}+ </div>+ {importing && <div className="grid gap-2">+ <textarea value={pasted} onChange={e => setPasted(e.target.value)} rows={2} spellCheck={false} placeholder={t("society.companion.design.import_hint")}+ aria-label={t("society.companion.design.import")} className="w-full resize-none rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-xs" />+ <div className="flex justify-end"><button type="button" className={chip(true)} disabled={!pasted.trim()} onClick={applyImport}>{t("society.companion.design.import_apply")}</button></div>+ </div>}+ {skin && <div className="grid gap-3 rounded-lg border border-border p-3" data-testid="design-editor">+ <div className="flex flex-wrap items-center justify-between gap-2 text-sm"><span>{t("society.companion.design.colors")}</span>+ <div className="flex items-center gap-1.5">+ {skin.colors.map((stop, index) => <input key={index} type="color" value={stop} aria-label={`${t("society.companion.design.colors")} ${index + 1}`}+ onChange={e => edit({ colors: skin.colors.map((c, i) => i === index ? e.target.value : c) })} className="h-8 w-9 rounded border border-border bg-background" />)}+ {skin.colors.length > 2 && <button type="button" aria-label={t("society.companion.design.remove_color")} onClick={() => edit({ colors: skin.colors.slice(0, -1) })}+ className="grid h-8 w-8 place-items-center rounded border border-border hover:bg-secondary"><Minus size={14} /></button>}+ {skin.colors.length < 4 && <button type="button" aria-label={t("society.companion.design.add_color")} onClick={() => edit({ colors: [...skin.colors, skin.colors[skin.colors.length - 1]!] })}+ className="grid h-8 w-8 place-items-center rounded border border-border hover:bg-secondary"><Plus size={14} /></button>}+ </div>+ </div>+ <div className="flex flex-wrap items-center justify-between gap-2 text-sm"><span>{t("society.companion.design.pattern")}</span>+ <div className="flex gap-1.5" role="group" aria-label={t("society.companion.design.pattern")}>+ {SKIN_PATTERNS.map(pattern => <button key={pattern} type="button" aria-pressed={skin.pattern === pattern} onClick={() => edit({ pattern })} className={chip(skin.pattern === pattern)}>+ {t(`society.companion.design.pattern_${pattern}`)}</button>)}+ </div>+ </div>+ {skin.pattern === "linear" && <label className="flex items-center justify-between gap-3 text-sm">{t("society.companion.design.angle")}+ <input type="range" min={0} max={359} step={1} value={skin.angle} onChange={e => edit({ angle: Number(e.target.value) })} className="w-40 accent-primary" />+ </label>}+ <div className="grid gap-1.5 text-sm"><span>{t("society.companion.design.effect")}</span>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label={t("society.companion.design.effect")}>+ {SKIN_EFFECTS.map(effect => <button key={effect} type="button" aria-pressed={skin.effect === effect} onClick={() => edit({ effect })} className={chip(skin.effect === effect)}>+ {t(`society.companion.design.effects.${effect}`)}</button>)}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <input value={skin.name} maxLength={40} onChange={e => edit({ name: e.target.value.replace(/[\p{Cc}]/gu, "") })} placeholder={t("society.companion.design.name_placeholder")}+ aria-label={t("society.companion.design.name")} className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2.5 text-sm" />+ <button type="button" className={chip(false)} disabled={save.isPending} onClick={() => save.mutate(skin)}>+ <Save size={12} className="mr-1 inline" />{t("society.companion.design.save")}</button>+ <button type="button" className={chip(false)} onClick={() => void copyCode()}>+ {notice === "copied" ? <Check size={12} className="mr-1 inline" /> : <Copy size={12} className="mr-1 inline" />}{t(notice === "copied" ? "society.companion.design.copied" : "society.companion.design.copy_code")}</button>+ </div>+ </div>}+ {notice && notice !== "copied" && <p role={notice.endsWith("error") ? "alert" : "status"} className={`text-xs ${notice.endsWith("error") ? "text-destructive" : "text-muted-foreground"}`}>+ {t(`society.companion.design.${notice}`)}</p>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/SkinLayers.tsx b/jarvis/ui/web/frontend/src/components/society/companion/SkinLayers.tsxnew file mode 100644index 0000000000..da8654bb78--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/SkinLayers.tsx@@ -0,0 +1,85 @@+/**+ * The 2D drawing of a companion design (skins.ts) on an AgentSymbol: the+ * gradient the body is filled with, plus its effect. Every effect is a few+ * small SVG shapes moved by compositor-only CSS (skinLayers.css); reduced+ * motion leaves a still frame of each.+ */+import type { ReactNode } from "react";+import { angleVector, skinEffect, skinHighlight, type CompanionSkin } from "./skins";+import "./skinLayers.css";++/** Star specks inside the body, in symbol units (40 × 40): x, y, radius. */+const STARS: readonly (readonly [number, number, number])[] = [+ [12, 10, 0.7], [27, 8.5, 0.5], [31, 17, 0.8], [9, 21, 0.55], [17, 27, 0.75],+ [25, 25, 0.45], [33, 27, 0.55], [14, 33, 0.5], [22, 33.5, 0.65], [20, 13.5, 0.4], [7, 15, 0.4],+];+/** Four-point glints around the silhouette. */+const SPARKLES: readonly (readonly [number, number, number])[] = [[6.5, 7, 1], [34.5, 11, 0.8], [33, 34, 0.9]];+const GLINT = "M0 -3.2 L0.75 -0.75 L3.2 0 L0.75 0.75 L0 3.2 L-0.75 0.75 L-3.2 0 L-0.75 -0.75Z";+/** One loop of the flowing gradient, in symbol units. */+const FLOW_PERIOD = 40;++function Stops({ colors, cyclic = false }: { colors: readonly string[]; cyclic?: boolean }) {+ const ring = cyclic ? [...colors, colors[0]!] : colors;+ return <>{ring.map((color, index) => <stop key={index} offset={index / (ring.length - 1)} stopColor={color} />)}</>;+}++/** The body's gradient, referenced as `url(#id)`. */+export function SkinDefs({ id, skin }: { id: string; skin: CompanionSkin }) {+ const [x1, y1, x2, y2] = angleVector(skin.angle);+ return <defs>+ {skin.pattern === "radial"+ ? <radialGradient id={id} cx="0.38" cy="0.34" r="0.78"><Stops colors={skin.colors} /></radialGradient>+ : <linearGradient id={id} x1={x1} y1={y1} x2={x2} y2={y2}><Stops colors={skin.colors} /></linearGradient>}+ </defs>;+}++/** A soft pulsing halo of the design's brightest colour, drawn behind the body. */+export function SkinGlow({ id, skin, body }: { id: string; skin: CompanionSkin; body: (fill: string) => ReactNode }) {+ if (skinEffect(skin) !== "glow") return null;+ return <g data-skin-glow>+ <defs><filter id={`${id}-glow`} x="-60%" y="-60%" width="220%" height="220%"><feGaussianBlur stdDeviation={2.4} /></filter></defs>+ <g className="agent-skin-glow" filter={`url(#${id}-glow)`}>{body(skinHighlight(skin.colors))}</g>+ </g>;+}++/**+ * The effect on top of the filled body: clipped to the silhouette through a+ * mask of the same body, so stars, the shine and the flowing colours never+ * spill past the edge. Sparkles sit outside on purpose.+ */+export function SkinOverlay({ id, skin, body }: { id: string; skin: CompanionSkin; body: (fill: string) => ReactNode }) {+ const effect = skinEffect(skin);+ if (effect === "none" || effect === "glow") return null;+ if (effect === "sparkle") {+ return <g data-skin-effect="sparkle" fill={skinHighlight(skin.colors)} stroke={skin.colors[skin.colors.length - 1]} strokeWidth={0.35} strokeLinejoin="round">+ {SPARKLES.map(([x, y, k], index) => <g key={index} transform={`translate(${x} ${y}) scale(${k})`}>+ <path className="agent-skin-glint" d={GLINT} style={{ animationDelay: `${-index * 1.1}s` }} />+ </g>)}+ </g>;+ }+ const maskId = `${id}-mask`;+ return <g data-skin-effect={effect}>+ <mask id={maskId} maskUnits="userSpaceOnUse" x={-20} y={-20} width={80} height={84}>{body("#ffffff")}</mask>+ <g mask={`url(#${maskId})`}>+ {effect === "stars" && <g className="agent-skin-stars" fill="#ffffff">+ {STARS.map(([x, y, r], index) => <circle key={index} cx={x} cy={y} r={r} style={{ animationDelay: `${-index * 0.43}s` }} />)}+ </g>}+ {effect === "shimmer" && <>+ <defs><linearGradient id={`${id}-shine`} x1="0" y1="0" x2="1" y2="0">+ <stop offset="0" stopColor="#ffffff" stopOpacity="0" /><stop offset="0.5" stopColor="#ffffff" stopOpacity="0.75" /><stop offset="1" stopColor="#ffffff" stopOpacity="0" />+ </linearGradient></defs>+ <g transform="skewX(-22)"><rect className="agent-skin-shine" x={-14} y={-10} width={13} height={64} fill={`url(#${id}-shine)`} /></g>+ </>}+ {effect === "flow" && <>+ <defs><linearGradient id={`${id}-flow`} gradientUnits="userSpaceOnUse" x1={0} y1={0} x2={FLOW_PERIOD} y2={0} spreadMethod="repeat">+ <Stops colors={skin.colors} cyclic />+ </linearGradient></defs>+ {/* Along the design's own direction: CSS 90° (to the right) is the x axis. */}+ <g transform={`rotate(${skin.angle - 90} 20 20)`}>+ <rect className="agent-skin-flow" x={-60} y={-60} width={160} height={160} fill={`url(#${id}-flow)`} />+ </g>+ </>}+ </g>+ </g>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts b/jarvis/ui/web/frontend/src/components/society/companion/appearance.tsindex 465cf17dfb..73e395e799 100644--- a/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts+++ b/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts@@ -1,5 +1,6 @@import { z } from "zod";import { ACCESSORY_SLOTS, type AccessoryChoice } from "./accessories";+import { skinSchema } from "./skins";export const COMPANION_SHAPES = ["circle", "squircle", "pill", "triangle", "hexagon", "cloud", "drop"] as const;export type SymbolShape = typeof COMPANION_SHAPES[number];@@ -23,6 +24,8 @@ export const companionSchema = z.object({// A pet from My Pets worn instead of the shape. Open like accessory ids: a pet// missing on this machine shows the shape, it never invalidates the look.pet: z.string().regex(PET_ID).optional(),+ // A colour design (gradient + effect) worn instead of the flat colour; see skins.ts.+ skin: skinSchema.optional(),// Accept earlier saved slider values, but every presentation uses one scale.sizeM: z.number().finite().min(0.25).max(0.8).default(COMPANION_SIZE_M).transform(() => COMPANION_SIZE_M),followDistanceM: z.number().finite().min(0.5).max(2).default(COMPANION_FOLLOW_DISTANCE_M).transform(() => COMPANION_FOLLOW_DISTANCE_M),diff --git a/jarvis/ui/web/frontend/src/components/society/companion/skinLayers.css b/jarvis/ui/web/frontend/src/components/society/companion/skinLayers.cssnew file mode 100644index 0000000000..8d868d85d3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/skinLayers.css@@ -0,0 +1,55 @@+/* Companion design effects (SkinLayers.tsx): transforms and opacity only. */+.society-agent-symbol .agent-skin-stars circle {+ transform-box: fill-box;+ transform-origin: center;+ animation: agent-skin-twinkle 2.6s ease-in-out infinite;+}+@keyframes agent-skin-twinkle {+ 0%, 100% { opacity: 0.25; transform: scale(0.6); }+ 50% { opacity: 1; transform: scale(1.25); }+}++.society-agent-symbol .agent-skin-shine {+ animation: agent-skin-shine 3.4s ease-in-out infinite;+}+@keyframes agent-skin-shine {+ 0% { transform: translateX(0); }+ 55%, 100% { transform: translateX(78px); }+}++.society-agent-symbol .agent-skin-flow {+ animation: agent-skin-flow 7s linear infinite;+}+/* One gradient period (FLOW_PERIOD), so the loop has no seam. */+@keyframes agent-skin-flow {+ from { transform: translateX(0); }+ to { transform: translateX(-40px); }+}++.society-agent-symbol .agent-skin-glow {+ animation: agent-skin-glow 2.8s ease-in-out infinite alternate;+}+@keyframes agent-skin-glow {+ from { opacity: 0.45; }+ to { opacity: 0.95; }+}++.society-agent-symbol .agent-skin-glint {+ transform-box: fill-box;+ transform-origin: center;+ animation: agent-skin-glint 3.3s ease-in-out infinite;+}+@keyframes agent-skin-glint {+ 0%, 60%, 100% { transform: scale(0) rotate(0deg); opacity: 0; }+ 72% { transform: scale(1) rotate(45deg); opacity: 1; }+ 86% { transform: scale(0.5) rotate(80deg); opacity: 0.6; }+}++@media (prefers-reduced-motion: reduce) {+ .society-agent-symbol .agent-skin-stars circle,+ .society-agent-symbol .agent-skin-flow,+ .society-agent-symbol .agent-skin-glow { animation: none; }+ .society-agent-symbol .agent-skin-stars circle { opacity: 0.85; }+ .society-agent-symbol .agent-skin-shine { animation: none; transform: translateX(32px); opacity: 0.5; }+ .society-agent-symbol .agent-skin-glint { animation: none; transform: scale(0.85) rotate(45deg); opacity: 0.9; }+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/skinMaterial.ts b/jarvis/ui/web/frontend/src/components/society/companion/skinMaterial.tsnew file mode 100644index 0000000000..b280eaa67a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/skinMaterial.ts@@ -0,0 +1,130 @@+/**+ * A companion design (skins.ts) on the 3D body: the standard vinyl material+ * with its diffuse colour replaced by the design's gradient over the body's+ * own bounding box, and the effect added as emissive light (stars, a moving+ * shine, flowing colours, a pulsing glow, glints). One shader for every+ * design; the colours, layout and clock are per-material uniforms.+ */+import { Box3, Color, MeshStandardMaterial, Vector2, Vector3, type BufferGeometry } from "three";+import { skinEffect, skinHighlight, SKIN_EFFECTS, type CompanionSkin } from "./skins";++interface SkinUniforms {+ [name: string]: { value: unknown };+ uSkinColors: { value: Color[] };+ uSkinCount: { value: number };+ uSkinRadial: { value: number };+ uSkinDir: { value: Vector2 };+ uSkinMin: { value: Vector3 };+ uSkinMax: { value: Vector3 };+ uSkinEffect: { value: number };+ uSkinTime: { value: number };+ uSkinHighlight: { value: Color };+}++const VERTEX_HEAD = "#include <common>\nvarying vec3 vSkinPos;";+const VERTEX_BODY = "#include <begin_vertex>\nvSkinPos = position;";++const FRAGMENT_HEAD = /* glsl */ `#include <common>+varying vec3 vSkinPos;+uniform vec3 uSkinColors[4];+uniform int uSkinCount;+uniform int uSkinRadial;+uniform vec2 uSkinDir;+uniform vec3 uSkinMin;+uniform vec3 uSkinMax;+uniform int uSkinEffect;+uniform float uSkinTime;+uniform vec3 uSkinHighlight;+vec3 skinSample(float t) {+ t = clamp(t, 0.0, 1.0) * float(uSkinCount - 1);+ vec3 c = uSkinColors[0];+ for (int i = 1; i < 4; i++) {+ if (i >= uSkinCount) break;+ c = mix(c, uSkinColors[i], clamp(t - float(i - 1), 0.0, 1.0));+ }+ return c;+}+vec3 skinRing(float u) {+ float t = fract(u) * float(uSkinCount);+ vec3 c = uSkinColors[0];+ for (int i = 1; i <= 4; i++) {+ if (i > uSkinCount) break;+ c = mix(c, uSkinColors[i % uSkinCount], clamp(t - float(i - 1), 0.0, 1.0));+ }+ return c;+}+float skinHash(vec3 p) { return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); }+float skinSpecks(vec3 p, float cells, float density, float speed) {+ vec3 q = p * cells;+ vec3 cell = floor(q);+ float h = skinHash(cell);+ vec3 offset = vec3(skinHash(cell + 1.7), skinHash(cell + 4.3), skinHash(cell + 8.9)) - 0.5;+ float d = length(fract(q) - 0.5 - offset * 0.5);+ float twinkle = 0.55 + 0.45 * sin(uSkinTime * speed + h * 40.0);+ return step(1.0 - density, h) * smoothstep(0.24, 0.02, d) * twinkle;+}`;++const FRAGMENT_DIFFUSE = /* glsl */ `vec3 skinP = (vSkinPos - uSkinMin) / max(uSkinMax - uSkinMin, vec3(1e-4)) - 0.5;+float skinT = uSkinRadial == 1 ? length(skinP - vec3(-0.12, 0.16, 0.3)) * 1.25 : dot(skinP.xy, uSkinDir) + 0.5;+vec3 skinColor = uSkinEffect == 3 ? skinRing(skinT * 0.9 - uSkinTime * 0.14) : skinSample(skinT);+vec4 diffuseColor = vec4( skinColor, opacity );`;++const FRAGMENT_EMISSIVE = /* glsl */ `#include <emissivemap_fragment>+if (uSkinEffect == 1) totalEmissiveRadiance += vec3(1.0) * skinSpecks(skinP, 7.0, 0.3, 2.4) * 2.6;+if (uSkinEffect == 2) {+ float sweep = fract(uSkinTime * 0.26) * 2.6 - 1.3;+ float band = exp(-pow((skinP.x + skinP.y * 0.6 - sweep) * 8.0, 2.0));+ totalEmissiveRadiance += vec3(band * 0.55);+}+if (uSkinEffect == 4) totalEmissiveRadiance += uSkinHighlight * (0.32 + 0.18 * sin(uSkinTime * 2.2));+if (uSkinEffect == 5) totalEmissiveRadiance += uSkinHighlight * skinSpecks(skinP, 5.0, 0.18, 1.6) * 2.4;`;++/** Effect ids as the shader numbers them (index in SKIN_EFFECTS). */+function effectCode(skin: CompanionSkin): number {+ return SKIN_EFFECTS.indexOf(skinEffect(skin));+}++/**+ * The body material for a design. `geometry` gives the box the gradient spans;+ * call `advanceSkin` every frame to move its effect.+ */+export function createSkinMaterial(skin: CompanionSkin, geometry: BufferGeometry | undefined): MeshStandardMaterial {+ const box = new Box3(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5));+ if (geometry) {+ if (!geometry.boundingBox) geometry.computeBoundingBox();+ if (geometry.boundingBox) box.copy(geometry.boundingBox);+ }+ const colors = [0, 1, 2, 3].map(i => new Color(skin.colors[Math.min(i, skin.colors.length - 1)]!));+ const rad = skin.angle * Math.PI / 180;+ const uniforms: SkinUniforms = {+ uSkinColors: { value: colors },+ uSkinCount: { value: skin.colors.length },+ uSkinRadial: { value: skin.pattern === "radial" ? 1 : 0 },+ uSkinDir: { value: new Vector2(Math.sin(rad), Math.cos(rad)) },+ uSkinMin: { value: box.min.clone() },+ uSkinMax: { value: box.max.clone() },+ uSkinEffect: { value: effectCode(skin) },+ uSkinTime: { value: 0 },+ uSkinHighlight: { value: new Color(skinHighlight(skin.colors)) },+ };+ const material = new MeshStandardMaterial({ color: "#ffffff", roughness: skinEffect(skin) === "shimmer" ? 0.38 : 0.62 });+ material.userData.skinUniforms = uniforms;+ material.onBeforeCompile = shader => {+ Object.assign(shader.uniforms, uniforms);+ shader.vertexShader = shader.vertexShader+ .replace("#include <common>", VERTEX_HEAD)+ .replace("#include <begin_vertex>", VERTEX_BODY);+ shader.fragmentShader = shader.fragmentShader+ .replace("#include <common>", FRAGMENT_HEAD)+ .replace("vec4 diffuseColor = vec4( diffuse, opacity );", FRAGMENT_DIFFUSE)+ .replace("#include <emissivemap_fragment>", FRAGMENT_EMISSIVE);+ };+ material.customProgramCacheKey = () => "jarvis-companion-skin";+ return material;+}++/** Moves a design's effect on; a material without a design is left alone. */+export function advanceSkin(material: MeshStandardMaterial, seconds: number): void {+ const uniforms = material.userData.skinUniforms as SkinUniforms | undefined;+ if (uniforms) uniforms.uSkinTime.value = (uniforms.uSkinTime.value + seconds) % 3600;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/skins.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/skins.test.tsnew file mode 100644index 0000000000..a6d0d75d52--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/skins.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import { render } from "@testing-library/react";+import { createElement } from "react";+import { AgentSymbol } from "../AgentSymbol";+import {+ angleVector, encodeDesignCode, paletteFromPixels, parseDesignImport, sameSkin, skinBlend, skinEffect,+ skinSchema, SKIN_PRESETS, type CompanionSkin,+} from "./skins";++const GALAXY: CompanionSkin = { colors: ["#e05cc5", "#6a2fc2", "#160f3d"], pattern: "radial", angle: 135, effect: "stars", name: "Galaxy" };++describe("companion designs", () => {+ it("ships only valid presets", () => {+ for (const preset of SKIN_PRESETS) expect(skinSchema.safeParse({ ...preset.skin, name: preset.id }).success).toBe(true);+ });++ it("round-trips a design code, non-ASCII names included", () => {+ const skin = { ...GALAXY, name: "Nébula ✦ 星系" };+ const code = encodeDesignCode(skin);+ expect(code.startsWith("jarvis-design:")).toBe(true);+ expect(parseDesignImport(code)).toEqual(skin);+ });++ it("imports JSON of a design, a companion or a template avatar", () => {+ expect(parseDesignImport(JSON.stringify(GALAXY))).toEqual(GALAXY);+ expect(parseDesignImport(JSON.stringify({ companion: { shape: "circle", skin: GALAXY } }))).toEqual(GALAXY);+ });++ it("imports CSS gradients from gradient sites", () => {+ expect(parseDesignImport("background: linear-gradient(90deg, #FF2FD6 0%, rgba(47, 243, 255, 1) 100%);"))+ .toEqual({ colors: ["#ff2fd6", "#2ff3ff"], pattern: "linear", angle: 90, effect: "none", name: "" });+ expect(parseDesignImport("linear-gradient(to bottom right, #fc0, #f06, #60f)")?.angle).toBe(135);+ expect(parseDesignImport("radial-gradient(circle, #111111, #222222, #333333, #444444, #555555, #666666)"))+ .toMatchObject({ pattern: "radial", colors: ["#111111", "#333333", "#444444", "#666666"] });+ });++ it("takes a plain list of hex colours and refuses junk", () => {+ expect(parseDesignImport("#123456 #abcdef")?.colors).toEqual(["#123456", "#abcdef"]);+ expect(parseDesignImport("hello")).toBeNull();+ expect(parseDesignImport("jarvis-design:%%%")).toBeNull();+ expect(parseDesignImport("{ broken")).toBeNull();+ expect(parseDesignImport(JSON.stringify({ colors: ["#123456"] }))).toBeNull();+ });++ it("blends a design into the one colour other surfaces use", () => {+ expect(skinBlend(["#000000", "#000000"])).toBe("#000000");+ expect(skinBlend(["#ff0000", "#ff0000", "#ff0000"])).toBe("#ff0000");+ expect(skinBlend(["#000000", "#ffffff"])).toMatch(/^#[0-9a-f]{6}$/);+ });++ it("points the gradient the CSS way and compares looks by value", () => {+ expect(angleVector(90)).toEqual([0, 0.5, 1, 0.5]);+ expect(angleVector(180)).toEqual([0.5, 0, 0.5, 1]);+ expect(sameSkin(GALAXY, { ...GALAXY, name: "Other", colors: ["#E05CC5", "#6a2fc2", "#160f3d"] })).toBe(true);+ expect(sameSkin(GALAXY, { ...GALAXY, effect: "glow" })).toBe(false);+ expect(skinEffect({ ...GALAXY, effect: "futureeffect" })).toBe("none");+ });++ it("finds distinct dominant colours in a picture", () => {+ const pixels = new Uint8ClampedArray(4 * 100);+ for (let i = 0; i < 100; i++) {+ const [r, g, b] = i < 50 ? [20, 10, 60] : i < 80 ? [200, 60, 180] : [21, 11, 61];+ pixels.set([r, g, b, 255], i * 4);+ }+ const palette = paletteFromPixels(pixels, 3);+ expect(palette[0]).toBe("#c83cb4");+ expect(palette).toContain("#140a3c");+ });++ it("paints the symbol with the design and its effect", () => {+ const { container } = render(createElement(AgentSymbol, { shape: "circle", color: "#7a3fb8", size: 40, skin: GALAXY }));+ expect(container.querySelector("radialGradient stop")?.getAttribute("stop-color")).toBe("#e05cc5");+ expect(container.querySelector("[data-agent-body]")?.getAttribute("data-skin")).toBe("stars");+ expect(container.querySelectorAll("[data-skin-effect='stars'] circle").length).toBeGreaterThan(5);+ const plain = render(createElement(AgentSymbol, { shape: "circle", color: "#7a3fb8", size: 40 }));+ expect(plain.container.querySelector("[data-skin-effect]")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/skins.ts b/jarvis/ui/web/frontend/src/components/society/companion/skins.tsnew file mode 100644index 0000000000..66de8d3a36--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/skins.ts@@ -0,0 +1,232 @@+/**+ * Companion designs ("skins"): a colour gradient with an optional looping+ * effect, worn instead of the flat companion colour. `companion.skin` in the+ * avatar JSON; `CompanionSkin` in `jarvis/society/companion.py` validates the+ * same shape (the shared fixture `tests/contract/fixtures/agent-companion.json`+ * pins both).+ *+ * The appearance keeps a plain `color` beside the skin, set to the design's+ * blended colour, so surfaces that know one colour (chat bubble tint, thinking+ * dots, accessory tints) still match the design.+ */+import { z } from "zod";++export const SKIN_PATTERNS = ["linear", "radial"] as const;+/** Effects drawn here. Saved ids stay open: an unknown one draws no effect. */+export const SKIN_EFFECTS = ["none", "stars", "shimmer", "flow", "glow", "sparkle"] as const;+export type SkinEffect = typeof SKIN_EFFECTS[number];++const HEX = /^#[0-9a-fA-F]{6}$/;+// eslint-disable-next-line no-control-regex+const PLAIN_TEXT = /^[^\x00-\x1f\x7f]*$/;++export const skinSchema = z.object({+ colors: z.array(z.string().regex(HEX)).min(2).max(4),+ pattern: z.enum(SKIN_PATTERNS).default("linear"),+ angle: z.number().int().min(0).max(359).default(135),+ effect: z.string().regex(/^[a-z]{1,20}$/).default("none"),+ name: z.string().max(40).regex(PLAIN_TEXT).default(""),+}).strict();+export type CompanionSkin = z.infer<typeof skinSchema>;++/** The effect to draw; an id from a newer build draws nothing. */+export function skinEffect(skin: CompanionSkin): SkinEffect {+ return (SKIN_EFFECTS as readonly string[]).includes(skin.effect) ? skin.effect as SkinEffect : "none";+}++export interface SkinPreset { id: string; skin: Omit<CompanionSkin, "name"> }++/** Ready-made designs; the dialog names them through `society.companion.design.presets.<id>`. */+export const SKIN_PRESETS: readonly SkinPreset[] = [+ { id: "galaxy", skin: { colors: ["#e05cc5", "#6a2fc2", "#160f3d"], pattern: "radial", angle: 135, effect: "stars" } },+ { id: "aurora", skin: { colors: ["#22e3a5", "#2bb3e0", "#8a5cf0"], pattern: "linear", angle: 160, effect: "flow" } },+ { id: "holo", skin: { colors: ["#ffc6ec", "#bdf3ff", "#d6c4ff", "#fff1b8"], pattern: "linear", angle: 120, effect: "shimmer" } },+ { id: "lava", skin: { colors: ["#ffd23f", "#ff5a1f", "#8c1010"], pattern: "radial", angle: 135, effect: "glow" } },+ { id: "neon", skin: { colors: ["#ff2fd6", "#2ff3ff"], pattern: "linear", angle: 90, effect: "glow" } },+ { id: "ocean", skin: { colors: ["#64e1ff", "#1f7ae0", "#0b2a6b"], pattern: "linear", angle: 180, effect: "flow" } },+ { id: "sunset", skin: { colors: ["#ffb347", "#ff5f6d", "#7b3fa0"], pattern: "linear", angle: 180, effect: "none" } },+ { id: "gold", skin: { colors: ["#fff1a8", "#e3a92b", "#8a5a12"], pattern: "linear", angle: 145, effect: "sparkle" } },+ { id: "frost", skin: { colors: ["#ffffff", "#bfe6ff", "#7aa8e8"], pattern: "linear", angle: 200, effect: "sparkle" } },+];++function rgb(hex: string): [number, number, number] {+ const n = parseInt(hex.slice(1), 16);+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];+}++function hex([r, g, b]: readonly number[]): string {+ return `#${[r, g, b].map(v => Math.round(Math.max(0, Math.min(255, v!))).toString(16).padStart(2, "0")).join("")}`;+}++/** Relative luminance, 0 (black) to 1 (white). */+export function luminance(color: string): number {+ const [r, g, b] = rgb(color).map(v => { const c = v / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; });+ return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;+}++/** The one colour a design reads as: its stops averaged in linear light. */+export function skinBlend(colors: readonly string[]): string {+ const lin = colors.map(c => rgb(c).map(v => (v / 255) ** 2.2));+ const mean = [0, 1, 2].map(i => lin.reduce((sum, c) => sum + c[i]!, 0) / lin.length);+ return hex(mean.map(v => 255 * v ** (1 / 2.2)));+}++/** The brightest stop: what a glow or a sparkle shines in. */+export function skinHighlight(colors: readonly string[]): string {+ return [...colors].sort((a, b) => luminance(b) - luminance(a))[0]!;+}++/** A CSS background for a design's swatch. */+export function skinCss(skin: Pick<CompanionSkin, "colors" | "pattern" | "angle">): string {+ return skin.pattern === "radial"+ ? `radial-gradient(circle at 38% 34%, ${skin.colors.join(", ")})`+ : `linear-gradient(${skin.angle}deg, ${skin.colors.join(", ")})`;+}++/** Gradient end points in the unit box for a CSS angle (0 = up, 90 = right). */+export function angleVector(angle: number): [number, number, number, number] {+ const rad = angle * Math.PI / 180;+ const dx = Math.sin(rad) / 2;+ const dy = -Math.cos(rad) / 2;+ const r = (v: number) => Math.round(v * 1000) / 1000;+ return [r(0.5 - dx), r(0.5 - dy), r(0.5 + dx), r(0.5 + dy)];+}++/** Two designs look the same when colours, layout and effect match (names may differ). */+export function sameSkin(a: CompanionSkin | undefined, b: CompanionSkin | undefined): boolean {+ if (!a || !b) return a === b;+ return a.pattern === b.pattern && a.angle === b.angle && a.effect === b.effect+ && a.colors.length === b.colors.length && a.colors.every((c, i) => c.toLowerCase() === b.colors[i]!.toLowerCase());+}++// ---------------------------------------------------------------- import / export++const CODE_PREFIX = "jarvis-design:";++/** A short text anyone can paste into their own look dialog. */+export function encodeDesignCode(skin: CompanionSkin): string {+ const json = JSON.stringify({ v: 1, ...skin });+ const bytes = new TextEncoder().encode(json);+ let binary = "";+ bytes.forEach(b => { binary += String.fromCharCode(b); });+ return CODE_PREFIX + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++function decodeDesignCode(text: string): unknown {+ const body = text.slice(CODE_PREFIX.length).trim().replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(body + "=".repeat((4 - body.length % 4) % 4));+ return JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, c => c.charCodeAt(0))));+}++function fromObject(value: unknown): CompanionSkin | null {+ if (!value || typeof value !== "object") return null;+ const { v: _version, ...rest } = value as Record<string, unknown>;+ // A whole exported companion (or agent template) carries the skin inside.+ const inner = (rest.companion as Record<string, unknown> | undefined)?.skin ?? rest.skin ?? rest;+ const parsed = skinSchema.safeParse(inner);+ return parsed.success ? { ...parsed.data, colors: parsed.data.colors.map(c => c.toLowerCase()) } : null;+}++const CSS_COLOR = /#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}[^)]*\)/g;+const CSS_SIDES: Record<string, number> = {+ "to top": 0, "to top right": 45, "to right top": 45, "to right": 90, "to bottom right": 135, "to right bottom": 135,+ "to bottom": 180, "to bottom left": 225, "to left bottom": 225, "to left": 270, "to top left": 315, "to left top": 315,+};++function cssColorHex(token: string): string {+ if (token.startsWith("#")) {+ const h = token.slice(1);+ return `#${(h.length <= 4 ? h.slice(0, 3).split("").map(c => c + c).join("") : h.slice(0, 6))}`.toLowerCase();+ }+ return hex(token.match(/\d{1,3}/g)!.slice(0, 3).map(Number));+}++/** Up to four stops spread evenly over a longer list. */+function spread(colors: string[]): string[] {+ if (colors.length <= 4) return colors;+ return [0, 1, 2, 3].map(i => colors[Math.round(i * (colors.length - 1) / 3)]!);+}++function fromCss(text: string): CompanionSkin | null {+ const match = /(linear|radial|conic)-gradient\s*\(/i.exec(text);+ if (!match) return null;+ const colors = spread([...text.slice(match.index).matchAll(CSS_COLOR)].map(m => cssColorHex(m[0])));+ if (colors.length < 2) return null;+ const body = text.slice(match.index + match[0].length).toLowerCase();+ const degrees = /(-?\d+(?:\.\d+)?)deg/.exec(body);+ const side = Object.keys(CSS_SIDES).sort((a, b) => b.length - a.length).find(key => body.startsWith(key));+ const angle = degrees ? ((Math.round(Number(degrees[1])) % 360) + 360) % 360 : side ? CSS_SIDES[side]! : 180;+ return { colors, pattern: match[1]!.toLowerCase() === "radial" ? "radial" : "linear", angle, effect: "none", name: "" };+}++/**+ * Reads whatever a person pastes: a design code, an exported design or+ * companion as JSON, a CSS gradient from any gradient site, or just a list of+ * hex colours. Null when nothing usable is in it.+ */+export function parseDesignImport(text: string): CompanionSkin | null {+ const trimmed = text.trim();+ if (!trimmed) return null;+ try {+ if (trimmed.startsWith(CODE_PREFIX)) return fromObject(decodeDesignCode(trimmed));+ if (trimmed.startsWith("{")) return fromObject(JSON.parse(trimmed));+ } catch {+ return null; // A cut-off code or broken JSON: nothing to import, the dialog says so.+ }+ const css = fromCss(trimmed);+ if (css) return css;+ const colors = spread([...trimmed.matchAll(CSS_COLOR)].map(m => cssColorHex(m[0])));+ return colors.length >= 2 ? { colors, pattern: "linear", angle: 135, effect: "none", name: "" } : null;+}++// ---------------------------------------------------------------- from a picture++/**+ * The dominant, clearly different colours of a picture's pixels, darkest+ * last. Buckets the pixels by colour, then takes the most common buckets that+ * are far enough apart, so a galaxy wallpaper gives its violet, its pink and+ * its night blue rather than three shades of black.+ */+export function paletteFromPixels(data: Uint8ClampedArray, count = 3): string[] {+ const buckets = new Map<number, { n: number; r: number; g: number; b: number }>();+ for (let i = 0; i + 3 < data.length; i += 4) {+ if (data[i + 3]! < 128) continue;+ const r = data[i]!, g = data[i + 1]!, b = data[i + 2]!;+ const key = (r >> 4) << 8 | (g >> 4) << 4 | (b >> 4);+ const bucket = buckets.get(key) ?? { n: 0, r: 0, g: 0, b: 0 };+ bucket.n++; bucket.r += r; bucket.g += g; bucket.b += b;+ buckets.set(key, bucket);+ }+ const ranked = [...buckets.values()]+ .map(b => ({ n: b.n, c: [b.r / b.n, b.g / b.n, b.b / b.n] as const }))+ // Saturated colours carry a picture's character; weigh them above greys.+ .map(b => ({ ...b, score: b.n * (1 + 2 * (Math.max(...b.c) - Math.min(...b.c)) / 255) }))+ .sort((a, b) => b.score - a.score);+ const picked: (readonly number[])[] = [];+ for (const minDistance of [90, 60, 30, 0]) {+ for (const { c } of ranked) {+ if (picked.length >= count) break;+ if (picked.every(p => Math.hypot(p[0]! - c[0], p[1]! - c[1], p[2]! - c[2]) >= minDistance) && !picked.includes(c)) picked.push(c);+ }+ if (picked.length >= count) break;+ }+ return picked.map(hex).sort((a, b) => luminance(b) - luminance(a));+}++/** A design from a picture file: its palette, and stars when it is a dark sky. */+export async function skinFromImage(file: Blob): Promise<CompanionSkin | null> {+ const bitmap = await createImageBitmap(file);+ try {+ const canvas = document.createElement("canvas");+ canvas.width = 64; canvas.height = 64;+ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) return null;+ context.drawImage(bitmap, 0, 0, 64, 64);+ const colors = paletteFromPixels(context.getImageData(0, 0, 64, 64).data);+ if (colors.length < 2) return null;+ const dark = colors.reduce((sum, c) => sum + luminance(c), 0) / colors.length < 0.12;+ return { colors, pattern: dark ? "radial" : "linear", angle: 160, effect: dark ? "stars" : "none", name: "" };+ } finally {+ bitmap.close();+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx b/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsxindex a4e241f5aa..dee0fbaacf 100644--- a/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx@@ -41,7 +41,8 @@ export function ComputerPicker({const t = useT();const computers = useComputers();const setActiveSection = useEventStore((s) => s.setActiveSection);- const rows = computers.data ?? [];+ // A switched-off computer is not offered, unless it is the one already chosen.+ const rows = (computers.data ?? []).filter((c) => c.enabled !== false || c.id === value);const chosen = rows.find((c) => c.id === value);return (diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.catalog.test.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.catalog.test.tsxindex 1d03637c89..077dc05549 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.catalog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.catalog.test.tsx@@ -49,6 +49,37 @@ function openDialog() {act(() => { void useCreateAgentDialog.getState().request().catch(() => undefined); });}+test.each(["jarvis", "hermes", "openclaw"])("%s creates Ollama agents from the tool-capable local catalog", async (runtime) => {+ const row: AgentChatProvider = { ...fallback, id: "ollama", label: "Ollama", family: "ollama",+ runner: "brain", cli_installed: null, keyless: true, models_source: "live", hidden_models: [],+ default_model: "text-only", curated_models: [] };+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {+ if (url.includes("/catalog")) return new Response(JSON.stringify(catalog(row)));+ if (url.includes("/agent-runtimes")) return new Response(JSON.stringify({ runtimes: [], supported_providers: ["ollama"] }));+ if (url.includes("/status")) return new Response(JSON.stringify({ mapping: [{ jarvis: "ollama", key_set: false }] }));+ if (url === "/api/providers/ollama/models") return new Response(JSON.stringify({ models: [+ { id: "text-only", label: "Text only", tools: false },+ { id: "qwen:4b", label: "Local tools", tools: true },+ { id: "llamacpp:96f38c742e", label: "Imported tools", tools: true },+ ] }));+ if (url.endsWith("/providers")) return new Response(JSON.stringify({ providers: [{ id: "ollama",+ label: "Ollama", family: "ollama", runner: "brain", subscription: false, keyless: true, accounts: [] }] }));+ throw new Error(`Unexpected request: ${url}`);+ }));+ openDialog();+ await waitFor(() => expect(screen.getByTestId("create-agent-model").textContent).toContain("Local tools"));+ fireEvent.click(screen.getByTestId("create-agent-model"));+ expect(screen.queryByRole("option", { name: "Text only" })).toBeNull();+ expect(screen.getByRole("option", { name: "Imported tools" })).toBeTruthy();+ fireEvent.click(screen.getByRole("option", { name: "Imported tools" }));+ if (runtime !== "jarvis") fireEvent.click(screen.getByRole("radio", { name: runtime === "hermes" ? "Hermes" : "OpenClaw" }));+ expect(screen.getByTestId("create-agent-model").textContent).toContain("Imported tools");+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await waitFor(() => expect(createAgent).toHaveBeenCalledWith(expect.objectContaining({+ runtime, provider: "ollama", model: "llamacpp:96f38c742e",+ })));+});+test("opening replaces a fresh cached GPT-5.2 fallback with the enabled live subscription models", async () => {writeModelMenuSnapshot({ version: 1, savedAt: Date.now(), catalog: catalog(fallback), connections, providers, live: {} });let release!: () => void;diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex d45393dbad..28d909bb83 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -95,7 +95,7 @@ function CreateAgentDialog() {const accounts = accountChoice(option?.seat ?? null);const modelValue = models.some((entry) => entry.id === model) ? model : defaultModel(option);const accountValue = option?.seat.provider.id === accountProvider && accounts.some((entry) => entry.id === account) ? account : "";- const seatKey = `${runtime}|${chosen?.id ?? ""}|${option?.kind ?? ""}|${accountValue}`;+ const seatKey = `${chosen?.id ?? ""}|${option?.kind ?? ""}|${accountValue}`;useEffect(() => {// Another provider or access: its own default model, not the last one's id.setModel("");diff --git a/jarvis/ui/web/frontend/src/components/society/create/seatChoice.ts b/jarvis/ui/web/frontend/src/components/society/create/seatChoice.tsindex 45a193edcf..41d9327105 100644--- a/jarvis/ui/web/frontend/src/components/society/create/seatChoice.ts+++ b/jarvis/ui/web/frontend/src/components/society/create/seatChoice.ts@@ -170,6 +170,9 @@ export function providerChoices(export function accessModels(option: AccessOption | null): CuratedModel[] {if (!option) return [];const models = option.seat.provider.curated_models;+ // Local tags contain parameter sizes, context sizes and user hashes, which+ // are not comparable release versions. Preserve the server's catalog order.+ if (option.kind === "local") return models;const ranked = rankModels(models);return [...ranked.current, ...ranked.older];}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsx b/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsxindex 29384633c4..65c5cd611f 100644--- a/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsx+++ b/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsx@@ -157,7 +157,7 @@ function LevelToast({ toast, name, look, onClose, label }: { toast: Celebration;return (<span key={id} className="level-toast-look">{/* Looks dress the shape; an agent that wears a pet shows only the words. */}- {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} size={30}+ {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} skin={look.skin} size={30}accessories={{ ...look.accessories, ...lookSlot(id) }} />}<span>{label("society.level.new_look").replace("{0}", label(`society.companion.items.${id}`))}</span></span>diff --git a/jarvis/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsx b/jarvis/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsxindex 580f6152fc..210ad48b1e 100644--- a/jarvis/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsx+++ b/jarvis/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsx@@ -221,7 +221,7 @@ function TeamTab({ agents }: { agents: readonly SocietyAgent[] }) {<XpBar fraction={levelFraction(subject)} kind="agent" label={t("society.level.agent_xp_label").replace("{0}", agent.name)} />{next && nextItem && (<span className="hall-rank-next">- {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} size={22}+ {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} skin={look.skin} size={22}accessories={{ ...look.accessories, [nextItem.slot]: next[0] }} />}{t("society.hall.next_look").replace("{0}", t(`society.companion.items.${next[0]}`)).replace("{1}", String(next[1]))}</span>diff --git a/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts b/jarvis/ui/web/frontend/src/hooks/useAppZoom.tsindex 6a2fdd40c3..54e88bd992 100644--- a/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts+++ b/jarvis/ui/web/frontend/src/hooks/useAppZoom.ts@@ -31,6 +31,7 @@ import { appZoomIntentFor, nextAppZoom } from "@/lib/appZoom";import { armZoomTransition, installZoomTransition } from "@/lib/zoomTransition";import { useAppZoomSettings } from "@/store/appZoomSettings";import { useEventStore } from "@/store/events";+import { windowIdentity } from "@/lib/sectionWindows";/** Whether this window's engine zooms: unknown until the first answer. */export type AppZoomSupport = "unknown" | "native" | "browser" | "unsupported";@@ -58,7 +59,7 @@ export function hideZoomIndicator(): void {function windowView(): string | null {const { solo, activeSection } = useEventStore.getState();- return solo ? activeSection : null;+ return solo ? windowIdentity(window.location.search, activeSection) : null;}/**diff --git a/jarvis/ui/web/frontend/src/hooks/useComputers.ts b/jarvis/ui/web/frontend/src/hooks/useComputers.tsindex 747f56dac7..a1f93eb652 100644--- a/jarvis/ui/web/frontend/src/hooks/useComputers.ts+++ b/jarvis/ui/web/frontend/src/hooks/useComputers.ts@@ -17,6 +17,9 @@ import {export const computerKeys = {all: ["computers"] as const,list: () => ["computers", "list"] as const,+ sshHosts: () => ["computers", "ssh-hosts"] as const,+ tailscale: () => ["computers", "tailscale"] as const,+ placement: () => ["computers", "placement"] as const,identity: () => ["computers", "identity"] as const,cloud: () => ["computers", "cloud"] as const,cloudServers: (p: CloudProviderId) => ["computers", "cloud", p, "servers"] as const,@@ -105,6 +108,86 @@ export function useCheckAll() {});}+/** Edit one record (rename, switch on/off, "Automatic" share). */+export function useUpdateComputer() {+ const upsert = useUpsertComputer();+ return useMutation({+ mutationFn: ({ id, patch }: { id: string; patch: Parameters<typeof computersApi.update>[1] }) =>+ computersApi.update(id, patch),+ onSuccess: upsert,+ });+}++/** Add, reorder and forget a computer's addresses. */+export function useRouteMutations() {+ const upsert = useUpsertComputer();+ const qc = useQueryClient();+ const settle = (computer: Computer) => {+ upsert(computer);+ void qc.invalidateQueries({ queryKey: computerKeys.tailscale() });+ };+ return {+ add: useMutation({+ mutationFn: ({ id, route }: { id: string; route: Parameters<typeof computersApi.addRoute>[1] }) =>+ computersApi.addRoute(id, route),+ onSuccess: settle,+ }),+ order: useMutation({+ mutationFn: ({ id, routeIds }: { id: string; routeIds: string[] }) =>+ computersApi.orderRoutes(id, routeIds),+ onSuccess: settle,+ }),+ remove: useMutation({+ mutationFn: ({ id, routeId }: { id: string; routeId: string }) =>+ computersApi.removeRoute(id, routeId),+ onSuccess: settle,+ }),+ };+}++/** Servers this PC's own ssh knows; read once per dialog. */+export function useSshHosts(enabled: boolean) {+ return useQuery({+ queryKey: computerKeys.sshHosts(),+ queryFn: computersApi.sshHosts,+ enabled,+ staleTime: 30_000,+ });+}++/** This PC's tailnet and the addresses each computer could add. */+export function useTailscale(enabled = true) {+ return useQuery({+ queryKey: computerKeys.tailscale(),+ queryFn: computersApi.tailscale,+ enabled,+ staleTime: 60_000,+ retry: false,+ });+}++export function usePlacement() {+ return useQuery({ queryKey: computerKeys.placement(), queryFn: computersApi.placement, retry: false });+}++export function useSetPlacement() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: computersApi.setPlacement,+ onSuccess: (settings) => qc.setQueryData(computerKeys.placement(), settings),+ });+}++/** Share this PC's GitHub login with one computer's agents, or take it back. */+export function useGithubShare() {+ const upsert = useUpsertComputer();+ return useMutation({+ mutationFn: ({ id, share }: { id: string; share: boolean }) =>+ share ? computersApi.shareGithub(id) : computersApi.unshareGithub(id),+ onSuccess: upsert,+ });+}+export function useRemoveComputer() {const qc = useQueryClient();return useMutation({diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionUrlMemory.test.ts b/jarvis/ui/web/frontend/src/hooks/useSectionUrlMemory.test.tsindex f8ab8675a7..594c67fa4b 100644--- a/jarvis/ui/web/frontend/src/hooks/useSectionUrlMemory.test.ts+++ b/jarvis/ui/web/frontend/src/hooks/useSectionUrlMemory.test.ts@@ -29,12 +29,12 @@ describe("useSectionUrlMemory", () => {expect(initialSectionFromSearch(window.location.search)).toBe("sessions");});- it("leaves a detached window's own flags alone", () => {+ it("preserves a detached window's identity while remembering its section", () => {window.history.replaceState(null, "", "/?solo=1&view=chats");renderHook(() => useSectionUrlMemory());act(() => useEventStore.getState().setActiveSection("visualization"));- expect(window.location.search).toBe("?solo=1&view=visualization");+ expect(window.location.search).toBe("?solo=1&view=visualization&window=chats");});});diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/de.jsonindex b271fdaa4e..893d457743 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/de.json@@ -207,6 +207,50 @@"list_title": "Deine Computer","list_summary": "{online} von {total} online","list_attention": "{count} brauchen Aufmerksamkeit",+ "row_switched_off": "Ausgeschaltet",+ "row_switch_label": "{computer} verwenden",+ "row_routes_one": "1 Adresse",+ "row_routes_many": "{count} Adressen",+ "status_last_check": "Letzte Prüfung: {ago}",+ "status_error_id": "Fehler-ID: {id}",+ "copy_error_id": "Fehler-ID kopieren",+ "copied_error_id": "Fehler-ID kopiert",+ "routes_title": "Adressen",+ "routes_hint": "Werden von oben nach unten versucht. Die erste, die antwortet, wird genutzt; eine weiter oben übernimmt wieder, sobald sie antwortet.",+ "route_active": "In Benutzung",+ "route_seen": "Zuletzt erreicht: {ago}",+ "route_source_tailscale": "Tailscale",+ "route_source_ssh_config": "SSH-Konfiguration",+ "route_move_up": "Nach oben",+ "route_move_down": "Nach unten",+ "route_remove": "Adresse entfernen",+ "route_add": "Adresse hinzufügen",+ "route_add_host": "Hostname oder IP-Adresse",+ "route_add_label": "Name (optional)",+ "route_adding": "Wird geprüft …",+ "route_suggest": "Im Tailscale-Netz als {host}",+ "known_title": "Auf diesem PC bekannt",+ "known_body": "Aus den SSH-Einstellungen dieses PCs. Wähle einen aus, um das Formular auszufüllen.",+ "known_from_config": "SSH-Konfiguration",+ "known_from_history": "Schon einmal verbunden",+ "known_proxy": "Braucht einen Jump-Host, noch nicht unterstützt",+ "known_added": "Schon hinzugefügt",+ "known_key": "Hat einen eigenen Schlüssel",+ "github_title": "GitHub für die Agents hier",+ "github_body": "Teilt den GitHub-Login dieses PCs mit den Coding-Agents auf diesem Computer, damit sie klonen und pushen können, während dieser PC aus ist.",+ "github_warning": "Sie bekommen denselben Zugriff auf GitHub wie du. Teile ihn nur mit Servern, die du kontrollierst.",+ "github_share": "Teilen",+ "github_unshare": "Nicht mehr teilen",+ "github_shared": "Geteilt: {ago}",+ "github_refresh": "Erneut teilen",+ "placement_title": "Automatische Verteilung",+ "placement_body": "Neue Workspaces können sich selbst einen Rechner aussuchen. Lege fest, wie oft jeder neue Arbeit bekommt.",+ "placement_switch": "„Automatisch“ für neue Workspaces anbieten",+ "placement_this_pc": "Dieser PC",+ "weight_0": "Nie",+ "weight_1": "Weniger",+ "weight_2": "Normal",+ "weight_3": "Mehr","settings_title": "Für alle Computer","col_computer": "Computer","col_status": "Status",@@ -375,6 +419,19 @@"cx_server_host": "Host","cx_pairing_code": "Pairing-Code","cx_pairing_hint": "Füge eine vollständige Pairing-URL ein, um beide Felder automatisch auszufüllen.",- "cx_pairing_unavailable": "Das Verbinden per Pairing-Code ist noch nicht verfügbar. Über SSH kannst du dich bereits verbinden."+ "paired_servers": "Jarvis-Server",+ "paired_load_failed": "Server-Verbindungen konnten nicht geladen werden.",+ "paired_verified": "Bei der letzten Prüfung verbunden",+ "paired_offline": "Verbindung nicht verfügbar – Server prüfen oder erneut koppeln",+ "paired_open": "Server öffnen",+ "paired_disconnect": "Trennen und Zugang widerrufen",+ "paired_connection_hint": "Verwende den Code, der auf dem Zielserver in Jarvis erzeugt wurde. Entfernte Adressen benötigen HTTPS; ein SSH-Tunnel kann lokales HTTP verwenden.",+ "pair_this_server": "Einen anderen Computer mit diesem Jarvis verbinden",+ "pair_access_hint": "Erzeuge auf der Zielinstanz einen einmaligen Code. Jeder mit diesem Code kann diesen Jarvis öffnen und steuern. Er läuft nach fünf Minuten ab. Der andere Computer muss diesen Server über HTTPS oder einen SSH-Tunnel erreichen können. Ein Widerruf sperrt neue Verbindungen; bereits geöffnete Browsersitzungen bleiben angemeldet.",+ "pair_generate": "Pairing-Code erzeugen",+ "pair_link": "Pairing-URL",+ "pair_expires": "Gültig bis",+ "pair_revoke": "Zugang widerrufen",+ "paired_no_ssh": "Noch keine SSH-Computer"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/en.jsonindex 334066dd99..1ea2c87402 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/en.json@@ -207,6 +207,50 @@"list_title": "Your computers","list_summary": "{online} of {total} online","list_attention": "{count} need attention",+ "row_switched_off": "Switched off",+ "row_switch_label": "Use {computer}",+ "row_routes_one": "1 address",+ "row_routes_many": "{count} addresses",+ "status_last_check": "Last check: {ago}",+ "status_error_id": "Error ID: {id}",+ "copy_error_id": "Copy error ID",+ "copied_error_id": "Error ID copied",+ "routes_title": "Addresses",+ "routes_hint": "Tried from top to bottom. The first one that answers is used; a higher one takes over again as soon as it answers.",+ "route_active": "In use",+ "route_seen": "Last reached: {ago}",+ "route_source_tailscale": "Tailscale",+ "route_source_ssh_config": "SSH config",+ "route_move_up": "Move up",+ "route_move_down": "Move down",+ "route_remove": "Remove address",+ "route_add": "Add address",+ "route_add_host": "Host name or IP address",+ "route_add_label": "Name (optional)",+ "route_adding": "Checking…",+ "route_suggest": "On Tailscale as {host}",+ "known_title": "Known on this PC",+ "known_body": "From this PC's SSH settings. Pick one to fill in the form.",+ "known_from_config": "SSH config",+ "known_from_history": "Connected before",+ "known_proxy": "Needs a jump host, not supported yet",+ "known_added": "Already added",+ "known_key": "Has its own key",+ "github_title": "GitHub for the agents here",+ "github_body": "Shares this PC's GitHub login with the coding agents on this computer, so they can clone and push while this PC is off.",+ "github_warning": "They get the same access to GitHub as you. Share only with servers you control.",+ "github_share": "Share",+ "github_unshare": "Stop sharing",+ "github_shared": "Shared: {ago}",+ "github_refresh": "Share again",+ "placement_title": "Automatic placement",+ "placement_body": "New workspaces can pick a machine themselves. Choose how often each one gets new work.",+ "placement_switch": "Offer “Automatic” for new workspaces",+ "placement_this_pc": "This PC",+ "weight_0": "Never",+ "weight_1": "Less",+ "weight_2": "Normal",+ "weight_3": "More","settings_title": "For all computers","col_computer": "Computer","col_status": "Status",@@ -375,6 +419,19 @@"cx_server_host": "Host","cx_pairing_code": "Pairing code","cx_pairing_hint": "Paste a full pairing URL here to fill both fields automatically.",- "cx_pairing_unavailable": "Connecting with a pairing code is not available yet. Use SSH to connect now."+ "paired_servers": "Jarvis servers",+ "paired_load_failed": "Server connections could not be loaded.",+ "paired_verified": "Connected at the last check",+ "paired_offline": "Connection unavailable — check the server or pair again",+ "paired_open": "Open server",+ "paired_disconnect": "Disconnect and revoke access",+ "paired_connection_hint": "Use the code generated on the target Jarvis server. Remote addresses require HTTPS; an SSH tunnel can use local HTTP.",+ "pair_this_server": "Allow another computer to connect to this Jarvis",+ "pair_access_hint": "Generate a single-use code on the target instance. Anyone with this code can open and control this Jarvis. It expires after five minutes. The other computer must be able to reach this server over HTTPS or an SSH tunnel. Revoking a client blocks new connections; already opened browser sessions remain signed in.",+ "pair_generate": "Generate pairing code",+ "pair_link": "Pairing URL",+ "pair_expires": "Expires at",+ "pair_revoke": "Revoke access",+ "paired_no_ssh": "No SSH computers yet"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/es.jsonindex ef8fc999f4..fa7e6037ea 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/es.json@@ -207,6 +207,50 @@"list_title": "Tus ordenadores","list_summary": "{online} de {total} en línea","list_attention": "{count} requieren atención",+ "row_switched_off": "Desactivado",+ "row_switch_label": "Usar {computer}",+ "row_routes_one": "1 dirección",+ "row_routes_many": "{count} direcciones",+ "status_last_check": "Última comprobación: {ago}",+ "status_error_id": "ID de error: {id}",+ "copy_error_id": "Copiar ID de error",+ "copied_error_id": "ID de error copiado",+ "routes_title": "Direcciones",+ "routes_hint": "Se prueban de arriba abajo. Se usa la primera que responde; una más arriba vuelve a tomar el relevo en cuanto responde.",+ "route_active": "En uso",+ "route_seen": "Último contacto: {ago}",+ "route_source_tailscale": "Tailscale",+ "route_source_ssh_config": "Configuración SSH",+ "route_move_up": "Subir",+ "route_move_down": "Bajar",+ "route_remove": "Quitar dirección",+ "route_add": "Añadir dirección",+ "route_add_host": "Nombre de host o dirección IP",+ "route_add_label": "Nombre (opcional)",+ "route_adding": "Comprobando…",+ "route_suggest": "En Tailscale como {host}",+ "known_title": "Conocidos en este PC",+ "known_body": "De la configuración SSH de este PC. Elige uno para rellenar el formulario.",+ "known_from_config": "Configuración SSH",+ "known_from_history": "Conectado antes",+ "known_proxy": "Necesita un host de salto, aún no compatible",+ "known_added": "Ya añadido",+ "known_key": "Tiene su propia clave",+ "github_title": "GitHub para los agentes de aquí",+ "github_body": "Comparte el inicio de sesión de GitHub de este PC con los agentes de código de este equipo, para que puedan clonar y hacer push mientras este PC está apagado.",+ "github_warning": "Obtienen el mismo acceso a GitHub que tú. Compártelo solo con servidores que controles.",+ "github_share": "Compartir",+ "github_unshare": "Dejar de compartir",+ "github_shared": "Compartido: {ago}",+ "github_refresh": "Compartir de nuevo",+ "placement_title": "Reparto automático",+ "placement_body": "Los espacios de trabajo nuevos pueden elegir una máquina por sí mismos. Elige con qué frecuencia recibe trabajo cada una.",+ "placement_switch": "Ofrecer “Automático” para espacios de trabajo nuevos",+ "placement_this_pc": "Este PC",+ "weight_0": "Nunca",+ "weight_1": "Menos",+ "weight_2": "Normal",+ "weight_3": "Más","settings_title": "Para todos los ordenadores","col_computer": "Ordenador","col_status": "Estado",@@ -375,6 +419,19 @@"cx_server_host": "Host","cx_pairing_code": "Código de emparejamiento","cx_pairing_hint": "Pega una URL de emparejamiento completa para rellenar ambos campos automáticamente.",- "cx_pairing_unavailable": "La conexión mediante código de emparejamiento aún no está disponible. Usa SSH para conectarte ahora."+ "paired_servers": "Servidores Jarvis",+ "paired_load_failed": "No se pudieron cargar las conexiones con servidores.",+ "paired_verified": "Conectado en la última comprobación",+ "paired_offline": "Conexión no disponible: comprueba el servidor o vuelve a emparejarlo",+ "paired_open": "Abrir servidor",+ "paired_disconnect": "Desconectar y revocar el acceso",+ "paired_connection_hint": "Usa el código generado en el servidor Jarvis de destino. Las direcciones remotas requieren HTTPS; un túnel SSH puede usar HTTP local.",+ "pair_this_server": "Permitir que otro ordenador se conecte a este Jarvis",+ "pair_access_hint": "Genera un código de un solo uso en la instancia de destino. Cualquiera que tenga este código puede abrir y controlar este Jarvis. Caduca a los cinco minutos. El otro ordenador debe poder acceder al servidor mediante HTTPS o un túnel SSH. Revocar un cliente bloquea las conexiones nuevas; las sesiones de navegador ya abiertas siguen conectadas.",+ "pair_generate": "Generar código de emparejamiento",+ "pair_link": "URL de emparejamiento",+ "pair_expires": "Caduca a las",+ "pair_revoke": "Revocar acceso",+ "paired_no_ssh": "Aún no hay ordenadores SSH"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/computers/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/computers/zh.jsonindex b0dd2fe8b9..741415705a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/computers/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/computers/zh.json@@ -207,6 +207,50 @@"list_title": "你的电脑","list_summary": "{total} 台中 {online} 台在线","list_attention": "{count} 台需要处理",+ "row_switched_off": "已关闭",+ "row_switch_label": "使用 {computer}",+ "row_routes_one": "1 个地址",+ "row_routes_many": "{count} 个地址",+ "status_last_check": "上次检查:{ago}",+ "status_error_id": "错误 ID:{id}",+ "copy_error_id": "复制错误 ID",+ "copied_error_id": "已复制错误 ID",+ "routes_title": "地址",+ "routes_hint": "从上到下依次尝试,使用第一个有响应的地址;排在前面的地址一旦恢复响应就会重新接管。",+ "route_active": "使用中",+ "route_seen": "上次连通:{ago}",+ "route_source_tailscale": "Tailscale",+ "route_source_ssh_config": "SSH 配置",+ "route_move_up": "上移",+ "route_move_down": "下移",+ "route_remove": "移除地址",+ "route_add": "添加地址",+ "route_add_host": "主机名或 IP 地址",+ "route_add_label": "名称(可选)",+ "route_adding": "正在检查…",+ "route_suggest": "在 Tailscale 中为 {host}",+ "known_title": "此电脑已知",+ "known_body": "来自此电脑的 SSH 设置。选择一个即可填写表单。",+ "known_from_config": "SSH 配置",+ "known_from_history": "以前连接过",+ "known_proxy": "需要跳板机,暂不支持",+ "known_added": "已添加",+ "known_key": "有自己的密钥",+ "github_title": "此处代理的 GitHub",+ "github_body": "将此电脑的 GitHub 登录共享给这台计算机上的编程代理,使它们在此电脑关机时也能克隆和推送。",+ "github_warning": "它们将获得与你相同的 GitHub 权限。只与你掌控的服务器共享。",+ "github_share": "共享",+ "github_unshare": "停止共享",+ "github_shared": "已共享:{ago}",+ "github_refresh": "重新共享",+ "placement_title": "自动分配",+ "placement_body": "新工作区可以自行选择机器。设置每台机器接收新工作的频率。",+ "placement_switch": "为新工作区提供“自动”选项",+ "placement_this_pc": "此电脑",+ "weight_0": "从不",+ "weight_1": "较少",+ "weight_2": "正常",+ "weight_3": "较多","settings_title": "适用于所有电脑","col_computer": "电脑","col_status": "状态",@@ -375,6 +419,19 @@"cx_server_host": "主机","cx_pairing_code": "配对码","cx_pairing_hint": "粘贴完整的配对链接,即可自动填写两个字段。",- "cx_pairing_unavailable": "暂不支持通过配对码连接。现在可以使用 SSH 连接。"+ "paired_servers": "Jarvis 服务器",+ "paired_load_failed": "无法加载服务器连接。",+ "paired_verified": "上次检查时已连接",+ "paired_offline": "连接不可用,请检查服务器或重新配对",+ "paired_open": "打开服务器",+ "paired_disconnect": "断开连接并撤销访问权限",+ "paired_connection_hint": "使用目标 Jarvis 服务器上生成的配对码。远程地址需要 HTTPS;SSH 隧道可以使用本地 HTTP。",+ "pair_this_server": "允许另一台计算机连接到此 Jarvis",+ "pair_access_hint": "在目标实例上生成一次性配对码。持有码的人可以打开并控制此 Jarvis。配对码五分钟后过期。另一台计算机必须能够通过 HTTPS 或 SSH 隧道访问此服务器。撤销客户端会阻止新连接,但已打开的浏览器会话仍保持登录。",+ "pair_generate": "生成配对码",+ "pair_link": "配对链接",+ "pair_expires": "有效期至",+ "pair_revoke": "撤销访问权限",+ "paired_no_ssh": "尚无 SSH 计算机"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 5c9013b55f..632d9f656a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1,9 +1,56 @@{"custom_apis": {+ "connections_subtitle": "Deine Dienste für Jarvis und deine Agenten.",+ "add_title": "Plugin hinzufügen",+ "simple_hint": "Nur den Namen und den API-Key eingeben.",+ "edit_hint": "Ersetze den Schlüssel dieser Verbindung.",+ "service_name": "Name des Dienstes",+ "name_example": "Zum Beispiel ElevenLabs",+ "key_placeholder": "API-Key des Dienstes einfügen",+ "private_key": "Dein Schlüssel bleibt im geschützten Speicher. Agenten nutzen den Dienst, ohne den Schlüssel zu erhalten.",+ "automatic": "Jarvis übernimmt die Einrichtung",+ "automatic_hint": "Logo und verfügbare Aktionen werden automatisch hinzugefügt. Du kannst so viele Dienste verbinden, wie du möchtest.",+ "inheritance": "Neue Fähigkeiten stehen Jarvis und deinen Agenten automatisch zur Verfügung. Ihre bestehenden Berechtigungen gelten weiterhin.",+ "connect": "Plugin hinzufügen",+ "connecting": "Wird eingerichtet…",+ "discovering": "Der Dienst und seine verfügbaren Aktionen werden ermittelt.",+ "edit_key": "API-Key aktualisieren",+ "save_key": "Schlüssel speichern",+ "manage": "Verwalten",+ "pause": "Verbindung pausieren",+ "resume": "Verbindung fortsetzen",+ "paused": "Pausiert",+ "status_configured": "Eingerichtet",+ "status_verified": "Verbunden",+ "status_limited": "Eingeschränkter Zugriff",+ "capabilities_count": "Fähigkeiten",+ "capabilities_hint": "Sag Jarvis oder einem Agenten, was du erledigen möchtest. Sie finden die passende Aktion und nutzen diese Verbindung für dich.",+ "search_capabilities": "Fähigkeiten durchsuchen…",+ "blocked": "Blockiert",+ "partial_capabilities": "{count} Aktionen konnten nicht automatisch übernommen werden.",+ "remove_confirm": "Diese Verbindung für Jarvis und deine Agenten entfernen?",+ "errors": {+ "invalid_key": "Der Dienst akzeptiert diesen API-Key nicht. Bitte prüfe ihn.",+ "key_required": "Gib den API-Key des Dienstes ein.",+ "invalid_service_name": "Gib den Namen des Dienstes ein.",+ "service_not_found": "Der Dienst konnte nicht eindeutig erkannt werden. Versuche seinen vollständigen Namen.",+ "ambiguous_service": "Mehrere Dienste passen zu diesem Namen. Wähle den gemeinten Dienst.",+ "documentation_not_found": "Für diesen Dienst wurde noch keine brauchbare öffentliche API-Beschreibung gefunden.",+ "documentation_unavailable": "Die Dokumentation des Dienstes konnte nicht geladen werden. Bitte versuche es erneut.",+ "discovery_timeout": "Die Suche nach dem Dienst hat zu lange gedauert. Bitte versuche es erneut.",+ "unsafe_documentation": "Die Dokumentationsadresse des Dienstes konnte nicht verifiziert werden.",+ "documentation_too_large": "Die API-Beschreibung dieses Dienstes ist für den automatischen Import zu groß.",+ "service_address_mismatch": "Die API-Adresse ließ sich nicht zuverlässig zuordnen. Dein Schlüssel wurde nicht übertragen.",+ "connection_name_changed": "Füge zum Wechseln des Dienstes eine neue Verbindung hinzu.",+ "storage_unavailable": "Die Verbindung konnte nicht gespeichert werden. Bitte versuche es erneut.",+ "not_ready": "Jarvis startet noch. Bitte versuche es gleich erneut.",+ "unsupported_api": "Dieser Dienst lässt sich noch nicht automatisch mit einem einzelnen API-Key einrichten.",+ "invalid_connection": "Diese Verbindung ist nicht mehr verfügbar."+ },"download": "Ergebnis herunterladen",- "title": "Eigene APIs",+ "title": "Eigene Plugins","subtitle": "Verbinde eigene Dienste und stelle ihre Aktionen Jarvis und deinen Agenten zur Verfügung.",- "add": "API hinzufügen",+ "add": "Plugin hinzufügen","elevenlabs": "ElevenLabs-Vorlage","import": "Definition importieren","export": "Exportieren",@@ -232,9 +279,12 @@"update_blocked_no_appimage": "Diese Kopie wurde nicht aus ihrer AppImage-Datei gestartet, es gibt also nichts zu ersetzen. Lade stattdessen das neue AppImage.","update_blocked_appimage_read_only": "{name} darf im Ordner des AppImage nicht schreiben. Verschiebe das AppImage in einen eigenen Ordner wie ~/Applications und aktualisiere dann.","update_open_release": "Download-Seite öffnen",- "detach": "Eigenes Fenster",+ "detach": "Fenster abtrennen",+ "return_to_main": "Zurück ins Hauptfenster",+ "return_to_main_hint": "Dieses Fenster schließen und den Bereich ins Hauptfenster zurückholen","detach_hint": "Diese Ansicht in einem eigenen Fenster öffnen","detach_failed": "Eigenes Fenster konnte nicht geöffnet werden",+ "reattach_failed": "Die Ansicht konnte nicht zurückgeholt werden","detached_title": "Diese Ansicht ist in einem eigenen Fenster geöffnet","detached_body": "Arbeite dort weiter oder hole sie hierher zurück.","detach_focus": "Fenster zeigen",@@ -6737,6 +6787,26 @@"weekly_scoped": "Wochenlimit · {scope}","monthly": "Monatslimit","other": "Weiteres Limit"+ },+ "switch": {+ "use": "Wechseln",+ "use_tip": "{tool} auf diesem Abo betreiben: Neue Terminals starten hier, und jeder laufende Agent zieht um und setzt seine eigene Unterhaltung fort.",+ "switching": "Wechselt…",+ "done": "Läuft jetzt auf {label}.",+ "moved": "{n} Agent(s) samt Unterhaltung umgezogen.",+ "queued": "{n} arbeitende(r) Agent(s) folgen, sobald ihr aktueller Schritt endet.",+ "failed": "Der Wechsel hat nicht geklappt ({error}).",+ "empty_until": "Aufgebraucht bis {when}",+ "auto": "Automatisch wechseln",+ "auto_tip": "Wenn ein Abo knapp wird oder sein Limit erreicht, ziehen laufende Agents auf das Abo mit dem meisten Restbudget um und arbeiten weiter.",+ "threshold": "Wann wechseln",+ "at_left": "bei {left} % Rest",+ "at_limit": "erst am Limit",+ "event_manual": "{time} · {tool} auf {to} gewechselt",+ "event_limit": "{time} · {tool}: {from} hat das Limit erreicht, weiter auf {to}",+ "event_threshold": "{time} · {tool}: {from} fast aufgebraucht, umgezogen auf {to}",+ "event_no_seat": "{time} · {tool}: {from} ist aufgebraucht, und kein anderes Abo hat noch Budget",+ "event_refilled": "{time} · {tool}: {from} wieder aufgefüllt, unterbrochene Arbeit läuft weiter"}},"git": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex ea84707d27..1e3f3df386 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1,9 +1,56 @@{"custom_apis": {+ "connections_subtitle": "Your services, available to Jarvis and your agents.",+ "add_title": "Add a plugin",+ "simple_hint": "Just its name and API key.",+ "edit_hint": "Replace the key for this connection.",+ "service_name": "Service name",+ "name_example": "For example, ElevenLabs",+ "key_placeholder": "Paste the service's API key",+ "private_key": "Your key stays in protected storage. Agents use the service without receiving the key.",+ "automatic": "Jarvis takes care of the setup",+ "automatic_hint": "The service's logo and available actions are added automatically. You can connect as many services as you need.",+ "inheritance": "New capabilities become available to Jarvis and your agents automatically, within their existing permissions.",+ "connect": "Add plugin",+ "connecting": "Setting up…",+ "discovering": "Finding the service and learning its available actions.",+ "edit_key": "Update API key",+ "save_key": "Save key",+ "manage": "Manage",+ "pause": "Pause connection",+ "resume": "Resume connection",+ "paused": "Paused",+ "status_configured": "Set up",+ "status_verified": "Connected",+ "status_limited": "Limited access",+ "capabilities_count": "capabilities",+ "capabilities_hint": "Tell Jarvis or an agent what you want to do. They find the right action and use this connection for you.",+ "search_capabilities": "Search capabilities…",+ "blocked": "Blocked",+ "partial_capabilities": "{count} operations could not be imported automatically.",+ "remove_confirm": "Remove this connection from Jarvis and your agents?",+ "errors": {+ "invalid_key": "The service did not accept this API key. Please check it.",+ "key_required": "Enter the service's API key.",+ "invalid_service_name": "Enter the service name.",+ "service_not_found": "We could not identify this service. Try its full name.",+ "ambiguous_service": "Several services match this name. Choose the one you mean.",+ "documentation_not_found": "We could not find a usable public API description for this service yet.",+ "documentation_unavailable": "The service documentation could not be loaded. Please try again.",+ "discovery_timeout": "Finding the service took too long. Please try again.",+ "unsafe_documentation": "The service's documentation address could not be verified.",+ "documentation_too_large": "This service's API description is too large to import automatically.",+ "service_address_mismatch": "The API address could not be matched reliably to this service. Your key was not sent.",+ "connection_name_changed": "Add a new connection to switch to another service.",+ "storage_unavailable": "The connection could not be saved. Please try again.",+ "not_ready": "Jarvis is still starting. Please try again shortly.",+ "unsupported_api": "This service cannot yet be set up automatically with a single API key.",+ "invalid_connection": "This connection is no longer available."+ },"download": "Download result",- "title": "Custom APIs",+ "title": "Your plugins","subtitle": "Connect your own services and make their actions available to Jarvis and your agents.",- "add": "Add API",+ "add": "Add plugin","elevenlabs": "ElevenLabs template","import": "Import definition","export": "Export",@@ -232,9 +279,12 @@"update_blocked_no_appimage": "This copy wasn't started from its AppImage file, so there is nothing to replace. Download the new AppImage instead.","update_blocked_appimage_read_only": "{name} can't write to the AppImage's folder. Move the AppImage to a folder you own, such as ~/Applications, then update.","update_open_release": "Open download page",- "detach": "Own window",+ "detach": "Detach window",+ "return_to_main": "Back to main window",+ "return_to_main_hint": "Close this window and bring the section back into the main window","detach_hint": "Open this view in its own window","detach_failed": "Could not open a separate window",+ "reattach_failed": "Could not bring the view back","detached_title": "This view is open in its own window","detached_body": "Keep working there, or bring it back into this window.","detach_focus": "Show window",@@ -6737,6 +6787,26 @@"weekly_scoped": "Weekly limit · {scope}","monthly": "Monthly limit","other": "Other limit"+ },+ "switch": {+ "use": "Switch",+ "use_tip": "Run {tool} on this subscription: new terminals start here and every running agent moves over, continuing its own conversation.",+ "switching": "Switching…",+ "done": "Now running on {label}.",+ "moved": "{n} agent(s) moved with their conversation.",+ "queued": "{n} working agent(s) follow when their current step ends.",+ "failed": "The switch did not go through ({error}).",+ "empty_until": "Used up until {when}",+ "auto": "Switch automatically",+ "auto_tip": "When a subscription runs low or hits its limit, running agents move to the subscription with the most budget left and keep working.",+ "threshold": "When to switch",+ "at_left": "at {left}% left",+ "at_limit": "only at the limit",+ "event_manual": "{time} · {tool} switched to {to}",+ "event_limit": "{time} · {tool}: {from} hit its limit, work continued on {to}",+ "event_threshold": "{time} · {tool}: {from} nearly used up, work moved to {to}",+ "event_no_seat": "{time} · {tool}: {from} is used up and no other subscription has budget left",+ "event_refilled": "{time} · {tool}: {from} refilled, interrupted work continued"}},"git": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex c0b344bc33..7de678813c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1,9 +1,56 @@{"custom_apis": {+ "connections_subtitle": "Tus servicios, disponibles para Jarvis y tus agentes.",+ "add_title": "Añadir un plugin",+ "simple_hint": "Solo el nombre y la clave API.",+ "edit_hint": "Sustituye la clave de esta conexión.",+ "service_name": "Nombre del servicio",+ "name_example": "Por ejemplo, ElevenLabs",+ "key_placeholder": "Pega la clave API del servicio",+ "private_key": "Tu clave permanece protegida. Los agentes usan el servicio sin recibir la clave.",+ "automatic": "Jarvis se encarga de la configuración",+ "automatic_hint": "El logo y las acciones disponibles se añaden automáticamente. Puedes conectar tantos servicios como necesites.",+ "inheritance": "Las nuevas capacidades se ofrecen automáticamente a Jarvis y tus agentes, respetando sus permisos actuales.",+ "connect": "Añadir plugin",+ "connecting": "Configurando…",+ "discovering": "Buscando el servicio y sus acciones disponibles.",+ "edit_key": "Actualizar clave API",+ "save_key": "Guardar clave",+ "manage": "Gestionar",+ "pause": "Pausar conexión",+ "resume": "Reanudar conexión",+ "paused": "Pausada",+ "status_configured": "Configurada",+ "status_verified": "Conectada",+ "status_limited": "Acceso limitado",+ "capabilities_count": "capacidades",+ "capabilities_hint": "Dile a Jarvis o a un agente qué quieres hacer. Buscarán la acción adecuada y usarán esta conexión.",+ "search_capabilities": "Buscar capacidades…",+ "blocked": "Bloqueada",+ "partial_capabilities": "No se pudieron importar automáticamente {count} operaciones.",+ "remove_confirm": "¿Eliminar esta conexión para Jarvis y tus agentes?",+ "errors": {+ "invalid_key": "El servicio no aceptó esta clave API. Revísala.",+ "key_required": "Introduce la clave API del servicio.",+ "invalid_service_name": "Introduce el nombre del servicio.",+ "service_not_found": "No pudimos identificar el servicio. Prueba su nombre completo.",+ "ambiguous_service": "Varios servicios coinciden. Elige el que buscas.",+ "documentation_not_found": "Todavía no encontramos una descripción pública de API utilizable para este servicio.",+ "documentation_unavailable": "No se pudo cargar la documentación. Inténtalo de nuevo.",+ "discovery_timeout": "La búsqueda tardó demasiado. Inténtalo de nuevo.",+ "unsafe_documentation": "No se pudo verificar la dirección de la documentación.",+ "documentation_too_large": "La descripción de esta API es demasiado grande para importarla automáticamente.",+ "service_address_mismatch": "No se pudo vincular la dirección de API con este servicio. Tu clave no se envió.",+ "connection_name_changed": "Añade una nueva conexión para cambiar de servicio.",+ "storage_unavailable": "No se pudo guardar la conexión. Inténtalo de nuevo.",+ "not_ready": "Jarvis se está iniciando. Vuelve a intentarlo en breve.",+ "unsupported_api": "Este servicio todavía no admite la configuración automática con una sola clave API.",+ "invalid_connection": "Esta conexión ya no está disponible."+ },"download": "Descargar resultado",- "title": "APIs propias",+ "title": "Tus plugins","subtitle": "Conecta tus servicios y ofrece sus acciones a Jarvis y a tus agentes.",- "add": "Añadir API",+ "add": "Añadir plugin","elevenlabs": "Plantilla de ElevenLabs","import": "Importar definición","export": "Exportar",@@ -232,9 +279,12 @@"update_blocked_no_appimage": "Esta copia no se inició desde su archivo AppImage, así que no hay nada que reemplazar. Descarga el nuevo AppImage.","update_blocked_appimage_read_only": "{name} no puede escribir en la carpeta del AppImage. Mueve el AppImage a una carpeta tuya, como ~/Applications, y luego actualiza.","update_open_release": "Abrir página de descarga",- "detach": "Ventana propia",+ "detach": "Separar ventana",+ "return_to_main": "Volver a la ventana principal",+ "return_to_main_hint": "Cerrar esta ventana y devolver la sección a la ventana principal","detach_hint": "Abrir esta vista en su propia ventana","detach_failed": "No se pudo abrir una ventana separada",+ "reattach_failed": "No se pudo devolver la vista a la ventana principal","detached_title": "Esta vista está abierta en su propia ventana","detached_body": "Sigue trabajando allí o tráela de vuelta aquí.","detach_focus": "Mostrar ventana",@@ -6737,6 +6787,26 @@"weekly_scoped": "Límite semanal · {scope}","monthly": "Límite mensual","other": "Otro límite"+ },+ "switch": {+ "use": "Cambiar",+ "use_tip": "Usar {tool} con esta suscripción: los terminales nuevos empiezan aquí y cada agente en marcha se traslada y continúa su propia conversación.",+ "switching": "Cambiando…",+ "done": "Ahora funciona con {label}.",+ "moved": "{n} agente(s) trasladado(s) con su conversación.",+ "queued": "{n} agente(s) en marcha seguirán cuando termine su paso actual.",+ "failed": "El cambio no se completó ({error}).",+ "empty_until": "Agotada hasta {when}",+ "auto": "Cambiar automáticamente",+ "auto_tip": "Cuando una suscripción se queda corta o llega a su límite, los agentes en marcha pasan a la suscripción con más presupuesto y siguen trabajando.",+ "threshold": "Cuándo cambiar",+ "at_left": "con un {left} % restante",+ "at_limit": "solo al llegar al límite",+ "event_manual": "{time} · {tool} cambió a {to}",+ "event_limit": "{time} · {tool}: {from} llegó a su límite, el trabajo siguió en {to}",+ "event_threshold": "{time} · {tool}: {from} casi agotada, el trabajo pasó a {to}",+ "event_no_seat": "{time} · {tool}: {from} está agotada y ninguna otra suscripción tiene presupuesto",+ "event_refilled": "{time} · {tool}: {from} se ha recargado, el trabajo interrumpido continúa"}},"git": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.jsonindex 5e7ee90e8d..d80b92fd5e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json@@ -142,5 +142,38 @@"studio_done_watching": "Beobachte den Live-Feed, bis dein Paket erscheint — meist ein paar Minuten.","studio_done_share_heading": "Weitergeben","studio_done_share_note": "Das kann jetzt jeder ausführen — es löst deinen Eintrag aus der öffentlichen Registry auf."+ },+ "custom_connector": {+ "dialog_title": "Plugin hinzufügen",+ "tab_connector": "Connector-URL",+ "tab_folder": "Plugin-Ordner",+ "intro": "Verbinde Jarvis über die Adresse mit einem beliebigen MCP-Server. Wie er sich anmeldet, wird automatisch erkannt.",+ "name_label": "Name",+ "name_help": "Erscheint in deiner Plugin-Liste. Leer lassen, um den Namen des Servers zu verwenden.",+ "url_label": "MCP-Server-URL",+ "url_help": "Die HTTPS-Adresse, unter der der Server MCP-Anfragen annimmt, zum Beispiel https://mcp.example.com/mcp.",+ "advanced": "Erweiterte Einstellungen",+ "signin_label": "Anmeldung",+ "signin_auto": "Erkennen",+ "signin_oauth": "Browser",+ "signin_token": "Zugriffstoken",+ "signin_none": "Keine",+ "signin_auto_help": "Jarvis fragt den Server und wählt Browser-Anmeldung, Zugriffstoken oder keine Anmeldung.",+ "signin_oauth_help": "Öffnet die Anmeldeseite des Anbieters im Browser. Der Server muss neuen Apps die Selbstregistrierung erlauben.",+ "signin_token_help": "Du fügst direkt nach dem Hinzufügen einen API-Schlüssel oder Token ein. Er liegt im Anmeldedatenspeicher deines Systems.",+ "signin_none_help": "Für Server, die ohne Anmeldung antworten.",+ "header_label": "Header-Name",+ "header_help": "Leer lassen, um den Token als Bearer-Token im Authorization-Header zu senden.",+ "trust_note": "Füge nur Connectoren von Entwicklern hinzu, denen du vertraust. Jarvis kann nicht prüfen, welche Tools ein Server anbietet oder ob sie sich später ändern.",+ "checking": "Server wird geprüft…",+ "continue": "Weiter",+ "added": "{name} hinzugefügt",+ "menu_connector": "Eigener Connector (URL)",+ "menu_folder": "Plugin-Ordner hochladen",+ "remove": "Entfernen",+ "remove_title": "{name} entfernen?",+ "remove_body": "Die Anmeldung wird gelöscht und die Tools verschwinden aus allen Chats. Du kannst es jederzeit wieder hinzufügen.",+ "removed": "{name} entfernt",+ "fact_server": "Server"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.jsonindex 5d694311e9..2590cb20b3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json@@ -142,5 +142,38 @@"studio_done_watching": "Watching the live feed until your package appears — usually a few minutes.","studio_done_share_heading": "Share it","studio_done_share_note": "Anyone can run this now — it resolves your listing from the public registry."+ },+ "custom_connector": {+ "dialog_title": "Add a plugin",+ "tab_connector": "Connector URL",+ "tab_folder": "Plugin folder",+ "intro": "Connect Jarvis to any MCP server by its address. How it signs in is detected for you.",+ "name_label": "Name",+ "name_help": "Shown in your plugin list. Leave it empty to use the server's own name.",+ "url_label": "MCP server URL",+ "url_help": "The HTTPS address where the server accepts MCP requests, for example https://mcp.example.com/mcp.",+ "advanced": "Advanced settings",+ "signin_label": "Sign-in",+ "signin_auto": "Detect",+ "signin_oauth": "Browser",+ "signin_token": "Access token",+ "signin_none": "None",+ "signin_auto_help": "Jarvis asks the server and picks browser sign-in, an access token or no sign-in.",+ "signin_oauth_help": "Opens the provider's sign-in page in your browser. The server must let new apps register themselves.",+ "signin_token_help": "You paste an API key or token right after adding. It is kept in your system's credential store.",+ "signin_none_help": "For servers that answer without any sign-in.",+ "header_label": "Header name",+ "header_help": "Leave it empty to send the token as a Bearer token in Authorization.",+ "trust_note": "Only add connectors from developers you trust. Jarvis cannot check which tools a server offers or whether they change later.",+ "checking": "Checking the server…",+ "continue": "Continue",+ "added": "{name} added",+ "menu_connector": "Custom connector (URL)",+ "menu_folder": "Upload plugin folder",+ "remove": "Remove",+ "remove_title": "Remove {name}?",+ "remove_body": "Its sign-in is deleted and its tools leave every chat. You can add it again at any time.",+ "removed": "{name} removed",+ "fact_server": "Server"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.jsonindex ad86f21acf..21254a3da9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json@@ -142,5 +142,38 @@"studio_done_watching": "Vigilando el feed en vivo hasta que aparezca tu paquete; suelen ser unos minutos.","studio_done_share_heading": "Compártelo","studio_done_share_note": "Cualquiera puede ejecutar esto ahora: resuelve tu entrada desde el registro público."+ },+ "custom_connector": {+ "dialog_title": "Añadir un plugin",+ "tab_connector": "URL del conector",+ "tab_folder": "Carpeta del plugin",+ "intro": "Conecta Jarvis a cualquier servidor MCP mediante su dirección. El tipo de inicio de sesión se detecta automáticamente.",+ "name_label": "Nombre",+ "name_help": "Se muestra en tu lista de plugins. Déjalo vacío para usar el nombre del propio servidor.",+ "url_label": "URL del servidor MCP",+ "url_help": "La dirección HTTPS donde el servidor acepta solicitudes MCP, por ejemplo https://mcp.example.com/mcp.",+ "advanced": "Ajustes avanzados",+ "signin_label": "Inicio de sesión",+ "signin_auto": "Detectar",+ "signin_oauth": "Navegador",+ "signin_token": "Token de acceso",+ "signin_none": "Ninguno",+ "signin_auto_help": "Jarvis consulta al servidor y elige inicio de sesión en el navegador, token de acceso o ninguno.",+ "signin_oauth_help": "Abre la página de inicio de sesión del proveedor en tu navegador. El servidor debe permitir que las apps nuevas se registren solas.",+ "signin_token_help": "Pegas una clave API o un token justo después de añadirlo. Se guarda en el almacén de credenciales de tu sistema.",+ "signin_none_help": "Para servidores que responden sin iniciar sesión.",+ "header_label": "Nombre de la cabecera",+ "header_help": "Déjalo vacío para enviar el token como Bearer en Authorization.",+ "trust_note": "Añade solo conectores de desarrolladores de confianza. Jarvis no puede comprobar qué herramientas ofrece un servidor ni si cambian después.",+ "checking": "Comprobando el servidor…",+ "continue": "Continuar",+ "added": "{name} añadido",+ "menu_connector": "Conector propio (URL)",+ "menu_folder": "Subir carpeta del plugin",+ "remove": "Quitar",+ "remove_title": "¿Quitar {name}?",+ "remove_body": "Se borra su inicio de sesión y sus herramientas desaparecen de todos los chats. Puedes volver a añadirlo cuando quieras.",+ "removed": "{name} quitado",+ "fact_server": "Servidor"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/zh.jsonindex 9fd24be3a8..5018fc6346 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/zh.json@@ -142,5 +142,38 @@"studio_done_watching": "正在监视实时列表,直到你的包出现,通常需要几分钟。","studio_done_share_heading": "分享","studio_done_share_note": "现在任何人都可以运行它:它会从公共注册表中找到你的条目。"+ },+ "custom_connector": {+ "dialog_title": "添加插件",+ "tab_connector": "连接器 URL",+ "tab_folder": "插件文件夹",+ "intro": "通过地址把 Jarvis 连接到任意 MCP 服务器。登录方式会自动识别。",+ "name_label": "名称",+ "name_help": "显示在你的插件列表中。留空则使用服务器自己的名称。",+ "url_label": "MCP 服务器 URL",+ "url_help": "服务器接收 MCP 请求的 HTTPS 地址,例如 https://mcp.example.com/mcp。",+ "advanced": "高级设置",+ "signin_label": "登录",+ "signin_auto": "自动识别",+ "signin_oauth": "浏览器",+ "signin_token": "访问令牌",+ "signin_none": "无",+ "signin_auto_help": "Jarvis 会询问服务器,并选择浏览器登录、访问令牌或无需登录。",+ "signin_oauth_help": "在浏览器中打开服务商的登录页面。服务器必须允许新应用自行注册。",+ "signin_token_help": "添加后立即粘贴 API 密钥或令牌。它保存在系统的凭据存储中。",+ "signin_none_help": "适用于无需登录即可响应的服务器。",+ "header_label": "请求头名称",+ "header_help": "留空则以 Bearer 令牌的形式放在 Authorization 中发送。",+ "trust_note": "只添加你信任的开发者提供的连接器。Jarvis 无法检查服务器提供哪些工具,也无法检查它们以后是否会变化。",+ "checking": "正在检查服务器…",+ "continue": "继续",+ "added": "已添加 {name}",+ "menu_connector": "自定义连接器(URL)",+ "menu_folder": "上传插件文件夹",+ "remove": "移除",+ "remove_title": "移除 {name}?",+ "remove_body": "它的登录信息会被删除,它的工具会从所有聊天中消失。你随时可以重新添加。",+ "removed": "已移除 {name}",+ "fact_server": "服务器"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex d8db162707..d4339e34ad 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -887,6 +887,38 @@"shape": "Form","color": "Farbe","custom_color": "Eigene Farbe",+ "design": {+ "title": "Designs",+ "hint": "Farbverläufe mit Effekten statt einer Farbe. Wähle eins, bau dein eigenes oder importiere eins.",+ "create": "Eigenes Design bauen",+ "mine": "Meine Designs",+ "custom": "Eigenes Design",+ "delete": "{0} löschen",+ "import": "Importieren",+ "import_hint": "Design-Code, CSS-Verlauf oder ein paar Hex-Farben einfügen",+ "import_apply": "Übernehmen",+ "import_error": "Nichts zu importieren: kein Design-Code, Verlauf oder Farben gefunden.",+ "from_image": "Aus einem Bild",+ "image_error": "Das Bild konnte nicht gelesen werden.",+ "plain": "Einfache Farbe",+ "colors": "Farben",+ "add_color": "Farbe hinzufügen",+ "remove_color": "Letzte Farbe entfernen",+ "pattern": "Verlauf",+ "pattern_linear": "Linear",+ "pattern_radial": "Radial",+ "angle": "Richtung",+ "effect": "Effekt",+ "name": "Name des Designs",+ "name_placeholder": "Design benennen",+ "save": "Design speichern",+ "saved": "In „Meine Designs“ gespeichert. Jeder Agent kann es jetzt tragen.",+ "save_error": "Das Design konnte nicht gespeichert werden.",+ "copy_code": "Code kopieren",+ "copied": "Kopiert",+ "presets": { "galaxy": "Galaxie", "aurora": "Polarlicht", "holo": "Holo", "lava": "Lava", "neon": "Neon", "ocean": "Ozean", "sunset": "Sonnenuntergang", "gold": "Gold", "frost": "Frost" },+ "effects": { "none": "Keiner", "stars": "Sterne", "shimmer": "Schimmer", "flow": "Fließend", "glow": "Glühen", "sparkle": "Funkeln" }+ },"eyes": "Augen","dots": "Runde Augen","lines": "Strichaugen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 2acf633599..e558db5d53 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -887,6 +887,38 @@"shape": "Shape","color": "Colour","custom_color": "Custom colour",+ "design": {+ "title": "Designs",+ "hint": "Gradients with effects instead of one colour. Pick one, build your own or bring one in.",+ "create": "Build your own design",+ "mine": "My designs",+ "custom": "Own design",+ "delete": "Delete {0}",+ "import": "Import",+ "import_hint": "Paste a design code, a CSS gradient or a few hex colours",+ "import_apply": "Apply",+ "import_error": "Nothing to import: no design code, gradient or colours found.",+ "from_image": "From a picture",+ "image_error": "That picture could not be read.",+ "plain": "Plain colour",+ "colors": "Colours",+ "add_color": "Add colour",+ "remove_color": "Remove last colour",+ "pattern": "Layout",+ "pattern_linear": "Linear",+ "pattern_radial": "Radial",+ "angle": "Direction",+ "effect": "Effect",+ "name": "Design name",+ "name_placeholder": "Name this design",+ "save": "Save design",+ "saved": "Saved to My designs. Every agent can wear it now.",+ "save_error": "The design could not be saved.",+ "copy_code": "Copy code",+ "copied": "Copied",+ "presets": { "galaxy": "Galaxy", "aurora": "Aurora", "holo": "Holo", "lava": "Lava", "neon": "Neon", "ocean": "Ocean", "sunset": "Sunset", "gold": "Gold", "frost": "Frost" },+ "effects": { "none": "None", "stars": "Stars", "shimmer": "Shimmer", "flow": "Flowing", "glow": "Glow", "sparkle": "Sparkle" }+ },"eyes": "Eyes","dots": "Round eyes","lines": "Line eyes",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 6a87dd1b21..07696aa07a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -887,6 +887,38 @@"shape": "Forma","color": "Color","custom_color": "Color personalizado",+ "design": {+ "title": "Diseños",+ "hint": "Degradados con efectos en lugar de un solo color. Elige uno, crea el tuyo o importa uno.",+ "create": "Crear tu propio diseño",+ "mine": "Mis diseños",+ "custom": "Diseño propio",+ "delete": "Eliminar {0}",+ "import": "Importar",+ "import_hint": "Pega un código de diseño, un degradado CSS o algunos colores hex",+ "import_apply": "Aplicar",+ "import_error": "Nada que importar: no se encontró código de diseño, degradado ni colores.",+ "from_image": "Desde una imagen",+ "image_error": "No se pudo leer esa imagen.",+ "plain": "Color simple",+ "colors": "Colores",+ "add_color": "Añadir color",+ "remove_color": "Quitar el último color",+ "pattern": "Disposición",+ "pattern_linear": "Lineal",+ "pattern_radial": "Radial",+ "angle": "Dirección",+ "effect": "Efecto",+ "name": "Nombre del diseño",+ "name_placeholder": "Pon nombre al diseño",+ "save": "Guardar diseño",+ "saved": "Guardado en Mis diseños. Cualquier agente puede llevarlo ahora.",+ "save_error": "No se pudo guardar el diseño.",+ "copy_code": "Copiar código",+ "copied": "Copiado",+ "presets": { "galaxy": "Galaxia", "aurora": "Aurora", "holo": "Holo", "lava": "Lava", "neon": "Neón", "ocean": "Océano", "sunset": "Atardecer", "gold": "Oro", "frost": "Escarcha" },+ "effects": { "none": "Ninguno", "stars": "Estrellas", "shimmer": "Brillo", "flow": "Fluido", "glow": "Resplandor", "sparkle": "Destellos" }+ },"eyes": "Ojos","dots": "Ojos redondos","lines": "Ojos de línea",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.jsonindex 0ee8d4c6f3..e902301c87 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json@@ -887,6 +887,38 @@"shape": "形状","color": "颜色","custom_color": "自定义颜色",+ "design": {+ "title": "设计",+ "hint": "用带特效的渐变代替单一颜色。选一个、自己做一个,或导入一个。",+ "create": "自己做一个设计",+ "mine": "我的设计",+ "custom": "自定义设计",+ "delete": "删除 {0}",+ "import": "导入",+ "import_hint": "粘贴设计代码、CSS 渐变或几个十六进制颜色",+ "import_apply": "应用",+ "import_error": "没有可导入的内容:未找到设计代码、渐变或颜色。",+ "from_image": "从图片",+ "image_error": "无法读取这张图片。",+ "plain": "纯色",+ "colors": "颜色",+ "add_color": "添加颜色",+ "remove_color": "移除最后一个颜色",+ "pattern": "布局",+ "pattern_linear": "线性",+ "pattern_radial": "径向",+ "angle": "方向",+ "effect": "特效",+ "name": "设计名称",+ "name_placeholder": "给设计命名",+ "save": "保存设计",+ "saved": "已保存到“我的设计”。现在每个智能体都可以使用它。",+ "save_error": "无法保存这个设计。",+ "copy_code": "复制代码",+ "copied": "已复制",+ "presets": { "galaxy": "银河", "aurora": "极光", "holo": "全息", "lava": "熔岩", "neon": "霓虹", "ocean": "海洋", "sunset": "日落", "gold": "黄金", "frost": "冰霜" },+ "effects": { "none": "无", "stars": "星星", "shimmer": "流光", "flow": "流动", "glow": "发光", "sparkle": "闪烁" }+ },"eyes": "眼睛","dots": "圆眼","lines": "线条眼",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 06ab0592d4..04190257e9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -1,9 +1,56 @@{"custom_apis": {+ "connections_subtitle": "供 Jarvis 和代理使用的服务。",+ "add_title": "添加插件",+ "simple_hint": "只需输入名称和 API 密钥。",+ "edit_hint": "替换此连接的密钥。",+ "service_name": "服务名称",+ "name_example": "例如 ElevenLabs",+ "key_placeholder": "粘贴服务的 API 密钥",+ "private_key": "密钥保存在受保护的存储中。代理使用服务时不会收到密钥。",+ "automatic": "Jarvis 自动完成设置",+ "automatic_hint": "自动添加服务图标及其可用操作。你可以连接任意数量的服务。",+ "inheritance": "新功能自动提供给 Jarvis 和代理,并遵循现有权限。",+ "connect": "添加插件",+ "connecting": "正在设置…",+ "discovering": "正在查找服务及其可用操作。",+ "edit_key": "更新 API 密钥",+ "save_key": "保存密钥",+ "manage": "管理",+ "pause": "暂停连接",+ "resume": "恢复连接",+ "paused": "已暂停",+ "status_configured": "已设置",+ "status_verified": "已连接",+ "status_limited": "访问受限",+ "capabilities_count": "项功能",+ "capabilities_hint": "告诉 Jarvis 或代理你想做什么。它们会找到适合的操作并使用此连接。",+ "search_capabilities": "搜索功能…",+ "blocked": "已阻止",+ "partial_capabilities": "有 {count} 项操作无法自动导入。",+ "remove_confirm": "为 Jarvis 和代理移除此连接?",+ "errors": {+ "invalid_key": "服务未接受此 API 密钥,请检查。",+ "key_required": "请输入服务的 API 密钥。",+ "invalid_service_name": "请输入服务名称。",+ "service_not_found": "无法识别此服务,请尝试完整名称。",+ "ambiguous_service": "多个服务符合此名称,请选择所需服务。",+ "documentation_not_found": "尚未找到此服务可用的公开 API 描述。",+ "documentation_unavailable": "无法加载服务文档,请重试。",+ "discovery_timeout": "查找服务超时,请重试。",+ "unsafe_documentation": "无法验证文档地址。",+ "documentation_too_large": "此 API 描述太大,无法自动导入。",+ "service_address_mismatch": "无法可靠地匹配服务的 API 地址,密钥未发送。",+ "connection_name_changed": "请添加新连接以更换服务。",+ "storage_unavailable": "无法保存连接,请重试。",+ "not_ready": "Jarvis 正在启动,请稍后重试。",+ "unsupported_api": "此服务暂时无法使用单个 API 密钥自动设置。",+ "invalid_connection": "此连接已不可用。"+ },"download": "下载结果",- "title": "自定义 API",+ "title": "你的插件","subtitle": "连接自己的服务,让 Jarvis 和代理使用这些操作。",- "add": "添加 API",+ "add": "添加插件","elevenlabs": "ElevenLabs 模板","import": "导入定义","export": "导出",@@ -227,8 +274,11 @@"update_checking": "正在检查…","update_unmanaged": "此副本不是通过安装程序设置的,因此需要在应用外部更新。","detach": "独立窗口",+ "return_to_main": "返回主窗口",+ "return_to_main_hint": "关闭此窗口并将此区域移回主窗口","detach_hint": "在独立窗口中打开此视图","detach_failed": "无法打开独立窗口",+ "reattach_failed": "无法将此视图移回主窗口","detached_title": "此视图已在独立窗口中打开","detached_body": "你可以继续在那里工作,或将它移回此窗口。","detach_focus": "显示窗口",@@ -6743,6 +6793,26 @@"weekly_scoped": "每周限额 · {scope}","monthly": "每月限额","other": "其他限额"+ },+ "switch": {+ "use": "切换",+ "use_tip": "让 {tool} 使用此订阅:新终端从这里启动,所有正在运行的智能体都会迁移过来并继续各自的对话。",+ "switching": "正在切换…",+ "done": "现在使用 {label}。",+ "moved": "{n} 个智能体已连同对话一起迁移。",+ "queued": "{n} 个正在工作的智能体会在当前步骤结束后跟进。",+ "failed": "切换未成功({error})。",+ "empty_until": "已用完,{when} 恢复",+ "auto": "自动切换",+ "auto_tip": "当某个订阅额度将尽或达到上限时,正在运行的智能体会迁移到剩余额度最多的订阅并继续工作。",+ "threshold": "切换时机",+ "at_left": "剩余 {left}% 时",+ "at_limit": "仅在达到上限时",+ "event_manual": "{time} · {tool} 已切换到 {to}",+ "event_limit": "{time} · {tool}:{from} 已达上限,工作在 {to} 上继续",+ "event_threshold": "{time} · {tool}:{from} 即将用完,工作已迁移到 {to}",+ "event_no_seat": "{time} · {tool}:{from} 已用完,且没有其他订阅仍有额度",+ "event_refilled": "{time} · {tool}:{from} 额度已恢复,中断的工作已继续"}},"git": {diff --git a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.tsindex 1175fc5f0b..e2203c7dd5 100644--- a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts@@ -302,3 +302,67 @@ export function groupFor(): AccountPlatformGroup | undefined {return data?.platforms?.find((group) => group.platform === platform);}++/** What one switch did: where the CLI now runs and how its agents followed. */+export interface SeatSwitchResult {+ active_account: string;+ active_label: string;+ /** Agents restarted on the new seat now (or stopped panes re-pointed). */+ moved: number;+ /** Working agents that move the moment their current turn ends. */+ queued: number;+ message: string;+}++/**+ * Make one subscription the active seat AND move every running agent of that+ * CLI onto it, each continuing its own conversation.+ */+export function switchSeat(platform: AccountPlatform, accountId: string): Promise<SeatSwitchResult> {+ return send<SeatSwitchResult>("/api/agentic-ide/accounts/switch", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ agent: platform, account_id: accountId }),+ });+}++/** One switch as the backend recorded it. */+export interface SeatSwitchEvent {+ at: number;+ platform: string;+ /** "manual" | "limit" | "threshold" | "no_seat" */+ reason: string;+ to_account: string | null;+ to_label: string;+ from_label: string;+ moved: number;+ queued: number;+}++/** Whether work follows a seat that runs out, and what happened lately. */+export interface AutoSwitchState {+ enabled: boolean;+ /** Spent share of a plan limit at which its work moves on. */+ at_percent: number;+ watching: boolean;+ /** Seats out of rotation, until their epoch-second refill. */+ exhausted: { account_id: string; until: number }[];+ /** Newest first. */+ events: SeatSwitchEvent[];+}++export async function fetchAutoSwitch(): Promise<AutoSwitchState | null> {+ const res = await fetch("/api/agentic-ide/accounts/auto-switch", { cache: "no-store" });+ // An older backend has no such route: the panel then simply has no bar.+ if (res.status === 404) return null;+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as AutoSwitchState;+}++export function updateAutoSwitch(change: { enabled?: boolean; at_percent?: number }): Promise<AutoSwitchState> {+ return send<AutoSwitchState>("/api/agentic-ide/accounts/auto-switch", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(change),+ });+}diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex cbd20f2932..a00e811910 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -14,6 +14,9 @@ export interface CuratedModel {efforts?: string[];/** A short note for the picker's hint ("retires 2026-08-31"). */note?: string;+ /** Catalog capabilities; absent/null means unknown, not unsupported. */+ tools?: boolean | null;+ vision?: boolean | null;}export interface PermissionModeOption {@@ -351,6 +354,8 @@ export interface LiveModel {id: string;label?: string;name?: string;+ tools?: boolean | null;+ vision?: boolean | null;}/** The provider's live model list (brain catalog route); [] when the route has none. */diff --git a/jarvis/ui/web/frontend/src/lib/computersApi.ts b/jarvis/ui/web/frontend/src/lib/computersApi.tsindex 8e0065db4e..5cd34fd934 100644--- a/jarvis/ui/web/frontend/src/lib/computersApi.ts+++ b/jarvis/ui/web/frontend/src/lib/computersApi.ts@@ -45,6 +45,22 @@ export interface ComputerHealth {mem_used_pct: number | null;disk_used_pct: number | null;uptime_s: number | null;+ /** The log correlation id of a failed check, for a bug report. */+ trace_id?: string | null;+}++/** Where an address came from: typed in, Tailscale, or this PC's ~/.ssh/config. */+export type RouteSource = "manual" | "tailscale" | "ssh_config";++/** One address the machine answers on; a computer tries them in list order. */+export interface ComputerRoute {+ id: string;+ host: string;+ port: number;+ label: string | null;+ source: RouteSource;+ /** When a connection last got through on this address (epoch seconds). */+ last_ok_at: number | null;}export interface Computer {@@ -66,10 +82,64 @@ export interface Computer {created_at: number;facts: ComputerFacts | null;health: ComputerHealth;+ // The fields below are optional because an older backend does not send them;+ // every reader falls back to the old behaviour (on, one address, normal share).+ /** Switched off: kept, but nothing connects to it and no picker offers it. */+ enabled?: boolean;+ /** Every address, preferred first; `host`/`port` mirror the active one. */+ routes?: ComputerRoute[];+ active_route_id?: string | null;+ /** "Automatic" share: 0 never, 1 less, 2 normal, 3 more. */+ placement_weight?: number;+ /** When this PC's GitHub login was shared with the agents here; null = not shared. */+ github_shared_at?: number | null;/** A background job (VM creation) is still running for this record. */busy: boolean;}+/** A server this PC's own ssh knows (~/.ssh/config or known_hosts). */+export interface SshConfigHost {+ alias: string;+ host: string;+ port: number;+ username: string | null;+ source: "ssh_config" | "known_hosts";+ has_identity_file: boolean;+ /** Needs a jump host; the app cannot connect to it directly. */+ needs_proxy: boolean;+ /** The computer this address is already connected as, if any. */+ added_as: string | null;+}++export interface TailscalePeer {+ host_name: string;+ dns_name: string;+ ips: string[];+ online: boolean;+ os: string;+ address: string;+}++export interface RouteSuggestion {+ host: string;+ port: number;+ label: string;+ online: boolean;+}++export interface TailscaleStatus {+ available: boolean;+ peers: TailscalePeer[];+ /** Per computer id: Tailscale addresses it could add. */+ suggestions: Record<string, RouteSuggestion[]>;+}++export interface PlacementSettings {+ enabled: boolean;+ /** This PC's share, 0-3 like a computer's. */+ local_weight: number;+}+export interface Identity {public_key: string;fingerprint: string;@@ -137,6 +207,8 @@ export interface AddServerInput {auth: LoginMode;password?: string;keep_password?: boolean;+ /** A Host alias from this PC's ~/.ssh/config: its IdentityFile keys are offered too. */+ ssh_alias?: string;/** The user's own private key (OpenSSH/PEM text), for ``auth: "private_key"``. */private_key?: string;passphrase?: string;@@ -249,6 +321,30 @@ const post = (body?: unknown): RequestInit => ({body: body === undefined ? undefined : JSON.stringify(body),});+/** Independent HTTPS Jarvis environments; these are not SSH execution targets. */+export interface PairedServer {+ id: string;+ url: string;+ name: string;+ platform: string;+ created_at: number;+ checked_at: number;+ online: boolean;+}++export interface PairedClient { id: string; name: string; created_at: number }++export const pairedServersApi = {+ list: () => request<{ servers: PairedServer[] }>("/pairing/servers").then((r) => r.servers),+ add: (host: string, code: string) => request<PairedServer>("/pairing/servers", post({ host, code })),+ check: (id: string) => request<PairedServer>(`/pairing/servers/${encodeURIComponent(id)}/check`, post()),+ open: (id: string) => request<{ url: string }>(`/pairing/servers/${encodeURIComponent(id)}/open`, post()),+ remove: (id: string) => request<{ removed: boolean }>(`/pairing/servers/${encodeURIComponent(id)}`, { method: "DELETE" }),+ code: () => request<{ code: string; expires_at: number }>("/pairing/code", post()),+ clients: () => request<{ clients: PairedClient[] }>("/pairing/clients").then((r) => r.clients),+ revoke: (id: string) => request<{ removed: boolean }>(`/pairing/clients/${encodeURIComponent(id)}`, { method: "DELETE" }),+};+export const computersApi = {list: () => request<{ computers: Computer[] }>("").then((r) => r.computers),providers: () => request<{ providers: ProviderInfo[] }>("/providers").then((r) => r.providers),@@ -262,7 +358,10 @@ export const computersApi = {add: (input: AddServerInput) => request<Computer>("", post(input)),checkAll: () => request<{ computers: Computer[] }>("/check-all", post()).then((r) => r.computers),check: (id: string) => request<Computer>(`/${encodeURIComponent(id)}/check`, post()),- update: (id: string, patch: Partial<Pick<Computer, "name" | "host" | "port" | "username">>) =>+ update: (+ id: string,+ patch: Partial<Pick<Computer, "name" | "host" | "port" | "username" | "enabled" | "placement_weight">>,+ ) =>request<Computer>(`/${encodeURIComponent(id)}`, {method: "PATCH",body: JSON.stringify(patch),@@ -297,6 +396,27 @@ export const computersApi = {) => request<Computer>(`/cloud/${provider}/import`, post(body)),localStatus: () => request<LocalStatus>("/local"),createLocalVm: (input: LocalVmInput) => request<Computer>("/local", post(input)),+ sshHosts: () => request<{ hosts: SshConfigHost[] }>("/ssh-hosts").then((r) => r.hosts),+ tailscale: () => request<TailscaleStatus>("/tailscale"),+ addRoute: (id: string, route: { host: string; port: number; label?: string; source?: RouteSource }) =>+ request<Computer>(`/${encodeURIComponent(id)}/routes`, post(route)),+ orderRoutes: (id: string, routeIds: string[]) =>+ request<Computer>(`/${encodeURIComponent(id)}/routes/order`, {+ method: "PUT",+ body: JSON.stringify({ route_ids: routeIds }),+ }),+ removeRoute: (id: string, routeId: string) =>+ request<Computer>(`/${encodeURIComponent(id)}/routes/${encodeURIComponent(routeId)}`, {+ method: "DELETE",+ }),+ placement: () => request<PlacementSettings>("/placement"),+ setPlacement: (patch: Partial<PlacementSettings>) =>+ request<PlacementSettings>("/placement", { method: "PUT", body: JSON.stringify(patch) }),+ pickPlacement: () =>+ request<{ computer_id: string | null }>("/placement/pick", post()).then((r) => r.computer_id),+ shareGithub: (id: string) => request<Computer>(`/${encodeURIComponent(id)}/github`, post()),+ unshareGithub: (id: string) =>+ request<Computer>(`/${encodeURIComponent(id)}/github`, { method: "DELETE" }),};// ---------------------------------------------------------------------------diff --git a/jarvis/ui/web/frontend/src/lib/customApi.ts b/jarvis/ui/web/frontend/src/lib/customApi.tsindex d1773e164c..17eb9a7bab 100644--- a/jarvis/ui/web/frontend/src/lib/customApi.ts+++ b/jarvis/ui/web/frontend/src/lib/customApi.ts@@ -1,17 +1,22 @@export interface ApiParameter {name: string;- location: "path" | "query";- type: "string" | "integer" | "number" | "boolean";+ location: "path" | "query" | "header";+ type: "string" | "integer" | "number" | "boolean" | "array" | "object";+ value_schema?: Record<string, unknown> | null;required: boolean;description: string;}export interface ApiAction {id: string;description: string;- method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";path: string;parameters: ApiParameter[];body_schema: Record<string, unknown> | null;+ body_required?: boolean;+ body_encoding?: "json" | "multipart" | "form" | "binary";+ file_fields?: string[];+ content_type?: string;risk_tier: "monitor" | "ask" | "block";response: "auto" | "json" | "text" | "file";}@@ -20,7 +25,7 @@ export interface ApiDefinition {name: string;description: string;base_url: string;- auth: { mode: "none" | "bearer" | "header"; header_name: string };+ auth: { mode: "none" | "bearer" | "header" | "query"; header_name: string };enabled: boolean;actions: ApiAction[];}@@ -29,10 +34,30 @@ export interface ApiStatus {has_credential: boolean;tools_ready: boolean;}+export interface ApiConnection {+ id: string;+ name: string;+ website: string;+ brand_id: string;+ logo_data: string;+ categories: string[];+ action_count: number;+ omitted_operations: number;+ enabled: boolean;+ has_credential: boolean;+ tools_ready: boolean;+ status: "configured" | "verified" | "limited";+}+export class ApiConnectionError extends Error {+ constructor(public code: string, public suggestions: string[] = []) { super(code); }+}export async function customApiRequest<T>(path = "", init?: RequestInit): Promise<T> {const response = await fetch(`/api/custom-apis${path}`, init);const data = await response.json();- if (!response.ok) throw new Error(typeof data.detail === "string" ? data.detail : `HTTP ${response.status}`);+ if (!response.ok) {+ if (data.detail?.code) throw new ApiConnectionError(data.detail.code, data.detail.suggestions ?? []);+ throw new Error(typeof data.detail === "string" ? data.detail : `HTTP ${response.status}`);+ }return data as T;}export function newApiDefinition(): ApiDefinition {diff --git a/jarvis/ui/web/frontend/src/lib/customConnector.ts b/jarvis/ui/web/frontend/src/lib/customConnector.tsnew file mode 100644index 0000000000..6804be1268--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/customConnector.ts@@ -0,0 +1,79 @@+/**+ * Talking to `/api/marketplace/connectors` — a remote MCP server added by URL.+ *+ * One call: the backend asks the server how it signs in, and only writes the+ * catalog entry when the answer is usable. The reply carries that entry, so+ * the caller can start the matching connect flow straight away.+ */++export type ConnectorSignIn = "auto" | "oauth" | "token" | "none";++export type CustomConnectorRequest = {+ name: string;+ url: string;+ auth: ConnectorSignIn;+ /** Header an access token travels in; empty means Authorization (Bearer). */+ headerName?: string;+};++export type CustomConnectorResult = {+ ok: boolean;+ plugin: { id: string; display_name: string; source: string };+ detected: {+ auth: Exclude<ConnectorSignIn, "auto">;+ transport: "http" | "sse";+ server_name: string | null;+ };+};++export async function addCustomConnector(+ request: CustomConnectorRequest,+): Promise<CustomConnectorResult> {+ const res = await fetch("/api/marketplace/connectors", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: request.name.trim(),+ url: request.url.trim(),+ auth: request.auth,+ header_name: request.headerName?.trim() || null,+ }),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const detail = (body as { detail?: unknown }).detail;+ // FastAPI validation errors arrive as a list; show the first message.+ if (Array.isArray(detail) && detail[0]?.msg) throw new Error(String(detail[0].msg));+ throw new Error(typeof detail === "string" ? detail : `HTTP ${res.status}`);+ }+ return res.json();+}++/** Removes a plugin the owner added (connector, upload or community install). */+export async function removeAddedPlugin(pluginId: string): Promise<void> {+ const res = await fetch(`/api/marketplace/community/plugins/${encodeURIComponent(pluginId)}`, {+ method: "DELETE",+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const detail = (body as { detail?: unknown }).detail;+ throw new Error(typeof detail === "string" ? detail : `HTTP ${res.status}`);+ }+}++/**+ * A plugin another surface wants opened next time the Plugins view mounts —+ * the composer's Add menu uses it so "Connect" lands on that plugin's page+ * instead of the top of a long list.+ */+let pendingFocus: string | null = null;++export function requestPluginFocus(pluginId: string): void {+ pendingFocus = pluginId;+}++export function takePluginFocus(): string | null {+ const id = pendingFocus;+ pendingFocus = null;+ return id;+}diff --git a/jarvis/ui/web/frontend/src/lib/sectionUrl.test.ts b/jarvis/ui/web/frontend/src/lib/sectionUrl.test.tsindex 65d224c827..37564874cf 100644--- a/jarvis/ui/web/frontend/src/lib/sectionUrl.test.ts+++ b/jarvis/ui/web/frontend/src/lib/sectionUrl.test.ts@@ -25,6 +25,16 @@ describe("hrefWithSection", () => {// any of them would trade one lost place for another.expect(hrefWithSection(`${BASE}?solo=1&doc=agent-contract#naming`, "docs"),- ).toBe("/?solo=1&doc=agent-contract&view=docs#naming");+ ).toBe("/?solo=1&doc=agent-contract&window=docs&view=docs#naming");+ });++ it("keeps the window owner through tab changes and reloads", () => {+ const next = hrefWithSection(`${BASE}?view=profile&solo=1&window=settings`, "apikeys");+ expect(next).toBe("/?view=apikeys&solo=1&window=settings");+ expect(hrefWithSection(new URL(next!, BASE).href, "shortcuts")).toBe("/?view=shortcuts&solo=1&window=settings");+ });++ it("upgrades an older solo URL before changing its tab", () => {+ expect(hrefWithSection(`${BASE}?view=profile&solo=1`, "apikeys")).toBe("/?view=apikeys&solo=1&window=profile");});});diff --git a/jarvis/ui/web/frontend/src/lib/sectionUrl.ts b/jarvis/ui/web/frontend/src/lib/sectionUrl.tsindex 6c5d45d34f..e1ea6986ea 100644--- a/jarvis/ui/web/frontend/src/lib/sectionUrl.ts+++ b/jarvis/ui/web/frontend/src/lib/sectionUrl.ts@@ -34,6 +34,11 @@ export const SECTION_PARAM = "view";*/export function hrefWithSection(href: string, section: string): string | null {const url = new URL(href);+ if (url.searchParams.get("solo") === "1" && !url.searchParams.has("window")) {+ url.searchParams.set("window", url.searchParams.get(SECTION_PARAM) || section);+ url.searchParams.set(SECTION_PARAM, section);+ return `${url.pathname}${url.search}${url.hash}`;+ }if (url.searchParams.get(SECTION_PARAM) === section) return null;url.searchParams.set(SECTION_PARAM, section);return `${url.pathname}${url.search}${url.hash}`;diff --git a/jarvis/ui/web/frontend/src/lib/sectionWindows.ts b/jarvis/ui/web/frontend/src/lib/sectionWindows.tsnew file mode 100644index 0000000000..1d675bdb5d--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/sectionWindows.ts@@ -0,0 +1,27 @@+import type { SectionId } from "@/store/events";+import { SETTINGS_HUB_IDS } from "@/components/layout/navGroups";++/** A tab changes the content, never the identity of its native window. */+export function sectionWindow(section: SectionId): SectionId {+ if (SETTINGS_HUB_IDS.includes(section)) return "settings";+ if (["agentic-ide", "agentic-ide-classic", "chat-workspace"].includes(section)) return "agentic-ide";+ if (["plugins", "mcps", "skills"].includes(section)) return "plugins";+ if (section === "cli-test-hub") return "clis";+ return section;+}++export const DETACHABLE_SECTIONS: readonly SectionId[] = [+ "agentic-ide", "agents", "settings", "plugins", "clis", "docs", "memory",+ "board", "sessions", "marketplace", "visualization",+];++export function detachedWindowFor(section: SectionId, detached: readonly SectionId[]): SectionId | undefined {+ const owner = sectionWindow(section);+ return detached.find((view) => sectionWindow(view) === owner);+}++/** The URL keeps this identity when a Settings/Plugins tab changes or reloads. */+export function windowIdentity(search: string, fallback: SectionId): string {+ const params = new URLSearchParams(search);+ return params.get("window") || params.get("view") || sectionWindow(fallback);+}diff --git a/jarvis/ui/web/frontend/src/views/AddConnectorDialog.test.tsx b/jarvis/ui/web/frontend/src/views/AddConnectorDialog.test.tsxnew file mode 100644index 0000000000..430ea69eff--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AddConnectorDialog.test.tsx@@ -0,0 +1,149 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import { loadLocaleChunk, setUiLanguage } from "@/i18n";+import { browseToolRows, type ToolChoice } from "@/components/agentchat/toolChoices";+import { AddConnectorDialog, AddPluginTabs } from "@/views/AddConnectorDialog";++/**+ * Adding a connector is a name and an address. The dialog sends exactly+ * those (plus the advanced overrides when the owner set them), shows the+ * server's own reason when the backend refuses, and hands the created entry+ * to the caller so the connect step can start at once.+ */++const ADDED = {+ ok: true,+ plugin: { id: "acme", display_name: "Acme", source: "local" },+ detected: { auth: "oauth", transport: "http", server_name: "Acme MCP" },+};++function respond(body: unknown, status = 200): Response {+ return { ok: status < 400, status, json: async () => body } as Response;+}++let fetchMock: ReturnType<typeof vi.fn>;++function stubFetch(body: unknown, status = 200) {+ fetchMock = vi.fn(async () => respond(body, status));+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+}++function sentBody(): Record<string, unknown> {+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ return JSON.parse(String(init.body));+}++beforeAll(async () => {+ setUiLanguage("en");+ await loadLocaleChunk("marketplace");+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("AddConnectorDialog", () => {+ it("needs only an address and sends name, address and automatic sign-in", async () => {+ stubFetch(ADDED);+ const onAdded = vi.fn();+ render(<AddConnectorDialog open onClose={() => {}} onAdded={onAdded} />);++ const continueButton = screen.getByTestId("connector-continue") as HTMLButtonElement;+ expect(continueButton.disabled).toBe(true);++ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Acme" } });+ fireEvent.change(screen.getByTestId("connector-url"), {+ target: { value: "https://mcp.acme.example/mcp" },+ });+ expect(continueButton.disabled).toBe(false);+ fireEvent.click(continueButton);++ await waitFor(() => expect(onAdded).toHaveBeenCalledWith(ADDED));+ expect(fetchMock.mock.calls[0][0]).toBe("/api/marketplace/connectors");+ expect(sentBody()).toEqual({+ name: "Acme",+ url: "https://mcp.acme.example/mcp",+ auth: "auto",+ header_name: null,+ });+ });++ it("submits on Enter in the address field", async () => {+ stubFetch(ADDED);+ const onAdded = vi.fn();+ render(<AddConnectorDialog open onClose={() => {}} onAdded={onAdded} />);++ const url = screen.getByTestId("connector-url");+ fireEvent.change(url, { target: { value: "mcp.acme.example/mcp" } });+ fireEvent.keyDown(url, { key: "Enter" });++ await waitFor(() => expect(onAdded).toHaveBeenCalled());+ });++ it("sends the access-token override with its header name", async () => {+ stubFetch(ADDED);+ render(<AddConnectorDialog open onClose={() => {}} onAdded={() => {}} />);++ fireEvent.change(screen.getByTestId("connector-url"), {+ target: { value: "https://mcp.acme.example/mcp" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Advanced settings/ }));+ fireEvent.click(screen.getByRole("radio", { name: "Access token" }));+ fireEvent.change(screen.getByLabelText("Header name"), { target: { value: "X-API-Key" } });+ fireEvent.click(screen.getByTestId("connector-continue"));++ await waitFor(() => expect(fetchMock).toHaveBeenCalled());+ expect(sentBody()).toMatchObject({ auth: "token", header_name: "X-API-Key" });+ });++ it("shows the server's own reason when the connector is refused", async () => {+ stubFetch({ detail: "The server answered HTTP 500. Check that this is the address." }, 422);+ const onAdded = vi.fn();+ render(<AddConnectorDialog open onClose={() => {}} onAdded={onAdded} />);++ fireEvent.change(screen.getByTestId("connector-url"), {+ target: { value: "https://mcp.acme.example/mcp" },+ });+ fireEvent.click(screen.getByTestId("connector-continue"));++ expect((await screen.findByRole("alert")).textContent).toContain("HTTP 500");+ expect(onAdded).not.toHaveBeenCalled();+ });++ it("switches to the folder upload from the shared tabs", () => {+ const onChange = vi.fn();+ render(<AddPluginTabs mode="connector" onChange={onChange} />);++ expect(screen.getByTestId("add-plugin-tab-connector").getAttribute("aria-selected")).toBe("true");+ fireEvent.click(screen.getByTestId("add-plugin-tab-folder"));+ expect(onChange).toHaveBeenCalledWith("folder");+ });+});++describe("Add menu rows for plugins the owner added", () => {+ const row = (over: Partial<ToolChoice>): ToolChoice => ({+ id: "plugin:x",+ label: "X",+ description: "",+ category: "plugins",+ group: "X",+ brand: "x",+ available: false,+ tool_names: [],+ skill: "",+ ...over,+ });++ it("lists a connector the owner added before it is connected", () => {+ const added = row({ id: "plugin:acme", user_added: true });+ const shipped = row({ id: "plugin:notion" });++ expect(browseToolRows([added, shipped]).map((r) => r.id)).toEqual(["plugin:acme"]);+ expect(browseToolRows([added, shipped], "no").map((r) => r.id)).toEqual([+ "plugin:acme",+ "plugin:notion",+ ]);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/AddConnectorDialog.tsx b/jarvis/ui/web/frontend/src/views/AddConnectorDialog.tsxnew file mode 100644index 0000000000..adf9606381--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/AddConnectorDialog.tsx@@ -0,0 +1,357 @@+import { useEffect, useId, useRef, useState, type ReactNode } from "react";+import { AlertTriangle, ChevronRight, FolderUp, Link2, Loader2, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { useLocaleChunk, useT } from "@/i18n";+import {+ addCustomConnector,+ type ConnectorSignIn,+ type CustomConnectorResult,+} from "@/lib/customConnector";+import { cn } from "@/lib/utils";++/** The two ways into the plugin list: a server address, or a whole folder. */+export type AddPluginMode = "connector" | "folder";++/**+ * Switches the add dialog between "Connector URL" and "Plugin folder".+ *+ * Both dialogs render this same row under the same title at the same size,+ * so switching reads as one dialog changing tabs rather than one window+ * closing and another opening.+ */+export function AddPluginTabs({+ mode,+ onChange,+}: {+ mode: AddPluginMode;+ onChange: (mode: AddPluginMode) => void;+}) {+ const t = useT();+ useLocaleChunk("marketplace");+ const tabs: { id: AddPluginMode; label: string; icon: ReactNode }[] = [+ { id: "connector", label: t("custom_connector.tab_connector"), icon: <Link2 className="h-4 w-4" /> },+ { id: "folder", label: t("custom_connector.tab_folder"), icon: <FolderUp className="h-4 w-4" /> },+ ];+ return (+ <div+ role="tablist"+ aria-label={t("custom_connector.dialog_title")}+ className="flex items-center gap-6 border-b border-border"+ >+ {tabs.map((tab) => {+ const active = tab.id === mode;+ return (+ <button+ key={tab.id}+ type="button"+ role="tab"+ aria-selected={active}+ data-testid={`add-plugin-tab-${tab.id}`}+ onClick={() => onChange(tab.id)}+ className={cn(+ "relative -mb-px inline-flex h-10 items-center gap-2 border-b-2 text-sm font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ active+ ? "border-accent text-foreground-strong"+ : "border-transparent text-muted-foreground hover:text-foreground",+ )}+ >+ {tab.icon}+ {tab.label}+ </button>+ );+ })}+ </div>+ );+}++const SIGN_IN_CHOICES: ConnectorSignIn[] = ["auto", "oauth", "token", "none"];++const INPUT =+ "w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-sm text-foreground " ++ "placeholder:text-muted-foreground focus:border-border-strong focus:outline-none " ++ "focus:ring-2 focus:ring-border-strong/30 disabled:opacity-60";++/**+ * Add a custom connector: a name, the server's MCP address, done.+ *+ * Everything else is answered by the server itself. Continue sends one+ * request; the backend probes the address, works out whether it signs in+ * through the browser, wants an access token or needs nothing, and writes the+ * plugin only when that answer is usable. The caller then runs the matching+ * connect step, so the next thing the owner sees is the provider's sign-in+ * page, the token field, or a connected card.+ *+ * The advanced settings exist for the servers detection cannot read: one+ * that wants a key in a header of its own, or one that answers without+ * credentials but should still be treated as protected.+ */+export function AddConnectorDialog({+ open,+ onClose,+ onAdded,+ tabs,+}: {+ open: boolean;+ onClose: () => void;+ onAdded: (result: CustomConnectorResult) => void;+ /** The connector/folder switch, rendered under the title. */+ tabs?: ReactNode;+}) {+ const t = useT();+ useLocaleChunk("marketplace");+ const nameId = useId();+ const urlId = useId();+ const headerId = useId();+ const nameRef = useRef<HTMLInputElement>(null);+ const [name, setName] = useState("");+ const [url, setUrl] = useState("");+ const [advanced, setAdvanced] = useState(false);+ const [signIn, setSignIn] = useState<ConnectorSignIn>("auto");+ const [headerName, setHeaderName] = useState("");+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!open) return;+ setError(null);+ setPending(false);+ nameRef.current?.focus();+ }, [open]);++ useEffect(() => {+ if (!open) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape" && !pending) onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [open, pending, onClose]);++ if (!open) return null;++ const canSubmit = url.trim().length > 0 && !pending;++ const submit = async () => {+ if (!canSubmit) return;+ setPending(true);+ setError(null);+ try {+ const result = await addCustomConnector({+ name,+ url,+ auth: signIn,+ headerName: signIn === "token" || signIn === "auto" ? headerName : "",+ });+ setName("");+ setUrl("");+ setHeaderName("");+ setSignIn("auto");+ setAdvanced(false);+ onAdded(result);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setPending(false);+ }+ };++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/60 p-6"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget && !pending) onClose();+ }}+ >+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby={`${nameId}-title`}+ data-testid="add-connector-dialog"+ className="flex max-h-full w-[640px] max-w-full flex-col overflow-hidden rounded-lg border border-border bg-card shadow-float"+ >+ <header className={cn("px-6 pt-5", tabs ? "pb-0" : "border-b border-border pb-4")}>+ <div className="flex items-start justify-between gap-4">+ <h3 id={`${nameId}-title`} className="text-lg font-semibold tracking-tight text-foreground-strong">+ {tabs ? t("custom_connector.dialog_title") : t("custom_connector.tab_connector")}+ </h3>+ <Button+ size="sm"+ variant="ghost"+ onClick={onClose}+ disabled={pending}+ aria-label={t("common.cancel")}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ {tabs && <div className="mt-3">{tabs}</div>}+ </header>++ <ScrollArea className="min-h-0 flex-1">+ <form+ className="flex flex-col gap-5 px-6 py-5"+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ onKeyDown={(event) => {+ // Enter in any field submits; the visible button sits in the footer.+ if (event.key === "Enter" && event.target instanceof HTMLInputElement) {+ event.preventDefault();+ void submit();+ }+ }}+ >+ <p className="text-sm text-muted-foreground">{t("custom_connector.intro")}</p>++ <div>+ <label htmlFor={nameId} className="mb-1.5 block text-xs font-medium text-muted-foreground">+ {t("custom_connector.name_label")}+ </label>+ <input+ ref={nameRef}+ id={nameId}+ type="text"+ value={name}+ maxLength={80}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setName(event.target.value)}+ placeholder={t("custom_connector.name_label")}+ disabled={pending}+ className={INPUT}+ />+ <p className="mt-1.5 text-xs text-muted-foreground">{t("custom_connector.name_help")}</p>+ </div>++ <div>+ <label htmlFor={urlId} className="mb-1.5 block text-xs font-medium text-muted-foreground">+ {t("custom_connector.url_label")}+ </label>+ <input+ id={urlId}+ type="text"+ inputMode="url"+ value={url}+ maxLength={2048}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setUrl(event.target.value)}+ placeholder="https://mcp.example.com/mcp"+ disabled={pending}+ data-testid="connector-url"+ className={cn(INPUT, "font-mono text-[13px]")}+ />+ <p className="mt-1.5 text-xs text-muted-foreground">{t("custom_connector.url_help")}</p>+ </div>++ <div>+ <button+ type="button"+ onClick={() => setAdvanced((value) => !value)}+ aria-expanded={advanced}+ className="inline-flex items-center gap-1.5 rounded-md text-sm font-medium text-foreground transition-colors hover:text-foreground-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ChevronRight+ className={cn("h-4 w-4 text-muted-foreground transition-transform", advanced && "rotate-90")}+ />+ {t("custom_connector.advanced")}+ </button>+ {advanced && (+ <div className="mt-3 flex flex-col gap-4 rounded-xl border border-border bg-secondary/40 p-4">+ <div>+ <p className="mb-2 text-xs font-medium text-muted-foreground">+ {t("custom_connector.signin_label")}+ </p>+ <div+ role="radiogroup"+ aria-label={t("custom_connector.signin_label")}+ className="grid grid-cols-2 gap-1 rounded-lg border border-border bg-background p-1 sm:grid-cols-4"+ >+ {SIGN_IN_CHOICES.map((choice) => (+ <button+ key={choice}+ type="button"+ role="radio"+ aria-checked={signIn === choice}+ onClick={() => setSignIn(choice)}+ disabled={pending}+ className={cn(+ "rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ signIn === choice+ ? "bg-secondary text-foreground-strong"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`custom_connector.signin_${choice}`)}+ </button>+ ))}+ </div>+ <p className="mt-2 text-xs text-muted-foreground">+ {t(`custom_connector.signin_${signIn}_help`)}+ </p>+ </div>+ {(signIn === "token" || signIn === "auto") && (+ <div>+ <label htmlFor={headerId} className="mb-1.5 block text-xs font-medium text-muted-foreground">+ {t("custom_connector.header_label")}+ </label>+ <input+ id={headerId}+ type="text"+ value={headerName}+ maxLength={64}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setHeaderName(event.target.value)}+ placeholder="Authorization"+ disabled={pending}+ className={cn(INPUT, "font-mono text-[13px]")}+ />+ <p className="mt-1.5 text-xs text-muted-foreground">{t("custom_connector.header_help")}</p>+ </div>+ )}+ </div>+ )}+ </div>++ <p className="text-xs leading-relaxed text-muted-foreground">{t("custom_connector.trust_note")}</p>++ {error && (+ <p+ role="alert"+ className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"+ >+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {error}+ </p>+ )}+ </form>+ </ScrollArea>++ <footer className="flex items-center justify-between gap-4 border-t border-border px-6 py-4">+ <p className="min-w-0 truncate text-xs text-muted-foreground" role="status">+ {pending ? t("custom_connector.checking") : ""}+ </p>+ <div className="flex shrink-0 items-center gap-2">+ <Button size="sm" variant="ghost" onClick={onClose} disabled={pending}>+ {t("common.cancel")}+ </Button>+ <Button+ size="sm"+ onClick={() => void submit()}+ disabled={!canSubmit}+ data-testid="connector-continue"+ className="gap-1.5"+ >+ {pending && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t("custom_connector.continue")}+ </Button>+ </div>+ </footer>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex bac55b0ee0..5a44f19e79 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -6,7 +6,7 @@ import { ProjectConnectDialog } from "@/components/agentic/ProjectConnectDialog"import { VoiceBubble, storedVoiceBubbleOpen, storeVoiceBubbleOpen } from "@/components/agentic/VoiceBubble";import { RetainedWorkspaceGrid } from "@/components/agentic/RetainedWorkspaceGrid";import { WorkspaceAgentSetup } from "@/components/agentic/WorkspaceAgentSetup";-import { RunOnPicker, storeRunOn, storedRunOn } from "@/components/agentic/RunOnPicker";+import { RUN_ON_AUTO, RunOnPicker, storeRunOn, storedRunOn } from "@/components/agentic/RunOnPicker";import { WorkspaceOptionsDialog } from "@/components/agentic/WorkspaceOptionsDialog";import { FONT_DEFAULT } from "@/components/agentic/paneFont";import { storePaneStyle, storedPaneStyle, type PaneStyle } from "@/components/agentic/terminalThemes";@@ -19,6 +19,7 @@ import { leaderPassthrough, PANE_COMMAND_EVENT, PANE_INPUT_EVENT, type IdeHotkeyimport { appChord } from "@/store/appChordSettings";import { GitCheckoutPicker } from "@/components/agentic/git/GitCheckoutPicker";import { GitPanelDialog } from "@/components/agentic/git/GitPanelDialog";+import { computersApi } from "@/lib/computersApi";import { KEEP_CHECKOUT, prepareGit, type GitPlan } from "@/lib/gitApi";import { SplitRightIcon, SplitBelowIcon, SplitLeftIcon, SplitAboveIcon } from "@/components/agentic/splitIcons";import type { PaneSplitDirection } from "@/components/agentic/WorkspaceTerminalHeader";@@ -148,7 +149,8 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const installed = codingAgents.filter((agent) => agent.installed);// On a connected computer the CLI has to be installed THERE, not here: the// server is checked before anything is copied, so every coding CLI is offered.- const workspaceChoices = workspaceComputer ? codingAgents : installed;+ // "Automatic" may land on this PC, so it offers only what is installed here.+ const workspaceChoices = workspaceComputer && workspaceComputer !== RUN_ON_AUTO ? codingAgents : installed;const agentChoices = agents.filter((agent) =>(agent.kind === "shell" || agent.accepts_prompts !== false) && (agentComputer || agent.installed));const dialogOpen = projectDialog || workspaceProject !== null || renameOpen || agentPicker !== null;@@ -346,12 +348,14 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {const createWorkspace = () => void run(async () => {if (!workspaceProject || workspaceAgents.length === 0 || workspaceAgents.some((agent) => !agent)) throw new Error("Choose an installed coding agent for every session.");storeRunOn(workspaceProject.id, workspaceComputer);+ // "Automatic" settles on one machine now, by the shares set under Settings, Computers.+ const runsOn = workspaceComputer === RUN_ON_AUTO ? await computersApi.pickPlacement() : workspaceComputer;// Git first: a new branch or worktree decides WHICH folder the agents start in.const prepared = workspaceGit.mode === "current" ? null : await prepareGit(workspaceProject.path, workspaceGit);const ownCheckout = workspaceGit.mode === "new_worktree" || workspaceGit.mode === "open_worktree";const next = await startIdeSession(prepared?.folder ?? workspaceProject.path, workspaceAgents.map((agent) => ({ agent })), {projectId: workspaceProject.id, name: workspaceName.trim() || (ownCheckout && prepared?.branch ? prepared.branch : undefined),- computerId: workspaceComputer ?? undefined,+ computerId: runsOn ?? undefined,onMessage: notify,});setState(next);@@ -714,7 +718,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {</label><WorkspaceAgentSetup agents={workspaceChoices} sessions={workspaceAgents} onChange={setWorkspaceAgents} disabled={busy} /><GitCheckoutPicker folder={workspaceProject.path} value={workspaceGit} onChange={setWorkspaceGit} disabled={busy} context="workspace" />- <RunOnPicker value={workspaceComputer} onChange={setWorkspaceComputer} disabled={busy} />+ <RunOnPicker value={workspaceComputer} onChange={setWorkspaceComputer} disabled={busy} allowAuto /></div><footer className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-t border-border bg-muted/20 px-6 py-4 sm:px-8"><span className="text-xs text-muted-foreground" aria-live="polite">{workspaceAgents.length} {workspaceAgents.length === 1 ? "session" : "sessions"} · {new Set(workspaceAgents.filter(Boolean)).size} {new Set(workspaceAgents.filter(Boolean)).size === 1 ? "agent" : "agents"}</span>diff --git a/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx b/jarvis/ui/web/frontend/src/views/ComputersView.test.tsxindex ec9d568b64..8d39efae0f 100644--- a/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ComputersView.test.tsx@@ -9,7 +9,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-liimport { ComputersView } from "@/views/ComputersView";import { loadLocaleChunk, setUiLanguage } from "@/i18n";-import type { Computer } from "@/lib/computersApi";+import type { Computer, PairedServer } from "@/lib/computersApi";// Assembled from parts so the literal key header never appears in source;// the pre-push credential scanner flags that header as a private key block.@@ -23,6 +23,7 @@ interface Call {}function installFetch(routes: Record<string, (body: unknown) => unknown>) {+ routes = { "GET /api/computers/pairing/servers": () => ({ servers: [] }), ...routes };const calls: Call[] = [];const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const url = String(input);@@ -389,8 +390,7 @@ describe("ComputersView", () => {});expect((screen.getByTestId("cx-server-host") as HTMLInputElement).value).toBe("https://backend.example.com");expect((screen.getByTestId("cx-pairing-code") as HTMLInputElement).value).toBe("ExampleCode");- expect((within(screen.getByTestId("cx-server-form")).getByRole("button", { name: "Add computer" }) as HTMLButtonElement).disabled).toBe(true);- fireEvent.submit(screen.getByTestId("cx-server-form"));+ expect((within(screen.getByTestId("cx-server-form")).getByRole("button", { name: "Add computer" }) as HTMLButtonElement).disabled).toBe(false);expect(calls.some((call) => call.method === "POST")).toBe(false);fireEvent.click(screen.getByRole("radio", { name: "SSH" }));expect((screen.getByRole("textbox", { name: "SSH host" }) as HTMLInputElement).value).toBe("192.0.2.10");@@ -399,6 +399,81 @@ describe("ComputersView", () => {expect((screen.getByRole("textbox", { name: "Pairing code" }) as HTMLInputElement).value).toBe("ExampleCode");});+ it("pairs a server, opens its real launch URL, checks it and revokes the connection", async () => {+ let servers: PairedServer[] = [];+ const server: PairedServer = { id: "s_test", url: "https://backend.example.com", name: "Remote Jarvis", platform: "Linux", created_at: 1, checked_at: 1, online: true };+ const calls = installFetch({+ "GET /api/computers": () => ({ computers: [] }),+ "GET /api/computers/providers": () => ({ providers: PROVIDERS }),+ "GET /api/computers/identity": () => IDENTITY,+ "GET /api/computers/pairing/servers": () => ({ servers }),+ "POST /api/computers/pairing/servers": () => { servers = [server]; return server; },+ "POST /api/computers/pairing/servers/s_test/open": () => ({ url: "https://backend.example.com/api/computers/pairing/enter#example-ticket" }),+ "POST /api/settings/open-external": () => ({ opened: true }),+ "POST /api/computers/pairing/servers/s_test/check": () => { servers = [{ ...server, online: false }]; return servers[0]; },+ "DELETE /api/computers/pairing/servers/s_test": () => { servers = []; return { removed: true }; },+ });+ renderView();+ fireEvent.click(await screen.findByTestId("computers-add-first"));+ fireEvent.click(await screen.findByRole("radio", { name: "Server address" }));+ fireEvent.paste(screen.getByTestId("cx-server-host"), { clipboardData: { getData: () => "https://backend.example.com/#pairing_code=ExampleCode" } });+ fireEvent.submit(screen.getByTestId("cx-server-form"));+ fireEvent.submit(screen.getByTestId("cx-server-form"));+ expect(await screen.findByTestId("paired-servers")).toBeTruthy();+ expect(screen.queryByTestId("computers-connect-dialog")).toBeNull();+ expect(calls.filter((call) => call.method === "POST" && call.url === "/api/computers/pairing/servers")).toHaveLength(1);+ expect(calls.find((call) => call.method === "POST" && call.url === "/api/computers/pairing/servers")?.body).toEqual({ host: "https://backend.example.com", code: "ExampleCode" });+ expect(calls.some((call) => call.url === "/api/computers/test")).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Open server" }));+ await waitFor(() => expect(calls.some((call) => call.url === "/api/settings/open-external")).toBe(true));+ await waitFor(() => expect((screen.getByRole("button", { name: "Check again" }) as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));+ expect(await screen.findByText(/Connection unavailable/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Disconnect and revoke access" }));+ await waitFor(() => expect(screen.queryByTestId("paired-servers")).toBeNull());+ });++ it("keeps pairing details after a failed connection and can retry", async () => {+ const calls = installFetch({+ "GET /api/computers": () => ({ computers: [] }),+ "GET /api/computers/providers": () => ({ providers: PROVIDERS }),+ "GET /api/computers/identity": () => IDENTITY,+ "POST /api/computers/pairing/servers": () => { throw new Error("Pairing rejected"); },+ });+ renderView();+ fireEvent.click(await screen.findByTestId("computers-add-first"));+ fireEvent.click(await screen.findByRole("radio", { name: "Server address" }));+ fireEvent.change(screen.getByTestId("cx-server-host"), { target: { value: "backend.example.com" } });+ fireEvent.change(screen.getByTestId("cx-pairing-code"), { target: { value: "ExampleCode" } });+ fireEvent.submit(screen.getByTestId("cx-server-form"));+ expect(await screen.findByText("Pairing rejected")).toBeTruthy();+ expect((screen.getByTestId("cx-pairing-code") as HTMLInputElement).value).toBe("ExampleCode");+ fireEvent.submit(screen.getByTestId("cx-server-form"));+ await waitFor(() => expect(calls.filter((call) => call.method === "POST")).toHaveLength(2));+ });++ it("creates a pairing code only on request and can revoke a paired client", async () => {+ let clients = [{ id: "g_test", name: "Laptop", created_at: 1 }];+ const calls = installFetch({+ "GET /api/computers": () => ({ computers: [] }),+ "GET /api/computers/providers": () => ({ providers: PROVIDERS }),+ "GET /api/computers/identity": () => IDENTITY,+ "GET /api/computers/pairing/clients": () => ({ clients }),+ "POST /api/computers/pairing/code": () => ({ code: "ExampleCode", expires_at: Date.now() / 1000 + 300 }),+ "DELETE /api/computers/pairing/clients/g_test": () => { clients = []; return { removed: true }; },+ });+ renderView();+ fireEvent.click(await screen.findByTestId("computers-add-first"));+ fireEvent.click(await screen.findByRole("radio", { name: "Server address" }));+ expect(calls.some((call) => call.method === "POST")).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Allow another computer to connect to this Jarvis" }));+ expect(await screen.findByText("Laptop")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Generate pairing code" }));+ expect(await screen.findByText("ExampleCode")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Revoke access" }));+ await waitFor(() => expect(screen.queryByText("Laptop")).toBeNull());+ });+it("validates the visible SSH port and sends explicit login overrides", async () => {const calls = installFetch({"GET /api/computers": () => ({ computers: [] }),diff --git a/jarvis/ui/web/frontend/src/views/ComputersView.tsx b/jarvis/ui/web/frontend/src/views/ComputersView.tsxindex ad464a28fc..85ce28c441 100644--- a/jarvis/ui/web/frontend/src/views/ComputersView.tsx+++ b/jarvis/ui/web/frontend/src/views/ComputersView.tsx@@ -15,7 +15,7 @@ import { Panel } from "@/components/extensions/primitives";import { ComputersIcon } from "@/components/icons/sectionIcons";import { ScrollArea } from "@/components/ui/scroll-area";import { Button } from "@/components/ui/button";-import { useCheckAll, useComputers, useIdentity } from "@/hooks/useComputers";+import { useCheckAll, useComputers, useIdentity, useTailscale } from "@/hooks/useComputers";import { useLocaleChunk, useT } from "@/i18n";import { robustCopy } from "@/lib/clipboard";import type { Computer } from "@/lib/computersApi";@@ -23,8 +23,10 @@ import { ComputerDetail, type DetailTab } from "@/views/computers/ComputerDetailimport { ComputerRow } from "@/views/computers/ComputerRow";import { KeepWorking } from "@/views/computers/KeepWorking";import { needsAttention } from "@/views/computers/parts";+import { PlacementSection } from "@/views/computers/Placement";import { Empty, Group, Row, Section, sectionActionCls } from "@/views/computers/surface";import { ConnectDialog } from "@/views/computers/ConnectDialog";+import { PairedServers, usePairedServers } from "@/views/computers/PairedServers";/** Keyframes the provisioning bar uses; scoped by name, shipped with the view. */const KEYFRAMES = `@keyframes computers-indeterminate {@@ -72,16 +74,21 @@ export function ComputersView() {const t = useT();useLocaleChunk("computers");const computers = useComputers();+ const pairedServers = usePairedServers();const checkAll = useCheckAll();const [open, setOpen] = useState<{ id: string; tab: DetailTab } | null>(null);const [adding, setAdding] = useState(false);const rows = useMemo(() => computers.data ?? [], [computers.data]);+ // Tailscale addresses to suggest per computer; nothing without Tailscale.+ const tailscale = useTailscale(rows.length > 0);const current = open ? rows.find((c) => c.id === open.id) ?? null : null;- const attention = rows.filter(needsAttention).length;- const online = rows.filter((c) => c.health.status === "online").length;+ // A switched-off computer is neither online nor missing: it is left out of the count.+ const inUse = rows.filter((c) => c.enabled !== false);+ const attention = inUse.filter(needsAttention).length;+ const online = inUse.filter((c) => c.health.status === "online").length;const summary = [- t("computers.list_summary").replace("{online}", String(online)).replace("{total}", String(rows.length)),+ t("computers.list_summary").replace("{online}", String(online)).replace("{total}", String(inUse.length)),attention > 0 ? t("computers.list_attention").replace("{count}", String(attention)) : null,].filter(Boolean)@@ -140,6 +147,7 @@ export function ComputersView() {)}</div>+ <PairedServers />{computers.isSuccess && (<Sectiontitle={t("computers.list_title")}@@ -173,7 +181,7 @@ export function ComputersView() {<EmptytestId="computers-welcome"icon={<ComputersIcon />}- title={t("computers.empty_title")}+ title={t(pairedServers.data?.length ? "computers.paired_no_ssh" : "computers.empty_title")}description={t("computers.empty_body")}><Button@@ -196,6 +204,7 @@ export function ComputersView() {computer={computer}checking={checkAll.isPending}onOpen={() => setOpen({ id: computer.id, tab: "overview" })}+ suggestions={tailscale.data?.suggestions?.[computer.id]}/></li>))}@@ -203,6 +212,8 @@ export function ComputersView() {)}</Section>)}++ {computers.isSuccess && rows.length > 0 && <PlacementSection computers={rows} />}</div>)}</ScrollArea>diff --git a/jarvis/ui/web/frontend/src/views/CustomApisView.css b/jarvis/ui/web/frontend/src/views/CustomApisView.cssnew file mode 100644index 0000000000..9429561b73--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/CustomApisView.css@@ -0,0 +1,40 @@+.custom-api-connections {+ container-type: inline-size;+}++.custom-api-row {+ display: grid;+ grid-template-columns: 44px minmax(0, 1fr) auto 32px;+ align-items: center;+ gap: 14px;+}++@container (max-width: 480px) {+ .custom-api-header {+ flex-direction: column;+ }++ .custom-api-row {+ grid-template-columns: 44px minmax(0, 1fr) 32px;+ gap: 6px 12px;+ }++ .custom-api-row > :first-child {+ grid-row: 1 / 3;+ }++ .custom-api-row > :nth-child(2) {+ grid-column: 2;+ grid-row: 1;+ }++ .custom-api-status {+ grid-column: 2;+ grid-row: 2;+ }++ .custom-api-row > :last-child {+ grid-column: 3;+ grid-row: 1 / 3;+ }+}diff --git a/jarvis/ui/web/frontend/src/views/CustomApisView.test.tsx b/jarvis/ui/web/frontend/src/views/CustomApisView.test.tsxindex 82ee32a8d4..985de5acb5 100644--- a/jarvis/ui/web/frontend/src/views/CustomApisView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/CustomApisView.test.tsx@@ -2,64 +2,116 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { CustomApisView } from "./CustomApisView";-import { actionWithPath, newApiAction } from "@/lib/customApi";+import type { ApiConnection } from "@/lib/customApi";afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+const connection: ApiConnection = {+ id: "a".repeat(32), name: "ElevenLabs", website: "https://elevenlabs.io", brand_id: "elevenlabs",+ logo_data: "", categories: ["Speech"], action_count: 414, omitted_operations: 0,+ enabled: true, has_credential: true, tools_ready: true, status: "verified",+};+const reply = (data: unknown, ok = true) => ({ ok, status: ok ? 200 : 422, json: async () => data }) as Response;function show() {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });return render(<QueryClientProvider client={client}><CustomApisView onBack={() => {}} /></QueryClientProvider>);}-const reply = (data: unknown, ok = true) => ({ ok, status: ok ? 200 : 422, json: async () => data }) as Response;-describe("Custom APIs", () => {- it("saves native actions and keeps the key out of the definition", async () => {- let saved: { definition: Record<string, unknown>; credential: string } | null = null;+describe("simple service connections", () => {+ it("adds a service with only its name and key, then shows its inherited capabilities", async () => {+ let rows: ApiConnection[] = [];+ let saved: Record<string, string> | null = null;+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, init?: RequestInit) => {+ if (String(url).endsWith("/connect") && init?.method === "POST") {+ saved = JSON.parse(String(init.body)); rows = [connection]; return reply(connection);+ }+ return reply(rows);+ }));+ const rendered = show();+ await screen.findByLabelText("Service name");+ expect(rendered.container.querySelectorAll("input")).toHaveLength(2);+ expect(screen.queryByLabelText("Service URL")).toBeNull();+ expect(screen.queryByText("JSON body schema (optional)")).toBeNull();+ fireEvent.change(screen.getByLabelText("Service name"), { target: { value: "11labs" } });+ expect(screen.getByTestId("provider-logo-elevenlabs")).toBeDefined();+ fireEvent.change(screen.getByLabelText("API key", { exact: true }), { target: { value: "fixture-only-key" } });+ fireEvent.click(screen.getByRole("button", { name: "Add plugin" }));+ await screen.findByText("ElevenLabs", { exact: true });+ expect(saved!.name).toBe("11labs");+ expect(saved!.credential).toBe("fixture-only-key");+ expect(Object.keys(saved!).sort()).toEqual(["credential", "id", "name"]);+ expect(screen.queryByDisplayValue("fixture-only-key")).toBeNull();+ expect(screen.getByText(/414 capabilities/)).toBeDefined();+ expect(screen.getByText(/New capabilities become available/)).toBeDefined();+ });++ it("keeps the form recoverable when a key is rejected", async () => {+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "POST"+ ? reply({ detail: { code: "invalid_key" } }, false) : reply([])));+ show();+ fireEvent.change(await screen.findByLabelText("Service name"), { target: { value: "ElevenLabs" } });+ fireEvent.change(screen.getByLabelText("API key", { exact: true }), { target: { value: "fixture-only-key" } });+ fireEvent.click(screen.getByRole("button", { name: "Add plugin" }));+ expect((await screen.findByRole("alert")).textContent).toContain("did not accept");+ expect(screen.getByDisplayValue("ElevenLabs")).toBeDefined();+ expect(screen.getByRole("button", { name: "Add plugin" }).hasAttribute("disabled")).toBe(false);+ });++ it("lets another connection be added without replacing the existing one", async () => {+ let rows = [connection];+ const requested: string[] = [];vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => {- if (init?.method === "PUT") { saved = JSON.parse(String(init.body)); return reply({}); }- return reply([]);+ if (init?.method === "POST") {+ const body = JSON.parse(String(init.body)); requested.push(body.id);+ const second = { ...connection, id: body.id, name: "Sample Cloud", brand_id: "samplecloud" };+ rows = [...rows, second]; return reply(second);+ }+ return reply(rows);}));show();- await screen.findByText("Your services, connected to Jarvis");- fireEvent.click(screen.getByRole("button", { name: "Add API" }));- fireEvent.change(screen.getByLabelText("Service name"), { target: { value: "My service" } });- fireEvent.change(screen.getByLabelText("Service URL"), { target: { value: "https://api.example.com" } });- fireEvent.change(screen.getByLabelText("API key", { exact: true }), { target: { value: "test-secret-key" } });- fireEvent.change(screen.getByLabelText("What should Jarvis use this action for?"), { target: { value: "List items" } });- fireEvent.click(screen.getByRole("button", { name: "Save API" }));- await waitFor(() => expect(saved).not.toBeNull());- expect(saved!.credential).toBe("test-secret-key");- expect(JSON.stringify(saved!.definition)).not.toContain("test-secret-key");- await screen.findByRole("button", { name: "Add API" });- expect(screen.queryByDisplayValue("test-secret-key")).toBeNull();+ await screen.findByText("ElevenLabs", { exact: true });+ fireEvent.click(screen.getByRole("button", { name: "Add plugin" }));+ fireEvent.change(screen.getByLabelText("Service name"), { target: { value: "Sample Cloud" } });+ fireEvent.change(screen.getByLabelText("API key", { exact: true }), { target: { value: "second-fixture-key" } });+ fireEvent.click(screen.getByRole("button", { name: "Add plugin" }));+ await screen.findByText("Sample Cloud", { exact: true });+ expect(screen.getByText("ElevenLabs", { exact: true })).toBeDefined();+ expect(requested[0]).not.toBe(connection.id);+ expect(screen.getByTestId("generated-connection-mark")).toBeDefined();});- it("keeps failed saves open and displays the backend error", async () => {- vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "PUT"- ? reply({ detail: "Enter an API key before enabling this service" }, false) : reply([])));+ it("pauses the selected connection through its menu", async () => {+ let row = connection;+ const requests: unknown[] = [];+ vi.stubGlobal("fetch", vi.fn(async (url: unknown, init?: RequestInit) => {+ if (init?.method === "PATCH") {+ requests.push([String(url), JSON.parse(String(init.body))]); row = { ...row, enabled: false, tools_ready: false }; return reply(row);+ }+ return reply([row]);+ }));show();- fireEvent.click(await screen.findByRole("button", { name: "Add API" }));- fireEvent.change(screen.getByLabelText("Service name"), { target: { value: "My service" } });- fireEvent.change(screen.getByLabelText("Service URL"), { target: { value: "https://api.example.com" } });- fireEvent.change(screen.getByLabelText("What should Jarvis use this action for?"), { target: { value: "List items" } });- fireEvent.click(screen.getByRole("button", { name: "Save API" }));- expect((await screen.findByRole("alert")).textContent).toContain("Enter an API key");- expect(screen.getByDisplayValue("My service")).toBeDefined();+ fireEvent.click(await screen.findByRole("button", { name: "Manage ElevenLabs" }));+ fireEvent.click(screen.getByRole("menuitem", { name: "Pause connection" }));+ await screen.findByText("Paused");+ expect(requests).toEqual([[`/api/custom-apis/connections/${connection.id}`, { enabled: false }]]);});- it("derives required path arguments while keeping query parameters", () => {- const action = newApiAction();- action.parameters = [{ name: "page", location: "query", type: "integer", required: false, description: "" }];- const changed = actionWithPath(action, "/items/{item_id}");- expect(changed.parameters.map((p) => [p.name, p.location, p.required])).toEqual([- ["page", "query", false], ["item_id", "path", true],- ]);- expect(actionWithPath(changed, "/items").parameters).toHaveLength(1);+ it("offers name suggestions without requiring technical configuration", async () => {+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "POST"+ ? reply({ detail: { code: "ambiguous_service", suggestions: ["Sample Calendar", "Sample Mail"] } }, false) : reply([])));+ show();+ fireEvent.change(await screen.findByLabelText("Service name"), { target: { value: "Sample" } });+ fireEvent.change(screen.getByLabelText("API key", { exact: true }), { target: { value: "fixture-only-key" } });+ fireEvent.click(screen.getByRole("button", { name: "Add plugin" }));+ fireEvent.click(await screen.findByRole("button", { name: "Sample Calendar" }));+ expect(screen.getByDisplayValue("Sample Calendar")).toBeDefined();+ expect(screen.queryByRole("alert")).toBeNull();});- it("shows a loading failure without pretending the list is empty", async () => {+ it("does not render an empty setup form when the connection list failed", async () => {vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("Offline"); }));show();- expect((await screen.findByRole("alert")).textContent).toContain("Offline");- expect(screen.queryByText("Your services, connected to Jarvis")).toBeNull();+ await screen.findByRole("alert");+ expect(screen.queryByLabelText("API key", { exact: true })).toBeNull();+ await waitFor(() => expect(screen.getByRole("button", { name: "Retry" })).toBeDefined());});});diff --git a/jarvis/ui/web/frontend/src/views/CustomApisView.tsx b/jarvis/ui/web/frontend/src/views/CustomApisView.tsxindex b04afa62ac..f50fadbcf3 100644--- a/jarvis/ui/web/frontend/src/views/CustomApisView.tsx+++ b/jarvis/ui/web/frontend/src/views/CustomApisView.tsx@@ -1,226 +1,188 @@-import { useRef, useState, type FormEvent, type ReactNode } from "react";+import { useState, type FormEvent } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";-import { ArrowLeft, Cable, Download, Loader2, Plus, Trash2 } from "lucide-react";+import { ArrowRight, Check, ChevronRight, KeyRound, Loader2, LockKeyhole, MoreHorizontal, Pause, Play, Plus, Search, Trash2, Users } from "lucide-react";import { useT } from "@/i18n";-import { SoftButton } from "@/components/extensions/primitives";-import { BrandedSelect } from "@/components/ui/select";-import { actionWithPath, customApiRequest, newApiAction, newApiDefinition,- type ApiAction, type ApiDefinition, type ApiParameter, type ApiStatus } from "@/lib/customApi";+import { ActionMenu, BackLink, IconButton, Panel, PanelHeader, StatusDot } from "@/components/extensions/primitives";+import { ProviderLogo, providerFamily } from "@/components/providers/ProviderLogo";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { bundledPluginLogo } from "@/lib/pluginLogos";+import { ApiConnectionError, customApiRequest, type ApiConnection } from "@/lib/customApi";+import "./CustomApisView.css";-const fieldClass = "w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:ring-2 focus:ring-ring disabled:opacity-50";-const queryKey = ["custom-apis"];+const QUERY_KEY = ["api-connections"];const jsonRequest = (method: string, body: unknown): RequestInit => ({method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),});-function Field({ label, children }: { label: string; children: ReactNode }) {- return <label className="grid min-w-0 gap-1.5 text-xs font-medium text-muted-foreground">{label}{children}</label>;+function brandFor(name: string): string {+ const value = name.toLowerCase().replace(/\b(api|documentation)\b/g, "").replace(/[^a-z0-9]/g, "");+ return value === "11labs" ? "elevenlabs" : value;+}++/** Original artwork first; the geometric fallback is a Jarvis-owned connection mark. */+export function ConnectionLogo({ name, brand = "", image = "", large = false }: {+ name: string; brand?: string; image?: string; large?: boolean;+}) {+ const id = brand || brandFor(name);+ const size = large ? "!h-14 !w-14 !rounded-xl" : "!h-11 !w-11 !rounded-xl";+ const bundled = bundledPluginLogo(id);+ if (providerFamily(id) === id) return <ProviderLogo providerId={id} label={name} className={size} />;+ if (bundled || image) return <span aria-hidden className={`inline-flex shrink-0 items-center justify-center bg-secondary p-2 ${size}`}>+ <img src={bundled || image} alt="" className="h-full w-full object-contain" />+ </span>;+ const seed = [...name].reduce((hash, char) => ((hash * 31) + char.charCodeAt(0)) >>> 0, 19);+ return <span aria-hidden data-testid="generated-connection-mark" className={`inline-flex shrink-0 items-center justify-center bg-secondary text-muted-foreground ${size}`}>+ <svg viewBox="0 0 32 32" className="h-7 w-7" fill="none" stroke="currentColor" strokeWidth="1.8">+ <rect x="11" y="11" width="10" height="10" rx={seed % 2 ? 3 : 1} />+ {[0, 1, 2, 3].map((i) => <g key={i} transform={`rotate(${i * 90} 16 16)`}>+ <path d="M16 11V6" /><circle cx="16" cy="4.5" r={seed & (1 << i) ? 2 : 1} fill={seed & (1 << i) ? "currentColor" : "none"} />+ </g>)}+ </svg>+ </span>;+}++function useConnectionError() {+ const t = useT();+ return (error: unknown): string => {+ if (error instanceof ApiConnectionError) {+ const key = `custom_apis.errors.${error.code}`;+ const translated = t(key);+ return translated === key ? t("custom_apis.failed") : translated;+ }+ return t("custom_apis.failed");+ };}export function CustomApisView({ onBack }: { onBack: () => void }) {const t = useT();+ const errorText = useConnectionError();const queryClient = useQueryClient();- const list = useQuery({ queryKey, queryFn: () => customApiRequest<ApiStatus[]>(), retry: false });- const [editing, setEditing] = useState<ApiStatus | null>(null);- const [running, setRunning] = useState<ApiDefinition | null>(null);- const [deleting, setDeleting] = useState<string | null>(null);- const [busy, setBusy] = useState(false);+ const list = useQuery({ queryKey: QUERY_KEY, queryFn: () => customApiRequest<ApiConnection[]>("/connections"), retry: false });+ const [editor, setEditor] = useState<ApiConnection | "new" | null>(null);+ const [details, setDetails] = useState<ApiConnection | null>(null);+ const [removing, setRemoving] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);const [error, setError] = useState("");- const upload = useRef<HTMLInputElement>(null);- const refresh = () => queryClient.invalidateQueries({ queryKey });- const start = (definition: ApiDefinition) => {- setError(""); setEditing({ definition, has_credential: false, tools_ready: false });- };- async function loadTemplate() {- setBusy(true); setError("");- try { start({ ...await customApiRequest<ApiDefinition>("/templates/elevenlabs"), enabled: true }); }- catch (e) { setError(e instanceof Error ? e.message : t("custom_apis.failed")); }- finally { setBusy(false); }+ const refresh = () => queryClient.invalidateQueries({ queryKey: QUERY_KEY });+ async function remove(connection: ApiConnection) {+ setBusy(connection.id); setError("");+ try { await customApiRequest(`/${connection.id}`, { method: "DELETE" }); setRemoving(null); await refresh(); }+ catch (e) { setError(errorText(e)); }+ finally { setBusy(null); }}- async function remove(id: string) {- setBusy(true); setError("");- try { await customApiRequest(`/${id}`, { method: "DELETE" }); setDeleting(null); await refresh(); }- catch (e) { setError(e instanceof Error ? e.message : t("custom_apis.failed")); }- finally { setBusy(false); }+ async function toggle(connection: ApiConnection) {+ setBusy(connection.id); setError("");+ try { await customApiRequest(`/connections/${connection.id}`, jsonRequest("PATCH", { enabled: !connection.enabled })); await refresh(); }+ catch (e) { setError(errorText(e)); }+ finally { setBusy(null); }}- if (editing) return <ApiEditor key={editing.definition.id} initial={editing}- onCancel={() => setEditing(null)} onSaved={async () => { setEditing(null); await refresh(); }} />;- if (running) return <ApiRunner definition={running} onBack={() => setRunning(null)} />;- return <section className="space-y-5" aria-label={t("custom_apis.title")}>- <SoftButton onClick={onBack}><ArrowLeft className="mr-2 h-4 w-4" />{t("nav.plugins")}</SoftButton>- <div className="flex items-start gap-4">- <div className="rounded-xl bg-secondary p-3 text-primary"><Cable className="h-6 w-6" /></div>- <div><h2 className="text-xl font-semibold text-foreground">{t("custom_apis.title")}</h2>- <p className="mt-1 text-sm text-muted-foreground">{t("custom_apis.subtitle")}</p></div>- </div>- <div className="flex flex-wrap gap-2">- <SoftButton onClick={() => start(newApiDefinition())}><Plus className="mr-2 h-4 w-4" />{t("custom_apis.add")}</SoftButton>- <SoftButton disabled={busy} onClick={() => void loadTemplate()}>{t("custom_apis.elevenlabs")}</SoftButton>- <SoftButton onClick={() => upload.current?.click()}>{t("custom_apis.import")}</SoftButton>- <input ref={upload} className="hidden" type="file" accept="application/json,.json" aria-label={t("custom_apis.import")}- onChange={async (event) => {- const file = event.target.files?.[0]; event.target.value = "";- if (!file) return;- try {- if (file.size > 256_000) throw new Error(t("custom_apis.invalid_file"));- const value = JSON.parse(await file.text()) as ApiDefinition;- if (!value.name || !value.base_url || !Array.isArray(value.actions) || !value.auth || "credential" in value)- throw new Error(t("custom_apis.invalid_file"));- // Import is a draft, never an implicit activation or provider call.- start(await customApiRequest<ApiDefinition>("/validate", jsonRequest("POST", {- ...value, id: crypto.randomUUID().replaceAll("-", ""), enabled: false,- })));- } catch { setError(t("custom_apis.invalid_file")); }- }} />- </div>- {(error || list.error) && <p role="alert" className="text-sm text-destructive">{error || (list.error as Error).message}- {list.error && <button className="ml-2 underline" onClick={() => void list.refetch()}>{t("custom_apis.retry")}</button>}</p>}- {list.isPending ? <p role="status" className="text-sm text-muted-foreground">{t("custom_apis.loading")}</p>- : list.data?.length === 0 ? <div className="rounded-xl border border-dashed border-border p-8 text-center">- <h3 className="font-medium text-foreground">{t("custom_apis.empty")}</h3>- <p className="mx-auto mt-2 max-w-md text-sm text-muted-foreground">{t("custom_apis.empty_hint")}</p>- </div> : <div className="space-y-3">{list.data?.map((item) => <article key={item.definition.id} className="rounded-xl border border-border bg-card p-4">- <div className="flex flex-wrap items-start justify-between gap-3">- <div className="min-w-0"><h3 className="font-semibold text-foreground">{item.definition.name}</h3>- <p className="mt-1 break-all text-xs text-muted-foreground">{item.definition.base_url}</p>- <p className="mt-2 text-sm text-muted-foreground">{item.definition.description}</p>- <p className="mt-2 text-xs text-muted-foreground">{item.definition.actions.length} {t("custom_apis.actions")} · {t(!item.definition.enabled ? "custom_apis.disabled" : item.tools_ready ? "custom_apis.ready" : "custom_apis.saved")}</p>- </div>- <div className="flex flex-wrap gap-2">- <SoftButton onClick={() => setEditing(item)}>{t("custom_apis.edit")}</SoftButton>- <SoftButton disabled={!item.tools_ready} onClick={() => setRunning(item.definition)}>{t("custom_apis.run")}</SoftButton>- <SoftButton onClick={() => {- const url = URL.createObjectURL(new Blob([JSON.stringify({ ...item.definition, enabled: false }, null, 2)], { type: "application/json" }));- const anchor = document.createElement("a"); anchor.href = url; anchor.download = `api-${item.definition.id}.json`; anchor.click();- setTimeout(() => URL.revokeObjectURL(url), 1000);- }}><Download className="mr-1 h-3.5 w-3.5" />{t("custom_apis.export")}</SoftButton>- <button className="rounded-lg p-2 text-muted-foreground hover:bg-secondary hover:text-destructive" aria-label={`${t("custom_apis.delete")} ${item.definition.name}`} onClick={() => setDeleting(item.definition.id)}><Trash2 className="h-4 w-4" /></button>- </div>+ if (details) return <ConnectionDetails connection={details} onBack={() => setDetails(null)} />;+ const isEmpty = list.data?.length === 0;+ const showEditor = editor !== null || isEmpty;+ if (showEditor) return <section className="space-y-6" aria-label={t("custom_apis.title")}>+ <BackLink label={isEmpty ? t("nav.plugins") : t("custom_apis.title")}+ onClick={isEmpty ? onBack : () => setEditor(null)} />+ <ConnectionForm key={typeof editor === "object" && editor ? editor.id : "new"}+ initial={typeof editor === "object" ? editor : null}+ onSaved={async () => { await refresh(); setEditor(null); }} />+ </section>;+ return <section className="custom-api-connections space-y-5" aria-label={t("custom_apis.title")}>+ <BackLink label={t("nav.plugins")} onClick={onBack} />+ <PanelHeader className="custom-api-header" title={t("custom_apis.title")} subtitle={t("custom_apis.connections_subtitle")}+ actions={<Button size="sm" onClick={() => setEditor("new")}><Plus />{t("custom_apis.add")}</Button>} />+ {list.isPending && <div role="status" className="flex items-center gap-2 py-8 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("custom_apis.loading")}</div>}+ {(error || list.error) && <p role="alert" className="text-sm text-destructive">{error || errorText(list.error)} <button className="underline" onClick={() => void list.refetch()}>{t("custom_apis.retry")}</button></p>}+ {!!list.data?.length && <Panel><ul className="divide-y divide-border/60" aria-label={t("custom_apis.title")}>+ {list.data.map((connection) => <li key={connection.id} className="px-4 py-4 sm:px-5">+ <div className="custom-api-row">+ <ConnectionLogo name={connection.name} brand={connection.brand_id} image={connection.logo_data} />+ <button className="min-w-0 flex-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => setDetails(connection)}>+ <span className="block truncate text-base font-semibold text-foreground-strong">{connection.name}</span>+ <span className="mt-0.5 block truncate text-sm text-muted-foreground">{connection.action_count} {t("custom_apis.capabilities_count")} <span className="px-1.5 text-foreground-faint">·</span> {connection.website.replace(/^https?:\/\//, "")}</span>+ </button>+ <span className="custom-api-status"><StatusDot tone={!connection.enabled ? "off" : connection.status === "verified" ? "ok" : connection.status === "limited" ? "warn" : "off"}+ label={t(!connection.enabled ? "custom_apis.paused" : connection.tools_ready ? `custom_apis.status_${connection.status}` : "custom_apis.saved")} /></span>+ <ActionMenu label={`${t("custom_apis.manage")} ${connection.name}`} actions={[+ { id: "edit", label: t("custom_apis.edit_key"), icon: <KeyRound className="h-4 w-4" />, onSelect: () => setEditor(connection) },+ { id: "pause", label: t(connection.enabled ? "custom_apis.pause" : "custom_apis.resume"), icon: connection.enabled ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />, onSelect: () => void toggle(connection) },+ { id: "remove", label: t("custom_apis.delete"), icon: <Trash2 className="h-4 w-4" />, separatorAbove: true, onSelect: () => setRemoving(connection.id) },+ ]} trigger={({ toggle: openMenu }) => <IconButton label={`${t("custom_apis.manage")} ${connection.name}`} onClick={openMenu} disabled={busy === connection.id}><MoreHorizontal className="h-4 w-4" /></IconButton>} /></div>- {deleting === item.definition.id && <div className="mt-4 flex flex-wrap items-center gap-3 border-t border-border pt-3">- <p className="text-sm text-muted-foreground">{t("custom_apis.delete_hint")}</p>- <SoftButton disabled={busy} onClick={() => void remove(item.definition.id)}>{t("custom_apis.delete")}</SoftButton>- <SoftButton disabled={busy} onClick={() => setDeleting(null)}>{t("common.cancel")}</SoftButton>+ {removing === connection.id && <div className="mt-4 flex flex-wrap items-center justify-end gap-2 border-t border-border/60 pt-3">+ <p className="mr-auto text-sm text-muted-foreground">{t("custom_apis.remove_confirm")}</p>+ <Button size="sm" variant="ghost" disabled={busy !== null} onClick={() => setRemoving(null)}>{t("common.cancel")}</Button>+ <Button size="sm" variant="destructive" disabled={busy !== null} onClick={() => void remove(connection)}>{t("custom_apis.delete")}</Button></div>}- </article>)}</div>}- <p className="text-xs leading-relaxed text-muted-foreground">{t("custom_apis.availability")}</p>+ </li>)}+ </ul></Panel>}+ <div className="flex gap-2 px-1 text-sm leading-relaxed text-muted-foreground"><Users className="mt-0.5 h-4 w-4 shrink-0" /><p>{t("custom_apis.inheritance")}</p></div></section>;}-function ApiEditor({ initial, onCancel, onSaved }: { initial: ApiStatus; onCancel: () => void; onSaved: () => Promise<void> }) {+function ConnectionForm({ initial, onSaved }: { initial: ApiConnection | null; onSaved: () => Promise<void> }) {const t = useT();- const [definition, setDefinition] = useState(initial.definition);+ const errorText = useConnectionError();+ const [id] = useState(() => initial?.id ?? crypto.randomUUID().replaceAll("-", ""));+ const [name, setName] = useState(initial?.name ?? "");const [credential, setCredential] = useState("");- const [schemas, setSchemas] = useState(initial.definition.actions.map((a) => a.body_schema ? JSON.stringify(a.body_schema, null, 2) : ""));- const [error, setError] = useState("");const [busy, setBusy] = useState(false);- const updateAction = (index: number, action: ApiAction) => setDefinition((d) => ({ ...d, actions: d.actions.map((a, i) => i === index ? action : a) }));- async function save(event: FormEvent) {- event.preventDefault(); setError(""); setBusy(true);+ const [error, setError] = useState<unknown>(null);+ async function submit(event: FormEvent) {+ event.preventDefault(); setError(null); setBusy(true);try {- let actions: ApiAction[];- try { actions = definition.actions.map((a, i) => ({ ...a, body_schema: schemas[i]?.trim() ? JSON.parse(schemas[i]) : null })); }- catch { throw new Error(t("custom_apis.invalid_schema")); }- await customApiRequest(`/${definition.id}`, jsonRequest("PUT", { definition: { ...definition, actions }, ...(credential ? { credential } : {}) }));+ await customApiRequest<ApiConnection>("/connect", jsonRequest("POST", { id, name: name.trim(), ...(credential ? { credential } : {}) }));setCredential(""); await onSaved();- } catch (e) { setError(e instanceof Error ? e.message : t("custom_apis.failed")); }+ } catch (e) { setError(e); }finally { setBusy(false); }}- return <form onSubmit={(event) => void save(event)} className="space-y-5">- <div className="flex items-center justify-between gap-3"><h2 className="text-xl font-semibold text-foreground">{t("custom_apis.configure")}</h2>- <SoftButton disabled={busy} onClick={onCancel}>{t("common.cancel")}</SoftButton></div>- <fieldset disabled={busy} className="space-y-5">- <div className="grid gap-4 sm:grid-cols-2">- <Field label={t("custom_apis.name")}><input required maxLength={100} className={fieldClass} value={definition.name} onChange={(e) => setDefinition({ ...definition, name: e.target.value })} /></Field>- <Field label={t("custom_apis.url")}><input required type="url" placeholder="https://api.example.com" className={fieldClass} value={definition.base_url} onChange={(e) => setDefinition({ ...definition, base_url: e.target.value })} /></Field>- </div>- <Field label={t("custom_apis.description")}><input className={fieldClass} maxLength={2000} value={definition.description} onChange={(e) => setDefinition({ ...definition, description: e.target.value })} /></Field>- <div className="grid gap-4 sm:grid-cols-2">- <Field label={t("custom_apis.auth")}><BrandedSelect ariaLabel={t("custom_apis.auth")} disabled={busy} className={fieldClass} value={definition.auth.mode}- onValueChange={(mode) => setDefinition({ ...definition, auth: { ...definition.auth, mode: mode as ApiDefinition["auth"]["mode"] } })}- options={[{ value: "bearer", label: "Bearer token" }, { value: "header", label: t("custom_apis.header_auth") }, { value: "none", label: t("custom_apis.no_auth") }]} /></Field>- {definition.auth.mode === "header" && <Field label={t("custom_apis.header")}><input required className={fieldClass} value={definition.auth.header_name} onChange={(e) => setDefinition({ ...definition, auth: { ...definition.auth, header_name: e.target.value } })} /></Field>}- {definition.auth.mode !== "none" && <Field label={t("custom_apis.key")}><input type="password" autoComplete="new-password" className={fieldClass} value={credential} placeholder={initial.has_credential ? t("custom_apis.key_saved") : ""} onChange={(e) => setCredential(e.target.value)} /></Field>}- </div>- <p className="text-xs text-muted-foreground">{t("custom_apis.key_hint")}</p>- <label className="flex items-center gap-2 text-sm text-foreground"><input type="checkbox" checked={definition.enabled} onChange={(e) => setDefinition({ ...definition, enabled: e.target.checked })} />{t("custom_apis.enable")}</label>- <div className="space-y-4">{definition.actions.map((action, index) => <section key={index} className="space-y-4 rounded-xl border border-border bg-card p-4">- <div className="flex items-center justify-between"><h3 className="font-medium text-foreground">{t("custom_apis.action")} {index + 1}</h3>- <button type="button" disabled={definition.actions.length === 1} aria-label={`${t("custom_apis.remove_action")} ${index + 1}`} className="p-1 text-muted-foreground hover:text-destructive disabled:opacity-30" onClick={() => {- setDefinition({ ...definition, actions: definition.actions.filter((_, i) => i !== index) }); setSchemas(schemas.filter((_, i) => i !== index));- }}><Trash2 className="h-4 w-4" /></button></div>- <div className="grid gap-3 sm:grid-cols-2">- <Field label={t("custom_apis.action_id")}><input required pattern="[a-z][a-z0-9_]{0,23}" className={fieldClass} value={action.id} onChange={(e) => updateAction(index, { ...action, id: e.target.value })} /></Field>- <Field label={t("custom_apis.action_description")}><input required className={fieldClass} value={action.description} onChange={(e) => updateAction(index, { ...action, description: e.target.value })} /></Field>- <Field label={t("custom_apis.method")}><BrandedSelect ariaLabel={t("custom_apis.method")} disabled={busy} className={fieldClass} value={action.method} onValueChange={(value) => {- const method = value as ApiAction["method"]; updateAction(index, { ...action, method });- if (method === "GET") setSchemas(schemas.map((s, i) => i === index ? "" : s));- }} options={["GET", "POST", "PUT", "PATCH", "DELETE"].map((value) => ({ value, label: value }))} /></Field>- <Field label={t("custom_apis.path")}><input required placeholder="/v1/items/{item_id}" className={fieldClass} value={action.path} onChange={(e) => updateAction(index, actionWithPath(action, e.target.value))} /></Field>- </div>- {action.parameters.map((parameter, pi) => <div key={pi} className="flex flex-wrap items-end gap-2">- <span className="pb-2 text-xs text-muted-foreground">{parameter.location}</span>- <div className="min-w-0 flex-1"><Field label={t("custom_apis.parameter")}><input required disabled={parameter.location === "path"} className={fieldClass} value={parameter.name} onChange={(e) => updateAction(index, { ...action, parameters: action.parameters.map((p, i) => i === pi ? { ...p, name: e.target.value } : p) })} /></Field></div>- <BrandedSelect ariaLabel={t("custom_apis.type")} disabled={busy} className={`${fieldClass} !w-auto`} value={parameter.type}- onValueChange={(value) => updateAction(index, { ...action, parameters: action.parameters.map((p, i) => i === pi ? { ...p, type: value as ApiParameter["type"] } : p) })}- options={["string", "integer", "number", "boolean"].map((value) => ({ value, label: value }))} />- {parameter.location === "query" && <><label className="pb-2 text-xs text-muted-foreground"><input type="checkbox" checked={parameter.required} onChange={(e) => updateAction(index, { ...action, parameters: action.parameters.map((p, i) => i === pi ? { ...p, required: e.target.checked } : p) })} /> {t("custom_apis.required")}</label>- <button type="button" aria-label={t("custom_apis.remove_parameter")} className="p-2 text-muted-foreground" onClick={() => updateAction(index, { ...action, parameters: action.parameters.filter((_, i) => i !== pi) })}><Trash2 className="h-4 w-4" /></button></>}- </div>)}- <SoftButton onClick={() => updateAction(index, { ...action, parameters: [...action.parameters, { name: "", location: "query", type: "string", required: false, description: "" }] })}>{t("custom_apis.add_query")}</SoftButton>- {action.method !== "GET" && <Field label={t("custom_apis.body")}><textarea rows={5} spellCheck={false} className={`${fieldClass} font-mono text-xs`} placeholder={'{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}'} value={schemas[index]} onChange={(e) => setSchemas(schemas.map((s, i) => i === index ? e.target.value : s))} /></Field>}- <div className="grid gap-3 sm:grid-cols-2">- <Field label={t("custom_apis.response")}><BrandedSelect ariaLabel={t("custom_apis.response")} disabled={busy} className={fieldClass} value={action.response}- onValueChange={(value) => updateAction(index, { ...action, response: value as ApiAction["response"] })}- options={["auto", "json", "text", "file"].map((value) => ({ value, label: t(`custom_apis.response_${value}`) }))} /></Field>- <Field label={t("custom_apis.permission")}><BrandedSelect ariaLabel={t("custom_apis.permission")} disabled={busy} className={fieldClass} value={action.risk_tier}- onValueChange={(value) => updateAction(index, { ...action, risk_tier: value as ApiAction["risk_tier"] })}- options={["monitor", "ask", "block"].map((value) => ({ value, label: t(`custom_apis.permission_${value}`) }))} /></Field>- </div>- </section>)}</div>- <SoftButton onClick={() => {- let index = definition.actions.length + 1;- while (definition.actions.some((a) => a.id === `action_${index}`)) index++;- setDefinition({ ...definition, actions: [...definition.actions, newApiAction(index)] }); setSchemas([...schemas, ""]);- }}>{t("custom_apis.add_action")}</SoftButton>- </fieldset>- {error && <p role="alert" className="text-sm text-destructive">{error}</p>}- <button type="submit" disabled={busy} className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50">{busy && <Loader2 className="h-4 w-4 animate-spin" />}{t("custom_apis.save")}</button>- </form>;+ return <div className="mx-auto w-full max-w-md pb-3 pt-1">+ <div className="mb-7 flex items-center gap-4">+ <ConnectionLogo name={name || "Jarvis connection"} brand={initial?.brand_id} image={initial?.logo_data} large />+ <div className="min-w-0"><h2 className="text-xl font-semibold tracking-tight text-foreground-strong">{t(initial ? "custom_apis.edit_key" : "custom_apis.add_title")}</h2>+ <p className="mt-1 text-sm leading-relaxed text-muted-foreground">{t(initial ? "custom_apis.edit_hint" : "custom_apis.simple_hint")}</p></div>+ </div>+ <form onSubmit={(event) => void submit(event)} className="space-y-5" aria-label={t("custom_apis.add_title")}>+ <div className="space-y-2"><label htmlFor="api-service-name" className="text-sm font-medium text-foreground">{t("custom_apis.service_name")}</label>+ <Input id="api-service-name" required readOnly={!!initial} disabled={busy} autoComplete="off" maxLength={100} placeholder={t("custom_apis.name_example")} value={name} onChange={(event) => setName(event.target.value)} className="h-11 rounded-lg bg-secondary/50 text-base" autoFocus={!initial} /></div>+ <div className="space-y-2"><label htmlFor="api-service-key" className="text-sm font-medium text-foreground">{t("custom_apis.key")}</label>+ <Input id="api-service-key" type="password" required={!initial} disabled={busy} autoComplete="new-password" maxLength={8192} placeholder={t(initial?.has_credential ? "custom_apis.key_saved" : "custom_apis.key_placeholder")} value={credential} onChange={(event) => setCredential(event.target.value)} className="h-11 rounded-lg bg-secondary/50 font-mono text-base" /></div>+ {Boolean(error) && <div role="alert" className="rounded-lg bg-destructive/10 px-3 py-2.5 text-sm text-destructive">+ {errorText(error)}+ {error instanceof ApiConnectionError && error.suggestions.length > 0 && <div className="mt-2 flex flex-wrap gap-2">{error.suggestions.map((suggestion) => <button key={suggestion} type="button" className="rounded-md bg-background px-2 py-1 text-foreground" onClick={() => { setName(suggestion); setError(null); }}>{suggestion}</button>)}</div>}+ </div>}+ <Button type="submit" className="h-11 w-full rounded-lg" disabled={busy || !name.trim() || (!initial && !credential)}>+ {busy ? <><Loader2 className="animate-spin" />{t("custom_apis.connecting")}</> : <>{t(initial ? "custom_apis.save_key" : "custom_apis.connect")}<ArrowRight /></>}+ </Button>+ {busy && <p role="status" className="text-center text-sm text-muted-foreground">{t("custom_apis.discovering")}</p>}+ </form>+ <div className="mt-5 flex gap-2.5 text-xs leading-relaxed text-muted-foreground"><LockKeyhole className="mt-0.5 h-3.5 w-3.5 shrink-0" /><p>{t("custom_apis.private_key")}</p></div>+ {!initial && <div className="mt-7 border-t border-border/60 pt-5">+ <div className="flex items-center gap-2 text-sm font-medium text-foreground"><Check className="h-4 w-4 text-muted-foreground" />{t("custom_apis.automatic")}</div>+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{t("custom_apis.automatic_hint")}</p>+ </div>}+ </div>;}-function ApiRunner({ definition, onBack }: { definition: ApiDefinition; onBack: () => void }) {+function ConnectionDetails({ connection, onBack }: { connection: ApiConnection; onBack: () => void }) {const t = useT();- const [action, setAction] = useState(definition.actions[0].id);- const [argumentsText, setArgumentsText] = useState("{}");- const [result, setResult] = useState("");- const [downloadUrl, setDownloadUrl] = useState("");- const [error, setError] = useState("");- const [busy, setBusy] = useState(false);- return <section className="space-y-4">- <SoftButton disabled={busy} onClick={onBack}><ArrowLeft className="mr-2 h-4 w-4" />{t("custom_apis.title")}</SoftButton>- <h2 className="text-xl font-semibold text-foreground">{definition.name}</h2>- <p className="text-sm text-muted-foreground">{t("custom_apis.run_hint")}</p>- <Field label={t("custom_apis.action")}><BrandedSelect ariaLabel={t("custom_apis.action")} disabled={busy} className={fieldClass} value={action}- onValueChange={(value) => { setAction(value); setResult(""); setError(""); setDownloadUrl(""); }}- options={definition.actions.map((a) => ({ value: a.id, label: `${a.method} ${a.description}` }))} /></Field>- <Field label={t("custom_apis.arguments")}><textarea disabled={busy} className={`${fieldClass} font-mono`} rows={8} value={argumentsText} onChange={(e) => setArgumentsText(e.target.value)} /></Field>- <SoftButton disabled={busy} onClick={async () => {- setBusy(true); setError(""); setResult(""); setDownloadUrl("");- try {- let args: unknown;- try { args = JSON.parse(argumentsText); } catch { throw new Error(t("custom_apis.invalid_arguments")); }- const value = await customApiRequest<{ success: boolean; output: unknown; error?: string; artifacts?: string[] }>(`/${definition.id}/actions/${action}/run`, jsonRequest("POST", { arguments: args }));- if (!value.success) throw new Error(value.error || t("custom_apis.failed"));- const output = value.output as { download_url?: unknown } | null;- if (value.artifacts?.length && output && typeof output.download_url === "string"- && /^\/api\/outputs\/[a-zA-Z0-9_-]+\/files\/tasks\/api\/artifacts\/files\/[a-z0-9_]+\.[a-z0-9]+\/download$/.test(output.download_url)) setDownloadUrl(output.download_url);- setResult(JSON.stringify(value.output, null, 2));- } catch (e) { setError(e instanceof Error ? e.message : t("custom_apis.failed")); }- finally { setBusy(false); }- }}>{busy ? t("custom_apis.running") : t("custom_apis.run")}</SoftButton>- {error && <p role="alert" className="text-sm text-destructive">{error}</p>}- {downloadUrl && <a className="inline-flex items-center gap-2 text-sm text-primary underline" href={downloadUrl} download><Download className="h-4 w-4" />{t("custom_apis.download")}</a>}- {result && <pre role="status" className="max-h-80 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-secondary p-4 text-xs text-foreground">{result}</pre>}+ const [query, setQuery] = useState("");+ const actions = useQuery({ queryKey: ["api-capabilities", connection.id],+ queryFn: () => customApiRequest<{ total: number; actions: { id: string; description: string; risk_tier: string }[] }>(`/connections/${connection.id}/actions`), retry: false });+ const visible = (actions.data?.actions ?? []).filter((action) => action.description.toLowerCase().includes(query.toLowerCase()));+ return <section className="space-y-5">+ <BackLink label={t("custom_apis.title")} onClick={onBack} />+ <div className="flex items-center gap-4"><ConnectionLogo name={connection.name} brand={connection.brand_id} image={connection.logo_data} large />+ <div><h2 className="text-xl font-semibold text-foreground-strong">{connection.name}</h2><p className="mt-1 text-sm text-muted-foreground">{connection.action_count} {t("custom_apis.capabilities_count")}</p></div></div>+ <p className="text-sm leading-relaxed text-muted-foreground">{t("custom_apis.capabilities_hint")}</p>+ <label className="flex items-center gap-2 rounded-lg bg-secondary px-3 py-2.5 text-muted-foreground"><Search className="h-4 w-4" /><input type="search" aria-label={t("custom_apis.search_capabilities")} placeholder={t("custom_apis.search_capabilities")} value={query} onChange={(event) => setQuery(event.target.value)} className="min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none" /></label>+ {actions.isPending && <p role="status" className="text-sm text-muted-foreground">{t("custom_apis.loading")}</p>}+ {actions.error && <p role="alert" className="text-sm text-destructive">{t("custom_apis.failed")}</p>}+ <Panel><ul className="divide-y divide-border/60">{visible.map((action) => <li key={action.id} className="flex items-center gap-3 px-4 py-3 text-sm text-foreground">+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-foreground-faint" /><span>{action.description}</span>+ {action.risk_tier === "block" && <span className="ml-auto text-xs text-muted-foreground">{t("custom_apis.blocked")}</span>}+ </li>)}</ul></Panel>+ {connection.omitted_operations > 0 && <p className="text-xs text-muted-foreground">{t("custom_apis.partial_capabilities").replace("{count}", String(connection.omitted_operations))}</p>}+ <p className="flex items-center gap-2 text-xs text-muted-foreground"><Users className="h-3.5 w-3.5" />{t("custom_apis.inheritance")}</p></section>;}diff --git a/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsx b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsxindex 882c62d08b..f06175670a 100644--- a/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginUploadDialog.tsx@@ -1,10 +1,10 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { AlertTriangle, Check, Loader2, Plug, Upload, X } from "lucide-react";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";import { UploadDropzone, useUploadInputs } from "@/components/UploadDropzone";-import { useT } from "@/i18n";+import { useLocaleChunk, useT } from "@/i18n";import { collectDroppedFiles, formatBytes, type PickedFile } from "@/lib/filePicking";import {inspectPluginUpload,@@ -24,17 +24,24 @@ import {* The one thing it must not do is imply a review that never happened. An* uploaded plugin carries no publisher and no source URL, because there is* nothing here to vouch for either — and the dialog says so before the yes.+ *+ * With ``tabs`` it is the folder half of the shared "Add a plugin" dialog:+ * same title, same size, the connector/folder switch under the title.*/export function PluginUploadDialog({open,onClose,onInstalled,+ tabs,}: {open: boolean;onClose: () => void;onInstalled?: (id: string) => void;+ /** The connector/folder switch, rendered under the title. */+ tabs?: ReactNode;}) {const t = useT();+ useLocaleChunk("marketplace");const qc = useQueryClient();const [picked, setPicked] = useState<PickedFile[]>([]);const [report, setReport] = useState<PluginUploadReport | null>(null);@@ -119,25 +126,43 @@ export function PluginUploadDialog({void collectDroppedFiles(event.dataTransfer).then(inspect);}}>- <div className="flex max-h-full w-[640px] flex-col overflow-hidden rounded-lg border border-border bg-card">- <header className="flex items-start justify-between gap-4 border-b border-border px-6 py-4">- <div>- <h3 className="flex items-center gap-2 text-base font-semibold">- <Upload className="h-4 w-4 text-primary" />- {t("plugin_upload.title")}- </h3>- <p className="mt-1 text-sm text-muted-foreground">- {t("plugin_upload.subtitle")}- </p>- </div>- <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("common.cancel")}>- <X className="h-4 w-4" />- </Button>- </header>+ <div+ className="flex max-h-full w-[640px] max-w-full flex-col overflow-hidden rounded-lg border border-border bg-card shadow-float"+ data-testid="plugin-upload-dialog"+ >+ {tabs ? (+ <header className="px-6 pt-5">+ <div className="flex items-start justify-between gap-4">+ <h3 className="text-lg font-semibold tracking-tight text-foreground-strong">+ {t("custom_connector.dialog_title")}+ </h3>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("common.cancel")}>+ <X className="h-4 w-4" />+ </Button>+ </div>+ <div className="mt-3">{tabs}</div>+ </header>+ ) : (+ <header className="flex items-start justify-between gap-4 border-b border-border px-6 py-4">+ <div>+ <h3 className="flex items-center gap-2 text-base font-semibold">+ <Upload className="h-4 w-4 text-primary" />+ {t("plugin_upload.title")}+ </h3>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("plugin_upload.subtitle")}+ </p>+ </div>+ <Button size="sm" variant="ghost" onClick={onClose} aria-label={t("common.cancel")}>+ <X className="h-4 w-4" />+ </Button>+ </header>+ )}<ScrollArea className="min-h-0 flex-1"><div className="flex flex-col gap-4 px-6 py-5">{inputs}+ {tabs && <p className="text-sm text-muted-foreground">{t("plugin_upload.subtitle")}</p>}{picked.length === 0 ? (<UploadDropzonediff --git a/jarvis/ui/web/frontend/src/views/PluginsDialog.tsx b/jarvis/ui/web/frontend/src/views/PluginsDialog.tsxindex 67c1818512..e16a970a16 100644--- a/jarvis/ui/web/frontend/src/views/PluginsDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsDialog.tsx@@ -1,3 +1,4 @@+import { SectionWindowButton } from "@/components/layout/SectionWindowButton";import * as Dialog from "@radix-ui/react-dialog";import { useRef } from "react";import { X } from "lucide-react";@@ -11,14 +12,40 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";/** The catalog floats over the user's current work; nested setup stays inside. */export type PluginArea = "plugins" | "mcps" | "skills";-export function PluginsDialog({ onClose, area = "plugins", onAreaChange }: {+export function PluginsDialog({ onClose, area = "plugins", onAreaChange, standalone = false }: {onClose: () => void;area?: PluginArea;+ standalone?: boolean;onAreaChange?: (area: PluginArea) => void;}) {const t = useT();const content = useRef<HTMLDivElement>(null);const opener = useRef(document.activeElement);+ const tabs = (+ <Tabs defaultValue={area} value={onAreaChange ? area : undefined} onValueChange={(value) => onAreaChange?.(value as PluginArea)} className="flex min-h-0 flex-1 flex-col">+ <div className="mb-2 flex shrink-0 flex-wrap items-center justify-between gap-2 px-4 pt-3">+ <TabsList aria-label={t("nav.extensions")} className="w-fit">+ <TabsTrigger value="plugins">{t("nav.plugins")}</TabsTrigger>+ <TabsTrigger value="mcps">{t("nav.mcps")}</TabsTrigger>+ <TabsTrigger value="skills">{t("nav.skills")}</TabsTrigger>+ </TabsList>+ {!standalone && (+ <div className="ml-auto flex items-center gap-1">+ <SectionWindowButton />+ <Dialog.Close asChild>+ <button type="button" aria-label={t("common.close")} className="grid h-8 w-8 place-items-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <X className="h-4 w-4" aria-hidden />+ </button>+ </Dialog.Close>+ </div>+ )}+ </div>+ <TabsContent value="skills" className="mt-0 min-h-0 flex-1 overflow-hidden"><SkillsView /></TabsContent>+ <TabsContent value="plugins" className="mt-0 min-h-0 flex-1 overflow-hidden"><PluginsView inDialog /></TabsContent>+ <TabsContent value="mcps" className="mt-0 min-h-0 flex-1 overflow-hidden"><McpsView /></TabsContent>+ </Tabs>+ );+ if (standalone) return <div data-testid="plugin-catalog-window" className="flex h-full min-h-0 flex-col">{tabs}</div>;return (<Dialog.Root open onOpenChange={(open) => { if (!open) onClose(); }}><Dialog.Portal>@@ -63,21 +90,7 @@ export function PluginsDialog({ onClose, area = "plugins", onAreaChange }: {className="fixed left-1/2 top-1/2 z-40 flex h-[min(82dvh,780px)] w-[min(800px,calc(100vw-24px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl border border-border bg-popover text-foreground shadow-float outline-none [&_[aria-modal=true]]:overflow-y-auto"><Dialog.Title className="sr-only">{t("plugins_view.title")}</Dialog.Title>- <Dialog.Close asChild>- <button type="button" aria-label={t("common.close")} className="absolute right-3 top-3 z-10 grid h-8 w-8 place-items-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <X className="h-4 w-4" aria-hidden />- </button>- </Dialog.Close>- <Tabs defaultValue={area} value={onAreaChange ? area : undefined} onValueChange={(value) => onAreaChange?.(value as PluginArea)} className="flex min-h-0 flex-1 flex-col">- <TabsList aria-label={t("nav.extensions")} className="mx-6 mb-2 mt-4 w-fit shrink-0 self-start">- <TabsTrigger value="plugins">{t("nav.plugins")}</TabsTrigger>- <TabsTrigger value="mcps">{t("nav.mcps")}</TabsTrigger>- <TabsTrigger value="skills">{t("nav.skills")}</TabsTrigger>- </TabsList>- <TabsContent value="skills" className="mt-0 min-h-0 flex-1 overflow-hidden"><SkillsView /></TabsContent>- <TabsContent value="plugins" className="mt-0 min-h-0 flex-1 overflow-hidden"><PluginsView inDialog /></TabsContent>- <TabsContent value="mcps" className="mt-0 min-h-0 flex-1 overflow-hidden"><McpsView /></TabsContent>- </Tabs>+ {tabs}</Dialog.Content></Dialog.Portal></Dialog.Root>diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsxindex 2218f22f4b..64c9a857e1 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx@@ -17,14 +17,18 @@ import {X,Loader2,AlertTriangle,- Upload,Store,MoreHorizontal,ArrowRight,+ Link2,+ FolderUp,+ Trash2,} from "lucide-react";import { CommunityTab } from "@/views/PluginsCommunity";import { PluginUploadDialog } from "@/views/PluginUploadDialog";-import { fill, translate } from "@/i18n";+import { AddConnectorDialog, AddPluginTabs, type AddPluginMode } from "@/views/AddConnectorDialog";+import { removeAddedPlugin, takePluginFocus } from "@/lib/customConnector";+import { fill, translate, useLocaleChunk } from "@/i18n";import { ScrollArea } from "@/components/ui/scroll-area";import { BrandedSelect } from "@/components/ui/select";import {@@ -69,7 +73,8 @@ type AuthMode =| "oauth_pkce_loopback"| "instance_browser"| "local"- | "hosted_mcp_allowlist";+ | "hosted_mcp_allowlist"+ | "hosted_mcp_open";type PluginStatus = "not_connected" | "connected" | "needs_reauth" | "error";/** Deliberately a plain string, mirroring the backend. The catalog serves the@@ -160,6 +165,8 @@ interface CatalogPlugin {publisher?: string | null;version?: string | null;source_url?: string | null;+ /** Transport block; a custom connector's `url` is the server it reaches. */+ mcp_server?: { transport?: string; url?: string; [key: string]: unknown } | null;}interface CatalogResponse {@@ -266,6 +273,8 @@ export interface Plugin {selfUploaded: boolean;publisher?: string;sourceUrl?: string;+ /** Remote MCP address, shown for plugins the owner added by URL. */+ mcpUrl?: string;}function adapt(p: CatalogPlugin): Plugin {@@ -300,6 +309,7 @@ function adapt(p: CatalogPlugin): Plugin {selfUploaded: p.source === "local",publisher: p.publisher ?? undefined,sourceUrl: p.source_url ?? undefined,+ mcpUrl: typeof p.mcp_server?.url === "string" ? p.mcp_server.url : undefined,};}@@ -378,6 +388,7 @@ const AUTH_LABELS: Record<AuthMode, string> = {hosted_mcp_oauth_dcr: "One-Click",oauth_pkce_loopback: "Browser Login",hosted_mcp_allowlist: "Allowlist",+ hosted_mcp_open: "No sign-in",};// Provider families supporting an optional expert OAuth client override: use their@@ -585,7 +596,16 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {const [view, setView] = useState<"list" | "community" | "custom-apis">("list");const [selectedId, setSelectedId] = useState<string | null>(null);const [listFilter, setListFilter] = useState<ListFilter>(inDialog ? "recommended" : "all");- const [uploadOpen, setUploadOpen] = useState(false);+ // Which half of the "Add a plugin" dialog is open: a server URL or a folder.+ const [addMode, setAddMode] = useState<AddPluginMode | null>(null);+ const [removingPlugin, setRemovingPlugin] = useState<Plugin | null>(null);+ const pushToast = useEventStore((s) => s.pushToast);+ useLocaleChunk("marketplace");+ // Another surface (the composer's Add menu) asked for one plugin's page.+ useEffect(() => {+ const focus = takePluginFocus();+ if (focus) setSelectedId(focus);+ }, []);const [searchOpen, setSearchOpen] = useState(false);const [query, setQuery] = useState("");const [filter, setFilter] = useState<FilterId>("all");@@ -839,6 +859,7 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {}if (p.authMode === "hosted_mcp_oauth_dcr" ||+ p.authMode === "hosted_mcp_open" ||p.authMode === "local" ||p.authMode === "oauth_device_flow" ||p.authMode === "oauth_pkce_loopback"@@ -898,7 +919,8 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {p.status === "connected" ||p.status === "needs_reauth" ||p.status === "error" ||- p.fromMarketplace,+ p.fromMarketplace ||+ p.selfUploaded,),[allPlugins],);@@ -969,15 +991,43 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {</div></div>)}+ <AddConnectorDialog+ open={addMode === "connector"}+ onClose={() => setAddMode(null)}+ tabs={<AddPluginTabs mode="connector" onChange={setAddMode} />}+ onAdded={(result) => {+ setAddMode(null);+ pushToast(+ "success",+ fill(translate("custom_connector.added"), { name: result.plugin.display_name }),+ );+ void handleFreshInstall(result.plugin.id);+ }}+ /><PluginUploadDialog- open={uploadOpen}- onClose={() => setUploadOpen(false)}+ open={addMode === "folder"}+ onClose={() => setAddMode(null)}+ tabs={<AddPluginTabs mode="folder" onChange={setAddMode} />}onInstalled={(id) => {- setUploadOpen(false);+ setAddMode(null);void handleFreshInstall(id);}}/>+ {removingPlugin && (+ <RemovePluginDialog+ plugin={removingPlugin}+ onCancel={() => setRemovingPlugin(null)}+ onRemoved={() => {+ const name = removingPlugin.name;+ setRemovingPlugin(null);+ setSelectedId(null);+ pushToast("success", fill(translate("custom_connector.removed"), { name }));+ void qc.refetchQueries({ queryKey: ["marketplace-plugins"] });+ }}+ />+ )}+{connectingPlugin && (<PatConnectDialogplugin={connectingPlugin}@@ -1090,7 +1140,7 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {<div className="flex h-full min-h-0 flex-col bg-transparent">{inDialog && view === "list" && !selectedId ? content : (<ScrollArea className="flex-1">- <div className={cn("mx-auto w-full max-w-4xl px-8 py-6", inDialog && "pt-12")}>{content}</div>+ <div className={cn("mx-auto w-full max-w-4xl px-8 py-6", inDialog && (view === "custom-apis" ? "px-6 pt-5" : "pt-12"))}>{content}</div></ScrollArea>)}{dialogs}@@ -1125,6 +1175,7 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {plugin={selectedPlugin}onConnect={handleConnect}onDisconnect={handleDisconnect}+ onRemove={setRemovingPlugin}/>) : (<p className="mt-6 text-sm text-muted-foreground">@@ -1155,7 +1206,7 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {onCategory={(value) => { setFilter(value); setListFilter("all"); }}loading={isLoading} error={error instanceof Error ? error.message : null}refreshing={isFetching} onRefresh={() => void refetch()}- onBrowse={() => setView("community")} onUpload={() => setUploadOpen(true)}+ onBrowse={() => setView("community")} onAdd={setAddMode}onCustomApis={() => setView("custom-apis")}onOpen={setSelectedId} onConnect={handleConnect} onDisconnect={handleDisconnect}onReset={() => { resetFilters(); setListFilter("all"); }}@@ -1192,16 +1243,23 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {<ActionMenulabel={translate("plugins_view.add")}actions={[+ {+ id: "connector",+ label: translate("custom_connector.menu_connector"),+ icon: <Link2 className="h-3.5 w-3.5" />,+ onSelect: () => setAddMode("connector"),+ },{id: "upload",- label: translate("plugins_view.add_upload"),- icon: <Upload className="h-3.5 w-3.5" />,- onSelect: () => setUploadOpen(true),+ label: translate("custom_connector.menu_folder"),+ icon: <FolderUp className="h-3.5 w-3.5" />,+ onSelect: () => setAddMode("folder"),},{id: "community",label: translate("plugins_view.add_community"),icon: <Store className="h-3.5 w-3.5" />,+ separatorAbove: true,onSelect: () => setView("community"),},{@@ -1321,13 +1379,13 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {function PluginWindowCatalog({plugins, installed, total, listFilter, onListFilter, query, onQuery,category, categories, onCategory, loading, error, refreshing, onRefresh,- onBrowse, onUpload, onCustomApis, onOpen, onConnect, onDisconnect, onReset, attention, subtitle,+ onBrowse, onAdd, onCustomApis, onOpen, onConnect, onDisconnect, onReset, attention, subtitle,}: {plugins: Plugin[]; installed: Plugin[]; total: number; listFilter: ListFilter;onListFilter: (value: ListFilter) => void; query: string; onQuery: (value: string) => void;category: string; categories: string[]; onCategory: (value: string) => void;loading: boolean; error: string | null; refreshing: boolean; onRefresh: () => void;- onBrowse: () => void; onUpload: () => void; onOpen: (id: string) => void;+ onBrowse: () => void; onAdd: (mode: AddPluginMode) => void; onOpen: (id: string) => void;onCustomApis: () => void;onReset: () => void; attention: number; subtitle: string;} & ConnectHandlers) {@@ -1352,9 +1410,28 @@ function PluginWindowCatalog({</IconButton><SoftButton onClick={onBrowse}>{translate("plugins_view.browse")}</SoftButton><SoftButton onClick={onCustomApis}>{translate("custom_apis.title")}</SoftButton>- <IconButton label={translate("plugins_view.add_upload")} onClick={onUpload}>- <Plus className="h-4 w-4" />- </IconButton>+ <ActionMenu+ label={translate("plugins_view.add")}+ actions={[+ {+ id: "connector",+ label: translate("custom_connector.menu_connector"),+ icon: <Link2 className="h-3.5 w-3.5" />,+ onSelect: () => onAdd("connector"),+ },+ {+ id: "upload",+ label: translate("custom_connector.menu_folder"),+ icon: <FolderUp className="h-3.5 w-3.5" />,+ onSelect: () => onAdd("folder"),+ },+ ]}+ trigger={({ open, toggle }) => (+ <IconButton label={translate("plugins_view.add")} onClick={toggle} active={open}>+ <Plus className="h-4 w-4" />+ </IconButton>+ )}+ /></div></div><p className="sr-only">{subtitle}</p>@@ -1623,7 +1700,12 @@ async function fetchPluginFiles(pluginId: string): Promise<{ files: CardFile[] }return res.json();}-function PluginDetail({ plugin, onConnect, onDisconnect }: { plugin: Plugin } & ConnectHandlers) {+function PluginDetail({+ plugin,+ onConnect,+ onDisconnect,+ onRemove,+}: { plugin: Plugin; onRemove?: (plugin: Plugin) => void } & ConnectHandlers) {const { busy, run } = useConnectLock(() => onConnect(plugin));const filesQuery = useQuery({queryKey: ["marketplace-plugin-files", plugin.id],@@ -1656,6 +1738,20 @@ function PluginDetail({ plugin, onConnect, onDisconnect }: { plugin: Plugin } &},]: []),+ // A plugin the owner added (URL, folder or community install) can leave+ // again; a built-in one can only be disconnected.+ ...(onRemove && (plugin.selfUploaded || plugin.fromMarketplace)+ ? [+ {+ id: "remove",+ label: translate("custom_connector.remove"),+ icon: <Trash2 className="h-3.5 w-3.5" />,+ destructive: true,+ separatorAbove: Boolean(plugin.sourceUrl) || connected || needsReconnect,+ onSelect: () => onRemove(plugin),+ },+ ]+ : []),];return (@@ -1780,6 +1876,13 @@ function PluginDetail({ plugin, onConnect, onDisconnect }: { plugin: Plugin } &: "Browser sign-in is pending publisher setup. No developer setup is required from you.": null,},+ {+ label: translate("custom_connector.fact_server"),+ value:+ plugin.selfUploaded && plugin.mcpUrl ? (+ <code className="break-all font-mono text-meta">{plugin.mcpUrl}</code>+ ) : null,+ },{ label: translate("plugins_view.fact_publisher"), value: plugin.publisher ?? null },{label: translate("plugins_view.fact_source"),@@ -2945,6 +3048,90 @@ function DisconnectConfirmDialog({);}+/** "Remove {name}?" for a plugin the owner added: drops the catalog entry,+ * its stored sign-in and its tools. Built-in plugins never reach here. */+function RemovePluginDialog({+ plugin,+ onCancel,+ onRemoved,+}: {+ plugin: Plugin;+ onCancel: () => void;+ onRemoved: () => void;+}) {+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !pending) onCancel();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onCancel, pending]);++ const remove = async () => {+ setPending(true);+ setError(null);+ try {+ await removeAddedPlugin(plugin.id);+ onRemoved();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setPending(false);+ }+ };++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="remove-plugin-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/70 backdrop-blur-sm"+ onClick={(e) => {+ if (e.target === e.currentTarget && !pending) onCancel();+ }}+ >+ <div className="relative w-full max-w-sm overflow-hidden rounded-lg bg-popover shadow-float">+ <header className="flex items-center gap-3 border-b border-border px-5 py-4">+ <BrandTile plugin={plugin} />+ <h2 id="remove-plugin-title" className="font-display text-base font-semibold tracking-tight">+ {fill(translate("custom_connector.remove_title"), { name: plugin.name })}+ </h2>+ </header>+ <div className="px-5 py-5">+ <p className="text-sm leading-relaxed text-muted-foreground">+ {translate("custom_connector.remove_body")}+ </p>+ {error && (+ <div role="alert" className="mt-3 rounded-md bg-secondary px-3 py-2 text-xs text-destructive">+ {error}+ </div>+ )}+ </div>+ <footer className="flex items-center justify-end gap-2 border-t border-border px-5 py-3">+ <button+ type="button"+ onClick={onCancel}+ disabled={pending}+ className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30"+ >+ {translate("common.cancel")}+ </button>+ <button+ type="button"+ onClick={() => void remove()}+ disabled={pending}+ className="inline-flex items-center gap-1.5 rounded-md bg-destructive px-3.5 py-1.5 text-xs font-semibold text-destructive-foreground transition-all hover:bg-destructive/90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {pending && <Loader2 className="h-3 w-3 animate-spin" />}+ {translate("custom_connector.remove")}+ </button>+ </footer>+ </div>+ </div>+ );+}+// ---------------------------------------------------------------------------// Pat-Paste Connect Dialog — used by Vercel & Supabase. Opens the token-// creation page in a new tab, takes a paste, sends it to the backend.@@ -3145,6 +3332,7 @@ export function PatConnectDialog({{notice}</p>)}+ {auth.token_creation_url ? (<Stepnum={1}title={`Generate a token at ${plugin.name}`}@@ -3170,6 +3358,11 @@ export function PatConnectDialog({/></div></Step>+ ) : (+ // A custom connector: no page is known that issues its key, so+ // the step only says which key and where it goes.+ <Step num={1} title={`Get the key for ${plugin.name}`} body={auth.instruction_md} />+ )}{instanceField && (<Step num={2} title={instanceField.label} body={instanceField.help_md ?? undefined}>@@ -3318,7 +3511,7 @@ function Step({num: number;title: string;body?: string;- children: React.ReactNode;+ children?: React.ReactNode;}) {return (<div className="flex gap-3">diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsxindex c05726a54f..0fc0115a8b 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx@@ -9,6 +9,8 @@ import type { SectionHealth } from "@/hooks/useProviders";const { mockState } = vi.hoisted(() => ({mockState: {activeSection: "settings" as string,+ solo: false,+ detachedViews: [],setActiveSection: vi.fn(),},}));diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsxindex 22af4eec90..82a8008246 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx@@ -1,4 +1,5 @@import * as Dialog from "@radix-ui/react-dialog";+import { SectionWindowButton } from "@/components/layout/SectionWindowButton";import { isTourEvent } from "@/components/onboarding/tourEvents";import { lazy, Suspense, useEffect, useMemo, useRef, useState, type ComponentType, type LazyExoticComponent } from "react";import { Loader2, Search, X } from "lucide-react";@@ -209,6 +210,7 @@ export function SettingsHubView() {const t = useT();const language = useUiLanguage();const active = useEventStore((s) => s.activeSection);+ const solo = useEventStore((s) => s.solo);const setActive = useEventStore((s) => s.setActiveSection);const [query, setQuery] = useState("");const [searchTarget, setSearchTarget] = useState<string | null>(null);@@ -302,9 +304,12 @@ export function SettingsHubView() {<div className="px-3 pb-1 pt-3">{/* No way-out row of its own: the caption's back arrow and Escapeleave the page, so the heading opens the nav. */}- <p className="px-2.5 pb-3 pt-1 font-display text-lg font-semibold text-foreground-strong">- {t("nav.settings")}- </p>+ <div className="flex flex-wrap items-center justify-between gap-1 pb-3">+ <p className="px-2.5 pt-1 font-display text-lg font-semibold text-foreground-strong">+ {t("nav.settings")}+ </p>+ {!solo && <SectionWindowButton />}+ </div><div className="relative"><Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" aria-hidden /><input type="text" role="searchbox" data-testid="settings-hub-search" value={query} onChange={(event) => setQuery(event.target.value)}diff --git a/jarvis/ui/web/frontend/src/views/computers/ComputerDetail.tsx b/jarvis/ui/web/frontend/src/views/computers/ComputerDetail.tsxindex 6fe8972b9b..d11a606893 100644--- a/jarvis/ui/web/frontend/src/views/computers/ComputerDetail.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/ComputerDetail.tsx@@ -21,6 +21,7 @@ import {import { BackLink, FactRows, Panel, SegmentedFilter } from "@/components/extensions/primitives";import { Button } from "@/components/ui/button";import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { MachineIcon, wearsMachineGlyph } from "./machineKind";import {useCheckComputer,useIdentity,@@ -32,6 +33,7 @@ import { cn } from "@/lib/utils";import { computersApi, type CommandResult, type Computer } from "@/lib/computersApi";import { AccessPanel } from "./AccessPanel";import { AgentReadiness } from "./AgentReadiness";+import { GithubAccess } from "./GithubAccess";import { statusLabel } from "./ComputerRow";import {CopyField,@@ -512,7 +514,13 @@ export function ComputerDetail({<header className="flex flex-col gap-4 md:flex-row md:items-start"><div className="flex min-w-0 flex-1 items-start gap-4">- <ProviderLogo providerId={computer.provider} label={computer.name} className="h-12 w-12" />+ {wearsMachineGlyph(computer.provider) ? (+ <span aria-hidden className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-secondary">+ <MachineIcon computer={computer} className="h-5 w-5 text-muted-foreground" />+ </span>+ ) : (+ <ProviderLogo providerId={computer.provider} label={computer.name} className="h-12 w-12" />+ )}<div className="min-w-0 flex-1">{renaming ? (<input@@ -666,7 +674,12 @@ export function ComputerDetail({{tab === "console" && <Console computer={computer} />}{tab === "access" && <AccessPanel computer={computer} />}- {tab === "agents" && <AgentReadiness computer={computer} />}+ {tab === "agents" && (+ <div className="space-y-4">+ <AgentReadiness computer={computer} />+ <GithubAccess computer={computer} />+ </div>+ )}</div>);}diff --git a/jarvis/ui/web/frontend/src/views/computers/ComputerRow.tsx b/jarvis/ui/web/frontend/src/views/computers/ComputerRow.tsxindex 63f0f32d6f..f4264ff8a1 100644--- a/jarvis/ui/web/frontend/src/views/computers/ComputerRow.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/ComputerRow.tsx@@ -1,27 +1,36 @@/**- * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web EnvironmentRow),- * MIT License, Copyright (c) 2026 T3 Tools Inc. Full text:- * third_party/t3code/LICENSE.+ * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web EnvironmentRow,+ * SavedBackendListRow: a dimmed switched-off row, a routes toggle in the+ * subtitle, the status tooltip), MIT License, Copyright (c) 2026 T3 Tools Inc.+ * Full text: third_party/t3code/LICENSE.*- * One machine in the grouped list: its glyph, its name and ONE subtitle line- * (how it is reached, its state, its system), then any tight vital, the- * status dot and a chevron. The whole row opens the detail page.+ * One machine in the grouped list: the glyph of its kind, its name and ONE+ * subtitle line (how it is reached, its state, its system), then any tight+ * vital, its status dot, the on/off switch and a chevron. The name opens the+ * detail page; "N addresses" unfolds the routes under the row.*/-import { ChevronRight, Loader2 } from "lucide-react";-import { ComputersIcon } from "@/components/icons/sectionIcons";-import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { useState } from "react";+import { Check, ChevronRight, Copy } from "lucide-react";+import { Switch } from "@/components/ui/switch";+import { QuickTooltip } from "@/components/ui/tooltip";+import { useUpdateComputer } from "@/hooks/useComputers";import { useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";-import type { Computer } from "@/lib/computersApi";-import { formatMemory, loadPct, statusTone } from "./parts";+import type { Computer, RouteSuggestion } from "@/lib/computersApi";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { MachineIcon, wearsMachineGlyph } from "./machineKind";+import { formatAgo, formatMemory, loadPct, statusTone } from "./parts";+import { RouteList } from "./RouteList";import { StatusDot } from "./surface";export function statusLabel(computer: Computer, t: (k: string) => string): string {return t(`computers.status_${computer.health.status}`);}-/** Providers without a brand mark of their own wear the section's cloud. */-const CLOUD_MARK_PROVIDERS = new Set(["generic", "home_server", "strato"]);+function fill(template: string, values: Record<string, string>): string {+ return template.replace(/\{(\w+)\}/g, (_m, key: string) => values[key] ?? "");+}/** A vital earns a place in the row only once it gets tight. */const TIGHT_PCT = 75;@@ -30,20 +39,29 @@ export function ComputerRow({computer,checking,onOpen,+ suggestions = [],}: {computer: Computer;checking: boolean;onOpen: () => void;+ /** Tailscale addresses this computer could add. */+ suggestions?: RouteSuggestion[];}) {const t = useT();+ const update = useUpdateComputer();+ const [routesOpen, setRoutesOpen] = useState(false);+ const [copied, setCopied] = useState(false);const { facts, health } = computer;- const online = health.status === "online";- const tone = statusTone(health.status);- const busy = checking || computer.busy;+ const enabled = computer.enabled !== false;+ const online = enabled && health.status === "online";+ const tone = enabled ? statusTone(health.status) : "off";+ const busy = enabled && (checking || computer.busy);const login = `${computer.username}@${computer.host === "0.0.0.0" ? "…" : computer.host}${computer.port !== 22 ? `:${computer.port}` : ""}`;- const status = [statusLabel(computer, t), online && health.latency_ms !== null ? `${health.latency_ms} ms` : null]- .filter(Boolean)- .join(" ");+ const status = enabled+ ? [statusLabel(computer, t), online && health.latency_ms !== null ? `${health.latency_ms} ms` : null]+ .filter(Boolean)+ .join(" ")+ : t("computers.row_switched_off");const system = [facts?.os_name,facts?.cpu_count ? `${facts.cpu_count} ${t("computers.unit_cpu")}` : null,@@ -58,47 +76,120 @@ export function ComputerRow({{ label: t("computers.meter_disk"), pct: health.disk_used_pct },].filter((v): v is { label: string; pct: number } => v.pct !== null && v.pct >= TIGHT_PCT): [];+ // A backend from before routes and the switch sends neither field: it would+ // ignore both controls, so they appear only once it understands them.+ const modern = computer.routes !== undefined;+ const routeCount = computer.routes?.length ?? 1;+ const showRoutes = modern && computer.kind !== "local_vm";+ const failed = enabled && !online && Boolean(health.trace_id);+ const tooltip = [+ enabled && health.message && !online ? health.message : status,+ health.checked_at ? fill(t("computers.status_last_check"), { ago: formatAgo(health.checked_at, t) }) : null,+ failed && health.trace_id ? fill(t("computers.status_error_id"), { id: health.trace_id }) : null,+ ]+ .filter(Boolean)+ .join(" · ");return (- <button- type="button"- onClick={onOpen}- data-testid={`computer-row-${computer.id}`}- className="group grid w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 px-3 py-2.5 text-left transition-colors hover:bg-secondary/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:px-4"- >- {CLOUD_MARK_PROVIDERS.has(computer.provider) ? (- <ComputersIcon aria-hidden className="h-4 w-4 text-muted-foreground" />- ) : (- <ProviderLogo providerId={computer.provider} label={computer.name} size="sm" />- )}- <span className="min-w-0">- <span className="block truncate text-base font-medium text-foreground">{computer.name}</span>- <span className="block truncate text-xs text-muted-foreground">- <span className="font-mono">SSH {login}</span>- <span aria-hidden> · </span>- <span className={cn(tone === "error" && "text-destructive", tone === "warn" && "text-warning")}>{status}</span>- {system && <span> · {system}</span>}- </span>- </span>- <span className="flex shrink-0 items-center gap-2.5">- {tight.map((v) => (- <span- key={v.label}- className={cn("hidden text-xs tabular-nums sm:inline", v.pct >= 90 ? "text-destructive" : "text-warning")}- >- {v.label} {Math.round(Math.min(100, v.pct))} %+ <div data-testid={`computer-item-${computer.id}`} data-enabled={enabled}>+ <div className="group grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 px-3 py-2.5 transition-colors hover:bg-secondary/50 sm:px-4">+ <button+ type="button"+ onClick={onOpen}+ data-testid={`computer-row-${computer.id}`}+ className={cn(+ "flex min-w-0 items-center gap-3 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ !enabled && "opacity-60",+ )}+ >+ {wearsMachineGlyph(computer.provider) ? (+ <MachineIcon computer={computer} aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ ) : (+ <ProviderLogo providerId={computer.provider} label={computer.name} size="sm" />+ )}+ <span className="min-w-0">+ <span className="block truncate text-base font-medium text-foreground">{computer.name}</span>+ <span className="block truncate text-xs text-muted-foreground">+ <span className="font-mono">SSH {login}</span>+ <span aria-hidden> · </span>+ <span className={cn(tone === "error" && "text-destructive", tone === "warn" && "text-warning")}>{status}</span>+ {system && <span> · {system}</span>}+ </span></span>- ))}- {busy ? (- <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" aria-hidden />- ) : (- <StatusDot tone={tone} label={status} />- )}- <ChevronRight- aria-hidden- className="h-4 w-4 text-foreground-faint transition-transform group-hover:translate-x-0.5 group-hover:text-foreground"- />- </span>- </button>+ </button>+ <span className="flex shrink-0 items-center gap-2.5">+ {tight.map((v) => (+ <span+ key={v.label}+ className={cn("hidden text-xs tabular-nums md:inline", v.pct >= 90 ? "text-destructive" : "text-warning")}+ >+ {v.label} {Math.round(Math.min(100, v.pct))} %+ </span>+ ))}+ {showRoutes && (+ <button+ type="button"+ aria-expanded={routesOpen}+ onClick={() => setRoutesOpen((open) => !open)}+ data-testid={`computer-routes-toggle-${computer.id}`}+ className="inline-flex items-center gap-0.5 rounded-sm text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ >+ {routeCount === 1+ ? t("computers.row_routes_one")+ : fill(t("computers.row_routes_many"), { count: String(routeCount) })}+ {suggestions.length > 0 && <span aria-hidden className="ml-1 h-1.5 w-1.5 rounded-full bg-accent" />}+ <ChevronRight+ aria-hidden+ className={cn("h-3 w-3 transition-transform motion-reduce:transition-none", routesOpen && "rotate-90")}+ />+ </button>+ )}+ {failed && health.trace_id && (+ <button+ type="button"+ aria-label={copied ? t("computers.copied_error_id") : t("computers.copy_error_id")}+ onClick={() => {+ void robustCopy(health.trace_id ?? "").then((ok) => {+ if (!ok) return;+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1600);+ });+ }}+ className="rounded p-0.5 text-foreground-faint hover:bg-secondary hover:text-foreground"+ data-testid={`computer-copy-error-${computer.id}`}+ >+ {copied ? <Check className="h-3.5 w-3.5 text-success" /> : <Copy className="h-3.5 w-3.5" />}+ </button>+ )}+ <QuickTooltip content={tooltip} side="top" className="inline-flex">+ {/* A check in flight pings the dot instead of swapping it for a spinner. */}+ <StatusDot tone={busy ? "busy" : tone} label={status} />+ </QuickTooltip>+ {modern && (+ <Switch+ checked={enabled}+ disabled={update.isPending}+ onCheckedChange={(next) => update.mutate({ id: computer.id, patch: { enabled: next } })}+ aria-label={fill(t("computers.row_switch_label"), { computer: computer.name })}+ data-testid={`computer-switch-${computer.id}`}+ />+ )}+ <button+ type="button"+ tabIndex={-1}+ aria-hidden+ onClick={onOpen}+ className="text-foreground-faint transition-transform group-hover:translate-x-0.5 group-hover:text-foreground"+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ </span>+ </div>+ {showRoutes && routesOpen && (+ <div className="pl-10 pr-3 sm:pl-11 sm:pr-4">+ <RouteList computer={computer} suggestions={suggestions} />+ </div>+ )}+ </div>);}diff --git a/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx b/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsxindex 130777f646..85f5ed5020 100644--- a/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/ConnectDialog.tsx@@ -52,6 +52,7 @@ import { CopyField, Field, inputClass } from "./parts";import { ApiImportStep } from "./wizard/ApiImportStep";import { LocalVmStep } from "./wizard/LocalVmStep";import { errorText } from "./wizard/shared";+import { KnownHosts } from "./KnownHosts";import { ServerAddressForm } from "./ServerAddressForm";type Screen = { kind: "form" } | { kind: "check" } | { kind: "account"; provider: ProviderInfo } | { kind: "vm" };@@ -141,6 +142,10 @@ export function ConnectDialog({const [name, setName] = useState("");const [username, setUsername] = useState("");const [port, setPort] = useState("");+ // A host picked from this PC's ~/.ssh/config: its alias lets the automatic+ // login offer the key file the config names, as long as that host is still+ // the one in the box.+ const [picked, setPicked] = useState<{ alias: string; host: string } | null>(null);const [keepPassword, setKeepPassword] = useState(false);const [keyError, setKeyError] = useState<string | null>(null);const [promptCopied, setPromptCopied] = useState(false);@@ -245,6 +250,7 @@ export function ConnectDialog({private_key: login === "private_key" ? keyText : undefined,passphrase: login === "private_key" && passphrase ? passphrase : undefined,provider: "generic",+ ssh_alias: login === "auto" && picked?.host === detected.host ? picked.alias : undefined,};let state = startCheck();const show = (next: CheckState) => {@@ -423,7 +429,7 @@ export function ConnectDialog({/>)}- {screen.kind === "form" && <div id="cx-server-panel" hidden={connectionType !== "server"}><ServerAddressForm /></div>}+ {screen.kind === "form" && <div id="cx-server-panel" hidden={connectionType !== "server"}><ServerAddressForm onConnected={onClose} /></div>}{screen.kind === "form" && (<form@@ -435,6 +441,16 @@ export function ConnectDialog({void connect();}}>+ <KnownHosts+ selected={picked?.host === detected.host ? picked?.alias : null}+ onPick={(host) => {+ setPicked({ alias: host.alias, host: host.host });+ setPasted(host.host);+ setUsername(host.username ?? "");+ setPort(host.port !== 22 ? String(host.port) : "");+ setName(host.alias);+ }}+ /><div><Field label={t("computers.cx_ssh_host")}><textareadiff --git a/jarvis/ui/web/frontend/src/views/computers/GithubAccess.tsx b/jarvis/ui/web/frontend/src/views/computers/GithubAccess.tsxnew file mode 100644index 0000000000..b7b880b896--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/GithubAccess.tsx@@ -0,0 +1,85 @@+/**+ * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+ * GitHubRoutingSettings.tsx: per-machine GitHub sharing with the trust+ * warning as the first line next to the control), MIT License, Copyright (c)+ * 2026 T3 Tools Inc. Full text: third_party/t3code/LICENSE.+ *+ * "GitHub for the agents here": on an explicit click, this PC's GitHub login+ * is shared with the coding agents on this computer, so they can clone and+ * push while this PC is off (backend: ``jarvis.computers.github_access``).+ */+import { Check, GitBranch, Loader2, ShieldAlert } from "lucide-react";+import { Panel } from "@/components/extensions/primitives";+import { Button } from "@/components/ui/button";+import { useGithubShare } from "@/hooks/useComputers";+import { useT } from "@/i18n";+import type { Computer } from "@/lib/computersApi";+import { formatAgo } from "./parts";++function fill(template: string, values: Record<string, string>): string {+ return template.replace(/\{(\w+)\}/g, (_m, key: string) => values[key] ?? "");+}++export function GithubAccess({ computer }: { computer: Computer }) {+ const t = useT();+ const github = useGithubShare();+ // A backend from before GitHub sharing does not send the field: nothing to offer yet.+ if (computer.github_shared_at === undefined) return null;+ const shared = computer.github_shared_at != null;+ const reachable = computer.enabled !== false && computer.health.status === "online";+ const error = github.error instanceof Error ? github.error.message : null;++ return (+ <div data-testid="computer-github">+ <Panel className="p-5">+ <div className="flex items-start gap-3">+ <GitBranch aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1 space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h3 className="text-base font-semibold text-foreground-strong">{t("computers.github_title")}</h3>+ <div className="flex items-center gap-2">+ {shared && (+ <Button+ variant="ghost"+ size="sm"+ disabled={!reachable || github.isPending}+ onClick={() => github.mutate({ id: computer.id, share: false })}+ data-testid="computer-github-unshare"+ >+ {t("computers.github_unshare")}+ </Button>+ )}+ <Button+ variant="outline"+ size="sm"+ disabled={!reachable || github.isPending}+ onClick={() => github.mutate({ id: computer.id, share: true })}+ data-testid="computer-github-share"+ >+ {github.isPending && <Loader2 className="animate-spin" />}+ {shared ? t("computers.github_refresh") : t("computers.github_share")}+ </Button>+ </div>+ </div>+ <p className="text-sm text-muted-foreground">{t("computers.github_body")}</p>+ <p className="flex items-start gap-1.5 text-xs text-warning">+ <ShieldAlert aria-hidden className="mt-px h-3.5 w-3.5 shrink-0" />+ {t("computers.github_warning")}+ </p>+ {shared && computer.github_shared_at && (+ <p className="flex items-center gap-1.5 text-xs text-success">+ <Check aria-hidden className="h-3.5 w-3.5" />+ {fill(t("computers.github_shared"), { ago: formatAgo(computer.github_shared_at, t) })}+ </p>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ </div>+ </div>+ </Panel>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/KeepWorking.tsx b/jarvis/ui/web/frontend/src/views/computers/KeepWorking.tsxindex cf1bc69ba6..40adf5a2d1 100644--- a/jarvis/ui/web/frontend/src/views/computers/KeepWorking.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/KeepWorking.tsx@@ -67,6 +67,7 @@ export function KeepWorking({ computers }: { computers: Computer[] }) {{ value: OFF, label: t("computers.keep_off") },...computers.filter((computer) => computer.health.status !== "provisioning" && !isWindows(computer))+ .filter((computer) => computer.enabled !== false || computer.id === value).map((computer) => ({ value: computer.id, label: computer.name })),];diff --git a/jarvis/ui/web/frontend/src/views/computers/KnownHosts.tsx b/jarvis/ui/web/frontend/src/views/computers/KnownHosts.tsxnew file mode 100644index 0000000000..c448b920a8--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/KnownHosts.tsx@@ -0,0 +1,85 @@+/**+ * "Known on this PC": the servers this PC's own ssh already knows, offered at+ * the top of the add dialog (backend: ``jarvis.computers.ssh_config``). A+ * click fills the form — address, login, port — and remembers the alias, so+ * the automatic login also offers the key file ``~/.ssh/config`` names for it.+ */+import { KeyRound, TerminalSquare } from "lucide-react";+import { useSshHosts } from "@/hooks/useComputers";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { SshConfigHost } from "@/lib/computersApi";++/** At most this many: a long known_hosts is history, not a menu. */+const MAX_SHOWN = 8;++export function KnownHosts({+ onPick,+ selected,+}: {+ onPick: (host: SshConfigHost) => void;+ /** The alias currently filled into the form. */+ selected?: string | null;+}) {+ const t = useT();+ const hosts = useSshHosts(true);+ const rows = (hosts.data ?? []).slice(0, MAX_SHOWN);+ if (rows.length === 0) return null;++ return (+ <section aria-labelledby="cx-known-title" data-testid="cx-known-hosts" className="space-y-2">+ <div>+ <h3 id="cx-known-title" className="text-sm font-medium text-foreground-secondary">+ {t("computers.known_title")}+ </h3>+ <p className="text-xs text-muted-foreground">{t("computers.known_body")}</p>+ </div>+ <ul className="overflow-hidden rounded-lg border border-border [&>li+li]:border-t [&>li+li]:border-border">+ {rows.map((host) => {+ const blocked = host.needs_proxy || Boolean(host.added_as);+ const note = host.needs_proxy+ ? t("computers.known_proxy")+ : host.added_as+ ? t("computers.known_added")+ : host.source === "ssh_config"+ ? t("computers.known_from_config")+ : t("computers.known_from_history");+ return (+ <li key={`${host.alias}:${host.port}`}>+ <button+ type="button"+ disabled={blocked}+ onClick={() => onPick(host)}+ aria-pressed={selected === host.alias}+ data-testid={`cx-known-${host.alias}`}+ className={cn(+ "flex w-full items-center gap-3 px-3 py-2 text-left transition-colors",+ "hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ "disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent",+ selected === host.alias && "bg-accent-soft",+ )}+ >+ <TerminalSquare aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">{host.alias}</span>+ {/* A known_hosts entry IS its address: the second line would repeat it. */}+ {(host.alias !== host.host || host.username || host.port !== 22) && (+ <span className="block truncate font-mono text-xs text-muted-foreground">+ {host.username ? `${host.username}@` : ""}+ {host.host}+ {host.port !== 22 ? `:${host.port}` : ""}+ </span>+ )}+ </span>+ {host.has_identity_file && !blocked && (+ <KeyRound aria-label={t("computers.known_key")} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ )}+ <span className="shrink-0 text-xs text-foreground-faint">{note}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/PairedServers.tsx b/jarvis/ui/web/frontend/src/views/computers/PairedServers.tsxnew file mode 100644index 0000000000..3c28436209--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/PairedServers.tsx@@ -0,0 +1,74 @@+import { useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { ExternalLink, Loader2, RefreshCw, Unplug } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";+import { pairedServersApi } from "@/lib/computersApi";+import { openExternalUrl } from "@/lib/openExternal";+import { Section } from "./surface";+import { errorText } from "./wizard/shared";++export const pairedServerKey = ["computers", "paired-servers"] as const;++export function usePairedServers() {+ return useQuery({ queryKey: pairedServerKey, queryFn: pairedServersApi.list, retry: false });+}++export function PairedServers() {+ const t = useT();+ const queryClient = useQueryClient();+ const servers = usePairedServers();+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [openingLink, setOpeningLink] = useState<string | null>(null);+ const acting = useRef(false);++ async function act(id: string, action: "open" | "check" | "remove") {+ if (acting.current) return;+ acting.current = true;+ setBusy(id);+ setError(null);+ setOpeningLink(null);+ try {+ if (action === "open") {+ const result = await pairedServersApi.open(id);+ // Keep a clickable fallback for browsers that block asynchronous popups.+ if (!await openExternalUrl(result.url)) setOpeningLink(result.url);+ } else {+ if (action === "check") await pairedServersApi.check(id);+ else await pairedServersApi.remove(id);+ await queryClient.invalidateQueries({ queryKey: pairedServerKey });+ }+ } catch (cause) {+ setError(errorText(cause));+ } finally {+ acting.current = false;+ setBusy(null);+ }+ }++ if (servers.isError) return <p role="alert" className="text-sm text-destructive">{t("computers.paired_load_failed")}</p>;+ if (!servers.data?.length) return null;+ return (+ <Section title={t("computers.paired_servers")}>+ <ul className="divide-y divide-border" data-testid="paired-servers">+ {servers.data.map((server) => (+ <li key={server.id} className="flex flex-wrap items-center gap-3 px-4 py-3">+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium text-foreground">{server.name}</p>+ <p className="truncate text-xs text-muted-foreground">{server.url} · {server.platform}</p>+ <p className="text-xs text-muted-foreground">{t(server.online ? "computers.paired_verified" : "computers.paired_offline")}</p>+ </div>+ <Button variant="outline" size="sm" onClick={() => void act(server.id, "open")} disabled={busy !== null}>+ {busy === server.id ? <Loader2 className="animate-spin" /> : <ExternalLink />}{t("computers.paired_open")}+ </Button>+ <Button variant="ghost" size="icon" aria-label={t("computers.check_again")} disabled={busy !== null} onClick={() => void act(server.id, "check")}><RefreshCw /></Button>+ <Button variant="ghost" size="icon" aria-label={t("computers.paired_disconnect")} disabled={busy !== null} onClick={() => void act(server.id, "remove")}><Unplug /></Button>+ </li>+ ))}+ </ul>+ {error && <p role="alert" className="px-4 py-3 text-sm text-destructive">{error}</p>}+ {openingLink && <a href={openingLink} target="_blank" rel="noopener noreferrer" className="block px-4 py-3 text-sm underline">{t("computers.paired_open")}</a>}+ </Section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/PairingAccess.tsx b/jarvis/ui/web/frontend/src/views/computers/PairingAccess.tsxnew file mode 100644index 0000000000..3df7d8ee9e--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/PairingAccess.tsx@@ -0,0 +1,49 @@+import { useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";+import { pairedServersApi } from "@/lib/computersApi";+import { CopyField } from "./parts";+import { errorText } from "./wizard/shared";++/** Codes and revocation are explicit user actions; opening the dialog grants nothing. */+export function PairingAccess() {+ const t = useT();+ const [expanded, setExpanded] = useState(false);+ const [invitation, setInvitation] = useState<{ code: string; expires_at: number } | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const acting = useRef(false);+ const clients = useQuery({ queryKey: ["computers", "paired-clients"], queryFn: pairedServersApi.clients, enabled: expanded, retry: false });++ async function act(id?: string) {+ if (acting.current) return;+ acting.current = true;+ setBusy(true);+ setError(null);+ try {+ if (id) { await pairedServersApi.revoke(id); await clients.refetch(); }+ else setInvitation(await pairedServersApi.code());+ } catch (cause) { setError(errorText(cause)); }+ finally { acting.current = false; setBusy(false); }+ }++ return (+ <div className="space-y-3 border-t border-border pt-4">+ <button type="button" aria-expanded={expanded} onClick={() => setExpanded((value) => !value)} className="text-sm text-muted-foreground hover:text-foreground">{t("computers.pair_this_server")}</button>+ {expanded && <div className="space-y-3">+ <p className="text-sm text-muted-foreground">{t("computers.pair_access_hint")}</p>+ <Button type="button" variant="outline" disabled={busy} onClick={() => void act()}>{t("computers.pair_generate")}</Button>+ {invitation && <>+ <CopyField value={invitation.code} label={t("computers.cx_pairing_code")} copyLabel={t("computers.copy")} copiedLabel={t("computers.copied")} />+ <CopyField value={`${window.location.origin}/#pairing_code=${encodeURIComponent(invitation.code)}`} label={t("computers.pair_link")} copyLabel={t("computers.copy")} copiedLabel={t("computers.copied")} />+ <p className="text-xs text-muted-foreground">{t("computers.pair_expires")} {new Date(invitation.expires_at * 1000).toLocaleTimeString()}</p>+ </>}+ {clients.data?.map((client) => <div key={client.id} className="flex items-center justify-between gap-2 text-sm">+ <span>{client.name}</span><Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void act(client.id)}>{t("computers.pair_revoke")}</Button>+ </div>)}+ {(error || clients.isError) && <p role="alert" className="text-sm text-destructive">{error || t("computers.paired_load_failed")}</p>}+ </div>}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/Placement.tsx b/jarvis/ui/web/frontend/src/views/computers/Placement.tsxnew file mode 100644index 0000000000..545dd806aa--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/Placement.tsx@@ -0,0 +1,127 @@+/**+ * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+ * LoadBalancingSettings.tsx: a switch, then one share per machine, shown once+ * there is a second machine to balance against), MIT License, Copyright (c)+ * 2026 T3 Tools Inc. Full text: third_party/t3code/LICENSE.+ *+ * "Automatic placement": when on, the new-workspace dialog offers+ * "Automatic", which sends the workspace to this PC or a switched-on, online+ * computer in proportion to each one's share (backend:+ * ``jarvis.computers.placement``).+ */+import { Laptop } from "lucide-react";+import { Switch } from "@/components/ui/switch";+import { usePlacement, useSetPlacement, useUpdateComputer } from "@/hooks/useComputers";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { Computer } from "@/lib/computersApi";+import { MachineIcon } from "./machineKind";+import { Row, Section } from "./surface";++const LEVELS = [0, 1, 2, 3] as const;++function ShareControl({+ value,+ onChange,+ label,+ disabled,+ testId,+}: {+ value: number;+ onChange: (next: number) => void;+ label: string;+ disabled?: boolean;+ testId?: string;+}) {+ const t = useT();+ return (+ <div+ role="radiogroup"+ aria-label={label}+ data-testid={testId}+ className="inline-flex items-center gap-0.5 rounded-md border border-border p-0.5"+ >+ {LEVELS.map((level) => {+ const active = level === value;+ return (+ <button+ key={level}+ type="button"+ role="radio"+ aria-checked={active}+ disabled={disabled}+ onClick={() => onChange(level)}+ className={cn(+ "h-7 rounded px-2.5 text-sm font-medium transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ active ? "bg-secondary text-foreground-strong" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`computers.weight_${level}`)}+ </button>+ );+ })}+ </div>+ );+}++export function PlacementSection({ computers }: { computers: Computer[] }) {+ const t = useT();+ const settings = usePlacement();+ const save = useSetPlacement();+ const update = useUpdateComputer();+ const switchedOn = computers.filter((computer) => computer.enabled !== false);+ // One machine besides this PC is the least there is to balance between.+ if (switchedOn.length === 0 || !settings.data) return null;+ const enabled = settings.data.enabled;++ return (+ <Section title={t("computers.placement_title")} testId="computers-placement">+ <Row+ title={t("computers.placement_switch")}+ description={t("computers.placement_body")}+ control={+ <Switch+ checked={enabled}+ disabled={save.isPending}+ onCheckedChange={(next) => save.mutate({ enabled: next })}+ aria-label={t("computers.placement_switch")}+ data-testid="computers-placement-switch"+ />+ }+ />+ {enabled && (+ <>+ <div className="flex flex-wrap items-center justify-between gap-3 px-3 py-2.5 sm:px-4">+ <span className="flex min-w-0 items-center gap-3">+ <Laptop aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="truncate text-base font-medium text-foreground">{t("computers.placement_this_pc")}</span>+ </span>+ <ShareControl+ value={settings.data.local_weight}+ onChange={(next) => save.mutate({ local_weight: next })}+ label={t("computers.placement_this_pc")}+ disabled={save.isPending}+ testId="computers-placement-local"+ />+ </div>+ {switchedOn.map((computer) => (+ <div key={computer.id} className="flex flex-wrap items-center justify-between gap-3 px-3 py-2.5 sm:px-4">+ <span className="flex min-w-0 items-center gap-3">+ <MachineIcon computer={computer} aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="truncate text-base font-medium text-foreground">{computer.name}</span>+ </span>+ <ShareControl+ value={computer.placement_weight ?? 2}+ onChange={(next) => update.mutate({ id: computer.id, patch: { placement_weight: next } })}+ label={computer.name}+ disabled={update.isPending}+ testId={`computers-placement-${computer.id}`}+ />+ </div>+ ))}+ </>+ )}+ </Section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/RouteList.tsx b/jarvis/ui/web/frontend/src/views/computers/RouteList.tsxnew file mode 100644index 0000000000..6e58674483--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/RouteList.tsx@@ -0,0 +1,261 @@+/**+ * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+ * EnvironmentRoutesList.tsx: a machine's ways in, preferred first, drag to+ * reorder, the first that answers is used), MIT License, Copyright (c) 2026+ * T3 Tools Inc. Full text: third_party/t3code/LICENSE.+ *+ * Every address one computer answers on, shown under its row. The order is+ * the preference: a connection tries them top to bottom and a higher one+ * takes over again as soon as it answers. Reorder by dragging or with the+ * arrow buttons; a new address must show the machine's pinned identity, so a+ * stranger on that address is refused by the backend.+ */+import { useEffect, useState } from "react";+import { ArrowDown, ArrowUp, GripVertical, Loader2, Plus, X } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useRouteMutations } from "@/hooks/useComputers";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { ComputerApiError, type Computer, type ComputerRoute, type RouteSuggestion } from "@/lib/computersApi";+import { formatAgo, inputClass } from "./parts";++function fill(template: string, values: Record<string, string>): string {+ return template.replace(/\{(\w+)\}/g, (_m, key: string) => values[key] ?? "");+}++function errorText(error: unknown): string | null {+ if (!error) return null;+ return error instanceof ComputerApiError || error instanceof Error ? error.message : String(error);+}++export function RouteList({+ computer,+ suggestions = [],+}: {+ computer: Computer;+ /** Tailscale addresses this computer could add (``GET /tailscale``). */+ suggestions?: RouteSuggestion[];+}) {+ const t = useT();+ const routes = useRouteMutations();+ // A dropped order shows until the record matches it, so a row does not jump+ // back while the reorder is being saved.+ const [pending, setPending] = useState<string[] | null>(null);+ const [dragging, setDragging] = useState<string | null>(null);+ const [host, setHost] = useState("");+ const [port, setPort] = useState("");+ const [label, setLabel] = useState("");++ const all: ComputerRoute[] = computer.routes?.length+ ? computer.routes+ : [{ id: "r_main", host: computer.host, port: computer.port, label: null, source: "manual", last_ok_at: null }];+ const saved = all.map((route) => route.id);+ useEffect(() => {+ if (pending && pending.join() === saved.join()) setPending(null);+ }, [pending, saved]);+ const byId = new Map(all.map((route) => [route.id, route]));+ const ordered = (pending ?? saved).map((id) => byId.get(id)).filter((r): r is ComputerRoute => Boolean(r));++ const reorder = (next: string[]) => {+ setPending(next);+ routes.order.mutate(+ { id: computer.id, routeIds: next },+ { onError: () => setPending(null) },+ );+ };+ const move = (index: number, delta: number) => {+ const ids = ordered.map((r) => r.id);+ const target = index + delta;+ if (target < 0 || target >= ids.length) return;+ [ids[index], ids[target]] = [ids[target], ids[index]];+ reorder(ids);+ };+ const dropOn = (targetId: string) => {+ if (!dragging || dragging === targetId) return;+ const ids = ordered.map((r) => r.id).filter((id) => id !== dragging);+ ids.splice(ids.indexOf(targetId), 0, dragging);+ setDragging(null);+ reorder(ids);+ };++ const portNumber = port.trim() ? Number(port) : all[0]?.port ?? 22;+ const canAdd =+ host.trim().length > 0 && Number.isInteger(portNumber) && portNumber >= 1 && portNumber <= 65535;+ const add = (route: { host: string; port: number; label?: string; source?: "manual" | "tailscale" }) =>+ routes.add.mutate(+ { id: computer.id, route },+ {+ onSuccess: () => {+ setHost("");+ setPort("");+ setLabel("");+ },+ },+ );+ const error = errorText(routes.add.error) ?? errorText(routes.remove.error) ?? errorText(routes.order.error);++ return (+ <div className="space-y-3 pb-3 pt-1" data-testid={`computer-routes-${computer.id}`}>+ <p className="text-xs text-muted-foreground">{t("computers.routes_hint")}</p>+ <ol className="space-y-1" aria-label={t("computers.routes_title")}>+ {ordered.map((route, index) => {+ const active = route.id === computer.active_route_id;+ return (+ <li+ key={route.id}+ draggable={ordered.length > 1}+ onDragStart={(event) => {+ event.dataTransfer.effectAllowed = "move";+ setDragging(route.id);+ }}+ onDragEnd={() => setDragging(null)}+ onDragOver={(event) => {+ if (dragging) event.preventDefault();+ }}+ onDrop={(event) => {+ event.preventDefault();+ dropOn(route.id);+ }}+ data-testid={`computer-route-${route.id}`}+ className={cn(+ "group/route flex items-center gap-2 rounded-md border border-border bg-background/40 px-2 py-1.5",+ dragging === route.id && "opacity-50",+ )}+ >+ {ordered.length > 1 && (+ <GripVertical aria-hidden className="h-3.5 w-3.5 shrink-0 cursor-grab text-foreground-faint" />+ )}+ <span className="w-4 shrink-0 text-center text-xs tabular-nums text-foreground-faint">{index + 1}</span>+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="truncate font-mono text-xs text-foreground">+ {route.host}+ {route.port !== 22 ? `:${route.port}` : ""}+ </span>+ {route.label && <span className="truncate text-xs text-muted-foreground">{route.label}</span>}+ {route.source !== "manual" && (+ <span className="shrink-0 rounded bg-secondary px-1.5 py-px text-xs text-muted-foreground">+ {route.source === "tailscale" ? t("computers.route_source_tailscale") : t("computers.route_source_ssh_config")}+ </span>+ )}+ {active && (+ <span className="shrink-0 rounded bg-success/10 px-1.5 py-px text-xs font-medium text-success">+ {t("computers.route_active")}+ </span>+ )}+ </span>+ {route.last_ok_at && (+ <span className="block text-xs text-foreground-faint">+ {fill(t("computers.route_seen"), { ago: formatAgo(route.last_ok_at, t) })}+ </span>+ )}+ </span>+ {ordered.length > 1 && (+ <span className="flex shrink-0 items-center">+ <button+ type="button"+ aria-label={t("computers.route_move_up")}+ disabled={index === 0 || routes.order.isPending}+ onClick={() => move(index, -1)}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground disabled:opacity-30"+ >+ <ArrowUp className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ aria-label={t("computers.route_move_down")}+ disabled={index === ordered.length - 1 || routes.order.isPending}+ onClick={() => move(index, 1)}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground disabled:opacity-30"+ >+ <ArrowDown className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ aria-label={t("computers.route_remove")}+ disabled={routes.remove.isPending}+ onClick={() => routes.remove.mutate({ id: computer.id, routeId: route.id })}+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-destructive disabled:opacity-30"+ data-testid={`computer-route-remove-${route.id}`}+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </span>+ )}+ </li>+ );+ })}+ </ol>++ {suggestions.map((suggestion) => (+ <div+ key={suggestion.host}+ className="flex items-center gap-2 rounded-md border border-dashed border-border px-2 py-1.5"+ data-testid="computer-route-suggestion"+ >+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">+ {fill(t("computers.route_suggest"), { host: suggestion.host })}+ </span>+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-2 text-xs"+ disabled={routes.add.isPending}+ onClick={() =>+ add({ host: suggestion.host, port: suggestion.port, label: suggestion.label, source: "tailscale" })+ }+ >+ <Plus className="h-3.5 w-3.5" />+ {t("computers.route_add")}+ </Button>+ </div>+ ))}++ {computer.kind !== "local_vm" && (+ <form+ className="flex flex-wrap items-center gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ if (canAdd) add({ host: host.trim(), port: portNumber, label: label.trim() || undefined });+ }}+ >+ <input+ className={cn(inputClass, "h-8 min-w-0 flex-[2_1_10rem] text-sm")}+ value={host}+ onChange={(event) => setHost(event.target.value)}+ placeholder={t("computers.route_add_host")}+ aria-label={t("computers.route_add_host")}+ spellCheck={false}+ autoComplete="off"+ data-testid={`computer-route-host-${computer.id}`}+ />+ <input+ className={cn(inputClass, "h-8 w-20 text-sm")}+ value={port}+ onChange={(event) => setPort(event.target.value)}+ placeholder={String(all[0]?.port ?? 22)}+ aria-label={t("computers.field_port")}+ inputMode="numeric"+ />+ <input+ className={cn(inputClass, "h-8 min-w-0 flex-[1_1_7rem] text-sm")}+ value={label}+ onChange={(event) => setLabel(event.target.value)}+ placeholder={t("computers.route_add_label")}+ aria-label={t("computers.route_add_label")}+ maxLength={40}+ />+ <Button type="submit" variant="outline" size="sm" className="h-8" disabled={!canAdd || routes.add.isPending}>+ {routes.add.isPending ? <Loader2 className="animate-spin" /> : <Plus />}+ {routes.add.isPending ? t("computers.route_adding") : t("computers.route_add")}+ </Button>+ </form>+ )}+ {error && (+ <p role="alert" className="text-xs text-destructive">+ {error}+ </p>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/computers/ServerAddressForm.tsx b/jarvis/ui/web/frontend/src/views/computers/ServerAddressForm.tsxindex 7170f70e7b..bf965801a7 100644--- a/jarvis/ui/web/frontend/src/views/computers/ServerAddressForm.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/ServerAddressForm.tsx@@ -1,21 +1,45 @@-import { useState } from "react";-import { Plus } from "lucide-react";+import { useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Loader2, Plus } from "lucide-react";import { Button } from "@/components/ui/button";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { Field, inputClass } from "./parts";+import { pairedServersApi } from "@/lib/computersApi";+import { pairedServerKey } from "./PairedServers";+import { PairingAccess } from "./PairingAccess";+import { errorText } from "./wizard/shared";-/** Collect pairing details without sending them to the unrelated SSH API. */-export function ServerAddressForm() {+/** Pair a real independent server and persist only its public metadata in the UI cache. */+export function ServerAddressForm({ onConnected }: { onConnected: () => void }) {const t = useT();const [host, setHost] = useState("");const [code, setCode] = useState("");+ const queryClient = useQueryClient();+ const submitting = useRef(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ async function connect() {+ if (!host.trim() || !code.trim() || submitting.current) return;+ submitting.current = true;+ setBusy(true);+ setError(null);+ try {+ await pairedServersApi.add(host.trim(), code.trim());+ setCode("");+ await queryClient.invalidateQueries({ queryKey: pairedServerKey });+ onConnected();+ } catch (cause) { setError(errorText(cause)); }+ finally { submitting.current = false; setBusy(false); }+ }function readPairingUrl(value: string): boolean {try {const url = new URL(value.trim());if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return false;- const pairingCode = url.searchParams.get("code") ?? url.searchParams.get("pairing_code");+ const fragment = new URLSearchParams(url.hash.slice(1));+ const pairingCode = fragment.get("pairing_code") ?? url.searchParams.get("code") ?? url.searchParams.get("pairing_code");if (!pairingCode?.trim()) return false;setHost(url.origin);setCode(pairingCode);@@ -27,12 +51,13 @@ export function ServerAddressForm() {}return (- <form className="space-y-5" onSubmit={(event) => event.preventDefault()} data-testid="cx-server-form">+ <form className="space-y-5" onSubmit={(event) => { event.preventDefault(); void connect(); }} data-testid="cx-server-form"><div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_10rem]"><Field label={t("computers.cx_server_host")}><inputclassName={cn(inputClass, "h-12 rounded-xl px-4")}value={host}+ disabled={busy}onChange={(event) => setHost(event.target.value)}onBlur={() => readPairingUrl(host)}onPaste={(event) => {@@ -49,6 +74,7 @@ export function ServerAddressForm() {<inputclassName={cn(inputClass, "h-12 rounded-xl px-4")}value={code}+ disabled={busy}onChange={(event) => setCode(event.target.value)}placeholder="PAIRCODE"autoComplete="off"@@ -59,11 +85,13 @@ export function ServerAddressForm() {</Field></div><p id="cx-pairing-hint" className="text-sm text-muted-foreground">{t("computers.cx_pairing_hint")}</p>- <Button type="submit" variant="outline" className="h-12 w-full rounded-xl text-base" disabled aria-describedby="cx-pairing-unavailable">- <Plus />+ <Button type="submit" variant="outline" className="h-12 w-full rounded-xl text-base" disabled={busy || !host.trim() || !code.trim()}>+ {busy ? <Loader2 className="animate-spin" /> : <Plus />}{t("computers.add")}</Button>- <p id="cx-pairing-unavailable" className="text-sm text-muted-foreground">{t("computers.cx_pairing_unavailable")}</p>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ <p className="text-xs text-muted-foreground">{t("computers.paired_connection_hint")}</p>+ <PairingAccess /></form>);}diff --git a/jarvis/ui/web/frontend/src/views/computers/computerFeatures.test.tsx b/jarvis/ui/web/frontend/src/views/computers/computerFeatures.test.tsxnew file mode 100644index 0000000000..1ec6475a51--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/computerFeatures.test.tsx@@ -0,0 +1,383 @@+/**+ * The Computers features adapted from T3 Code: machine glyphs, the on/off+ * switch, several addresses per machine, Tailscale suggestions, the hosts this+ * PC already knows, automatic placement and GitHub sharing.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";++import { loadLocaleChunk, setUiLanguage } from "@/i18n";+import type { Computer } from "@/lib/computersApi";+import { RUN_ON_AUTO, RunOnPicker } from "@/components/agentic/RunOnPicker";+import { ComputerRow } from "./ComputerRow";+import { GithubAccess } from "./GithubAccess";+import { KnownHosts } from "./KnownHosts";+import { isLanHost, machineKind } from "./machineKind";+import { PlacementSection } from "./Placement";++interface Call {+ url: string;+ method: string;+ body: unknown;+}++function installFetch(routes: Record<string, (body: unknown) => unknown>) {+ const calls: Call[] = [];+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;+ calls.push({ url, method, body });+ const handler = routes[`${method} ${url}`];+ if (!handler) throw new Error(`unexpected fetch ${method} ${url}`);+ const payload = handler(body);+ return { ok: true, status: 200, statusText: "OK", json: async () => payload } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ return calls;+}++function computer(overrides: Partial<Computer> = {}): Computer {+ return {+ id: "c_1",+ name: "VPS",+ kind: "server",+ provider: "generic",+ host: "203.0.113.15",+ port: 22,+ username: "root",+ auth: "key",+ provider_ref: null,+ region: null,+ plan: null,+ host_key: "ssh-ed25519 AAAA",+ host_fingerprint: "SHA256:server",+ created_at: 1_700_000_000,+ facts: {+ hostname: "vps-01",+ os_id: "ubuntu",+ os_name: "Ubuntu 24.04.1 LTS",+ kernel: null,+ arch: "x86_64",+ cpu_count: 4,+ mem_total_mb: 8192,+ disk_total_gb: 50,+ },+ health: {+ status: "online",+ checked_at: Date.now() / 1000,+ latency_ms: 42,+ message: null,+ load_1m: 0.5,+ mem_used_pct: 30,+ disk_used_pct: 25,+ uptime_s: 1000,+ trace_id: null,+ },+ enabled: true,+ routes: [+ { id: "r_main", host: "203.0.113.15", port: 22, label: null, source: "manual", last_ok_at: null },+ ],+ active_route_id: "r_main",+ placement_weight: 2,+ github_shared_at: null,+ busy: false,+ ...overrides,+ };+}++function withQuery(node: ReactNode) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}>{node}</QueryClientProvider>);+}++beforeEach(async () => {+ setUiLanguage("en");+ await loadLocaleChunk("computers");+});+afterEach(() => cleanup());++describe("machine kind", () => {+ it("reads the kind from where the machine came from and what it reported", () => {+ expect(machineKind(computer({ provider: "hetzner" }))).toBe("cloud");+ expect(machineKind(computer())).toBe("cloud");+ expect(machineKind(computer({ host: "192.168.1.20", routes: [] }))).toBe("server");+ expect(machineKind(computer({ provider: "raspberry_pi" }))).toBe("mini");+ expect(machineKind(computer({ kind: "local_vm", provider: "multipass" }))).toBe("linux");+ const windows = computer();+ windows.facts = { ...windows.facts!, os_id: "windows", hostname: "DESK-01" };+ expect(machineKind(windows)).toBe("desktop");+ windows.facts = { ...windows.facts!, os_id: "macos", hostname: "Adas-MacBook-Pro" };+ expect(machineKind(windows)).toBe("laptop");+ const pi = computer({ provider: "home_server" });+ pi.facts = { ...pi.facts!, arch: "aarch64", mem_total_mb: 4096 };+ expect(machineKind(pi)).toBe("mini");+ expect(machineKind(computer({ provider: "home_server" }))).toBe("server");+ });++ it("tells home-network addresses apart", () => {+ for (const host of ["10.0.0.4", "192.168.178.132", "172.20.1.1", "nas.local", "pi.fritz.box"]) {+ expect(isLanHost(host)).toBe(true);+ }+ for (const host of ["203.0.113.4", "172.32.0.1", "box.tail1234.ts.net", "example.com"]) {+ expect(isLanHost(host)).toBe(false);+ }+ });+});++describe("computer row", () => {+ it("switches a computer off and shows it as switched off", async () => {+ const calls = installFetch({+ "PATCH /api/computers/c_1": () => computer({ enabled: false }),+ });+ const { rerender } = withQuery(<ComputerRow computer={computer()} checking={false} onOpen={() => undefined} />);++ fireEvent.click(screen.getByTestId("computer-switch-c_1"));++ await waitFor(() => expect(calls.some((c) => c.method === "PATCH")).toBe(true));+ expect(calls.find((c) => c.method === "PATCH")?.body).toEqual({ enabled: false });+ rerender(+ <QueryClientProvider client={new QueryClient()}>+ <ComputerRow computer={computer({ enabled: false })} checking={false} onOpen={() => undefined} />+ </QueryClientProvider>,+ );+ expect(screen.getByTestId("computer-item-c_1").getAttribute("data-enabled")).toBe("false");+ expect(screen.getByText("Switched off")).toBeTruthy();+ });++ it("opens the detail page from the name, not from the switch", () => {+ installFetch({ "PATCH /api/computers/c_1": () => computer({ enabled: false }) });+ const onOpen = vi.fn();+ withQuery(<ComputerRow computer={computer()} checking={false} onOpen={onOpen} />);++ fireEvent.click(screen.getByTestId("computer-switch-c_1"));+ expect(onOpen).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId("computer-row-c_1"));+ expect(onOpen).toHaveBeenCalledTimes(1);+ });++ it("lists, reorders, adds and removes addresses", async () => {+ const two = computer({+ routes: [+ { id: "r_main", host: "192.168.1.20", port: 22, label: null, source: "manual", last_ok_at: null },+ { id: "r_ts", host: "vps-01.tail1234.ts.net", port: 22, label: "Tailscale", source: "tailscale", last_ok_at: 1 },+ ],+ });+ const calls = installFetch({+ "PUT /api/computers/c_1/routes/order": () => two,+ "POST /api/computers/c_1/routes": () => two,+ "DELETE /api/computers/c_1/routes/r_ts": () => computer(),+ });+ withQuery(<ComputerRow computer={two} checking={false} onOpen={() => undefined} />);++ fireEvent.click(screen.getByTestId("computer-routes-toggle-c_1"));+ const list = screen.getByTestId("computer-routes-c_1");+ expect(within(list).getByText("192.168.1.20")).toBeTruthy();+ expect(within(list).getByText("In use")).toBeTruthy();++ fireEvent.click(within(screen.getByTestId("computer-route-r_main")).getByRole("button", { name: "Move down" }));+ await waitFor(() =>+ expect(calls.find((c) => c.url.endsWith("/routes/order"))?.body).toEqual({ route_ids: ["r_ts", "r_main"] }),+ );++ fireEvent.change(screen.getByTestId("computer-route-host-c_1"), { target: { value: "box.example.com" } });+ fireEvent.click(within(list).getByRole("button", { name: "Add address" }));+ await waitFor(() =>+ expect(calls.find((c) => c.method === "POST")?.body).toEqual({ host: "box.example.com", port: 22 }),+ );++ fireEvent.click(screen.getByTestId("computer-route-remove-r_ts"));+ await waitFor(() => expect(calls.some((c) => c.method === "DELETE")).toBe(true));+ });++ it("offers a Tailscale address with one click", async () => {+ const calls = installFetch({ "POST /api/computers/c_1/routes": () => computer() });+ withQuery(+ <ComputerRow+ computer={computer()}+ checking={false}+ onOpen={() => undefined}+ suggestions={[{ host: "vps-01.tail1234.ts.net", port: 22, label: "Tailscale", online: true }]}+ />,+ );++ fireEvent.click(screen.getByTestId("computer-routes-toggle-c_1"));+ const suggestion = screen.getByTestId("computer-route-suggestion");+ expect(within(suggestion).getByText("On Tailscale as vps-01.tail1234.ts.net")).toBeTruthy();+ fireEvent.click(within(suggestion).getByRole("button"));++ await waitFor(() =>+ expect(calls[0]?.body).toEqual({+ host: "vps-01.tail1234.ts.net",+ port: 22,+ label: "Tailscale",+ source: "tailscale",+ }),+ );+ });++ it("a failed check offers its error ID to copy", () => {+ installFetch({});+ const down = computer({+ health: { ...computer().health, status: "offline", message: "The server did not answer in time.", trace_id: "cmp-1a2b3c4d" },+ });+ withQuery(<ComputerRow computer={down} checking={false} onOpen={() => undefined} />);++ expect(screen.getByTestId("computer-copy-error-c_1")).toBeTruthy();+ });++ it("an older backend gets no controls it would ignore", () => {+ installFetch({});+ const old = computer();+ delete old.routes;+ delete old.enabled;+ delete old.github_shared_at;+ withQuery(+ <>+ <ComputerRow computer={old} checking={false} onOpen={() => undefined} />+ <GithubAccess computer={old} />+ </>,+ );++ expect(screen.getByText(/203\.0\.113\.15/)).toBeTruthy();+ expect(screen.queryByTestId("computer-switch-c_1")).toBeNull();+ expect(screen.queryByTestId("computer-routes-toggle-c_1")).toBeNull();+ expect(screen.queryByTestId("computer-github")).toBeNull();+ });+});++describe("known hosts", () => {+ it("lists this PC's hosts and fills the form on a click", async () => {+ installFetch({+ "GET /api/computers/ssh-hosts": () => ({+ hosts: [+ { alias: "hz", host: "203.0.113.7", port: 2222, username: "deploy", source: "ssh_config", has_identity_file: true, needs_proxy: false, added_as: null },+ { alias: "inner", host: "inner", port: 22, username: "root", source: "ssh_config", has_identity_file: false, needs_proxy: true, added_as: null },+ { alias: "198.51.100.4", host: "198.51.100.4", port: 22, username: null, source: "known_hosts", has_identity_file: false, needs_proxy: false, added_as: "c_9" },+ ],+ }),+ });+ const onPick = vi.fn();+ withQuery(<KnownHosts onPick={onPick} />);++ const hz = await screen.findByTestId("cx-known-hz");+ expect(within(hz).getByText("[email protected]:2222")).toBeTruthy();+ expect((screen.getByTestId("cx-known-inner") as HTMLButtonElement).disabled).toBe(true);+ expect((screen.getByTestId("cx-known-198.51.100.4") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(hz);+ expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ alias: "hz", port: 2222 }));+ });++ it("shows nothing when this PC knows no servers", async () => {+ const calls = installFetch({ "GET /api/computers/ssh-hosts": () => ({ hosts: [] }) });+ const { container } = withQuery(<KnownHosts onPick={() => undefined} />);++ await waitFor(() => expect(calls.length).toBe(1));+ expect(container.textContent).toBe("");+ });+});++describe("automatic placement", () => {+ it("switches on and sets each machine's share", async () => {+ let enabled = false;+ const calls = installFetch({+ "GET /api/computers/placement": () => ({ enabled, local_weight: 2 }),+ "PUT /api/computers/placement": (body) => {+ enabled = Boolean((body as { enabled?: boolean }).enabled ?? enabled);+ return { enabled, local_weight: (body as { local_weight?: number }).local_weight ?? 2 };+ },+ "PATCH /api/computers/c_1": () => computer({ placement_weight: 3 }),+ });+ withQuery(<PlacementSection computers={[computer()]} />);++ fireEvent.click(await screen.findByTestId("computers-placement-switch"));+ await waitFor(() => expect(screen.getByTestId("computers-placement-local")).toBeTruthy());++ fireEvent.click(within(screen.getByTestId("computers-placement-c_1")).getByRole("radio", { name: "More" }));+ await waitFor(() =>+ expect(calls.find((c) => c.method === "PATCH")?.body).toEqual({ placement_weight: 3 }),+ );+ fireEvent.click(within(screen.getByTestId("computers-placement-local")).getByRole("radio", { name: "Never" }));+ await waitFor(() =>+ expect(calls.filter((c) => c.method === "PUT").at(-1)?.body).toEqual({ local_weight: 0 }),+ );+ });++ it("stays hidden while every computer is switched off", async () => {+ installFetch({ "GET /api/computers/placement": () => ({ enabled: true, local_weight: 2 }) });+ const { container } = withQuery(<PlacementSection computers={[computer({ enabled: false })]} />);++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(container.textContent).toBe("");+ });+});++describe("runs-on picker", () => {+ it("never offers a switched-off computer", async () => {+ installFetch({+ "GET /api/computers": () => ({+ computers: [computer(), computer({ id: "c_off", name: "Old box", enabled: false })],+ }),+ });+ render(<RunOnPicker value={null} onChange={() => undefined} />);++ expect(await screen.findByTestId("ide-run-on-c_1")).toBeTruthy();+ expect(screen.queryByTestId("ide-run-on-c_off")).toBeNull();+ });++ it("offers Automatic only while automatic placement is on", async () => {+ installFetch({+ "GET /api/computers": () => ({ computers: [computer()] }),+ "GET /api/computers/placement": () => ({ enabled: true, local_weight: 2 }),+ });+ const onChange = vi.fn();+ render(<RunOnPicker value={null} onChange={onChange} allowAuto />);++ fireEvent.click(await screen.findByTestId(`ide-run-on-${RUN_ON_AUTO}`));+ expect(onChange).toHaveBeenCalledWith(RUN_ON_AUTO);+ });++ it("falls back to this PC when Automatic was chosen but is switched off now", async () => {+ installFetch({+ "GET /api/computers": () => ({ computers: [computer()] }),+ "GET /api/computers/placement": () => ({ enabled: false, local_weight: 2 }),+ });+ const onChange = vi.fn();+ render(<RunOnPicker value={RUN_ON_AUTO} onChange={onChange} allowAuto />);++ await waitFor(() => expect(onChange).toHaveBeenCalledWith(null));+ expect(screen.queryByTestId(`ide-run-on-${RUN_ON_AUTO}`)).toBeNull();+ });+});++describe("GitHub for the agents", () => {+ it("shares with a warning beside it, then stops sharing", async () => {+ const calls = installFetch({+ "POST /api/computers/c_1/github": () => computer({ github_shared_at: Date.now() / 1000 }),+ "DELETE /api/computers/c_1/github": () => computer(),+ });+ const { rerender } = withQuery(<GithubAccess computer={computer()} />);++ expect(screen.getByText(/same access to GitHub as you/)).toBeTruthy();+ fireEvent.click(screen.getByTestId("computer-github-share"));+ await waitFor(() => expect(calls.some((c) => c.method === "POST")).toBe(true));++ rerender(+ <QueryClientProvider client={new QueryClient()}>+ <GithubAccess computer={computer({ github_shared_at: Date.now() / 1000 })} />+ </QueryClientProvider>,+ );+ expect(screen.getByTestId("computer-github-share").textContent).toContain("Share again");+ fireEvent.click(screen.getByTestId("computer-github-unshare"));+ await waitFor(() => expect(calls.some((c) => c.method === "DELETE")).toBe(true));+ });++ it("cannot share with a computer that is off or unreachable", () => {+ installFetch({});+ withQuery(<GithubAccess computer={computer({ enabled: false })} />);++ expect((screen.getByTestId("computer-github-share") as HTMLButtonElement).disabled).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/computers/machineKind.tsx b/jarvis/ui/web/frontend/src/views/computers/machineKind.tsxnew file mode 100644index 0000000000..8ee30cbb1a--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/computers/machineKind.tsx@@ -0,0 +1,93 @@+/**+ * Portions adapted from pingdotgg/t3code @ 12069ee (apps/web+ * EnvironmentMachineIcon.tsx: one glyph per kind of machine, the mini PC drawn+ * to lucide's grammar), MIT License, Copyright (c) 2026 T3 Tools Inc. Full+ * text: third_party/t3code/LICENSE.+ *+ * What kind of machine a computer is, read from what the app already knows+ * (where it came from, the facts its last check reported) — no field of its+ * own, so it can never disagree with the machine.+ */+import type { LucideProps } from "lucide-react";+import { Laptop, Monitor, Server, SquareTerminal } from "lucide-react";+import type { ComponentType, SVGProps } from "react";+import { ComputersIcon } from "@/components/icons/sectionIcons";+import type { Computer } from "@/lib/computersApi";++export type MachineKind = "cloud" | "server" | "linux" | "desktop" | "laptop" | "mini";++/** Hosting accounts and rented machines: a cloud. Anything typed in by hand is not. */+const SELF_HOSTED = new Set(["generic", "home_server", "raspberry_pi", "multipass"]);++/** Providers without a brand mark of their own: they wear their kind's glyph. */+export function wearsMachineGlyph(provider: string): boolean {+ return provider === "generic" || provider === "home_server" || provider === "multipass";+}++const LAPTOP_NAME = /book|laptop|notebook|thinkpad|xps|surface/i;++export function machineKind(computer: Computer): MachineKind {+ if (computer.kind === "local_vm") return "linux";+ if (computer.provider === "raspberry_pi") return "mini";+ const facts = computer.facts;+ const os = facts?.os_id?.toLowerCase() ?? "";+ if (os === "windows" || os === "macos") {+ return facts?.hostname && LAPTOP_NAME.test(facts.hostname) ? "laptop" : "desktop";+ }+ if (!SELF_HOSTED.has(computer.provider)) return "cloud";+ const arm = /^(arm|aarch)/i.test(facts?.arch ?? "");+ const small = facts?.mem_total_mb != null && facts.mem_total_mb <= 8192;+ if (arm && small) return "mini";+ if (computer.provider === "home_server") return "server";+ // A hand-typed address: a VPS somewhere, unless every address is on a home LAN.+ const hosts = computer.routes?.length ? computer.routes.map((route) => route.host) : [computer.host];+ return hosts.every((host) => isLanHost(host))+ ? "server"+ : "cloud";+}++/** A private IPv4 range or a local-network name (.local, .lan, .fritz.box, .home). */+export function isLanHost(host: string): boolean {+ const name = host.toLowerCase();+ if (/\.(local|lan|home|internal|fritz\.box)$/.test(name)) return true;+ const octets = name.split(".").map(Number);+ if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;+ const [a, b] = octets;+ return a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31);+}++/** A mini PC: a squat rounded slab with a front-edge LED. */+function MiniPcIcon({ className, strokeWidth = 2, ...rest }: SVGProps<SVGSVGElement> & LucideProps) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ {...(rest as SVGProps<SVGSVGElement>)}+ >+ <rect width="20" height="8" x="2" y="8" rx="2" />+ <path d="M6 12h.01" />+ </svg>+ );+}++const ICONS: Record<MachineKind, ComponentType<LucideProps>> = {+ cloud: ComputersIcon,+ server: Server,+ linux: SquareTerminal,+ desktop: Monitor,+ laptop: Laptop,+ mini: MiniPcIcon as ComponentType<LucideProps>,+};++export function MachineIcon({ computer, ...props }: LucideProps & { computer: Computer }) {+ const Icon = ICONS[machineKind(computer)];+ return <Icon data-machine-kind={machineKind(computer)} {...props} />;+}diff --git a/jarvis/ui/web/frontend/src/views/computers/surface.tsx b/jarvis/ui/web/frontend/src/views/computers/surface.tsxindex df63774b3e..4c70eb72e7 100644--- a/jarvis/ui/web/frontend/src/views/computers/surface.tsx+++ b/jarvis/ui/web/frontend/src/views/computers/surface.tsx@@ -97,7 +97,11 @@ const DOT: Record<Tone, string> = {/** The connection dot: a halo pings only while the state is in motion. */export function StatusDot({ tone, label }: { tone: Tone; label?: string }) {return (- <span className="relative flex h-3 w-3 shrink-0 items-center justify-center" title={label} aria-label={label}>+ <span+ className="relative flex h-3 w-3 shrink-0 items-center justify-center"+ role={label ? "img" : undefined}+ aria-label={label}+ >{tone === "busy" && (<span className="absolute inline-flex h-full w-full rounded-full bg-warning/60 motion-safe:animate-ping" />)}diff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.pyindex a3c0e8b79b..c1297d7a61 100644--- a/jarvis/ui/web/local_models_routes.py+++ b/jarvis/ui/web/local_models_routes.py@@ -630,6 +630,7 @@ def put_model_options(provider.models.pop(stored_key, None)if opts is not None:provider.models[tag] = opts+ _refresh_option_consumers(request)_forget_overview()return _options_response(tag, opts)@@ -652,10 +653,22 @@ def delete_model_options(provider = _ollama_provider_cfg(cfg)if stored_key is not None and provider is not None:provider.models.pop(stored_key, None)+ _refresh_option_consumers(request)_forget_overview()return _options_response(name, None)+def _refresh_option_consumers(request: Request) -> None:+ """The next turn must budget with the saved context before assembling tools."""+ from jarvis.agent_runtimes.gateway import invalidate_provider_metadata++ brain = getattr(request.app.state, "brain", None)+ reactivate = getattr(brain, "reactivate_provider", None)+ if callable(reactivate):+ reactivate("ollama")+ invalidate_provider_metadata("ollama")++@router.get("/models/{name:path}/suggested-options", response_model=SuggestedOptionsResponse)async def get_suggested_options(provider_id: str, name: str) -> SuggestedOptionsResponse:"""An advisory profile for ``name`` on THIS machine, with one reason per knob."""diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex fef50c1a1a..03d1a3a346 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -14,6 +14,7 @@ Endpoints:DELETE /api/marketplace/community/plugins/{id} — uninstall + revokePOST /api/marketplace/plugins/upload/inspect — read a dropped manifestPOST /api/marketplace/plugins/upload — install a dropped manifest+ POST /api/marketplace/connectors — add a remote MCP server by URL"""from __future__ import annotations@@ -59,6 +60,7 @@ from jarvis.marketplace.auth import (from jarvis.marketplace.catalog import (CATEGORY_ORDER,HostedMcpOAuthDcrAuth,+ HostedMcpOpenAuth,InstanceBrowserAuth,OAuthDeviceFlowAuth,OAuthPkceLoopbackAuth,@@ -306,6 +308,29 @@ def _make_validator(transport: httpx.AsyncBaseTransport | None = None):_validate_token = _make_validator()+async def _validate_connector_token(spec: Any, pat: PatPasteAuth, token: str) -> tuple[bool, int]:+ """Prove a custom connector's token with an MCP handshake.++ The server behind a custom connector has no REST "who am I" route to ask,+ so the token rides in the entry's own header on an ``initialize`` — the+ exact request the tool registry sends next. Unreachable or non-MCP+ answers surface as a 502 with the probe's sentence, not as "rejected".+ """+ from jarvis.marketplace.custom_connector import (+ ConnectorError,+ connector_auth_headers,+ probe_connector,+ )++ try:+ probe = await probe_connector(+ pat.validation_endpoint, headers=connector_auth_headers(spec, token)+ )+ except ConnectorError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ return probe.auth == "none", probe.status++# ----------------------------------------------------------------------# Read endpoints# ----------------------------------------------------------------------@@ -332,7 +357,7 @@ def _mcp_live(today's behaviour."""transport = str(mcp.get("transport", "")).lower()- if transport == "http":+ if transport in ("http", "sse"):if status == "connected":reg = _live_plugin_registry() # the same accessor refresh usesif reg is not None and reg.is_bootstrapped() and reg.live_tool_count(plugin_id) == 0:@@ -511,11 +536,12 @@ async def connect_pat(plugin_id: str, body: PatConnectBody, request: Request) -># Only widen the call for self-hosted plugins. Every other caller (and# every injected test double) keeps the two-argument shape it has had# since the flow was written.- ok, status = (- await _validate_token(pat, token, instance_url)- if instance_url- else await _validate_token(pat, token)- )+ if pat.validation_method == "mcp_initialize":+ ok, status = await _validate_connector_token(spec, pat, token)+ elif instance_url:+ ok, status = await _validate_token(pat, token, instance_url)+ else:+ ok, status = await _validate_token(pat, token)except httpx.HTTPError as exc:raise HTTPException(status_code=502,@@ -707,6 +733,27 @@ async def connect_start(TokenStore().save(plugin_id, Tokens(access="local-enabled"))_refresh_plugin_in_live_registry(plugin_id)return {"kind": "local", "plugin_id": plugin_id, "state": "connected"}+ elif isinstance(spec.auth, HostedMcpOpenAuth):+ # No sign-in to run: one answered handshake is the whole connect, so+ # "Connected" is never shown for a server that is down or now wants+ # credentials it did not want when it was added.+ from jarvis.marketplace.custom_connector import ConnectorError, probe_connector++ try:+ probe = await probe_connector(spec.auth.mcp_url)+ except ConnectorError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ if probe.auth != "none":+ raise HTTPException(+ status_code=409,+ detail=(+ f"{spec.display_name} now asks for sign-in. Remove it and add it "+ "again so the new sign-in is detected."+ ),+ )+ TokenStore().save(plugin_id, Tokens(access="open"))+ _refresh_plugin_in_live_registry(plugin_id)+ return {"kind": "local", "plugin_id": plugin_id, "state": "connected"}elif isinstance(spec.auth, OAuthDeviceFlowAuth):from jarvis.marketplace.connect_helpers import is_placeholder_client_idfrom jarvis.marketplace.publisher_clients import resolve_publisher_client@@ -771,7 +818,8 @@ async def connect_start(detail=(f"plugin {plugin_id!r} uses auth mode {spec.auth.mode!r} ""which is not yet wired to /connect/start. Supported: "- "hosted_mcp_oauth_dcr, oauth_device_flow, oauth_pkce_loopback."+ "hosted_mcp_oauth_dcr, hosted_mcp_open, oauth_device_flow, "+ "oauth_pkce_loopback."),)@@ -1681,14 +1729,17 @@ async def community_install_by_name(item_id: str, request: Request) -> dict[str,@router.delete("/community/plugins/{plugin_id}")async def community_uninstall(plugin_id: str) -> dict[str, Any]:"""Remove an installed community plugin: revoke + drop stored tokens,- remove the catalog entry and its usage card, refresh the live registry."""+ remove the catalog entry and its usage card, refresh the live registry.++ A plugin the owner added here (an upload or a custom connector) lives in+ the same override catalog and leaves the same way."""from jarvis.marketplace.community_install import remove_community_pluginfrom jarvis.marketplace.usage_cards.loader import delete_usage_cardspec = load_catalog().by_id(plugin_id)if spec is None:raise HTTPException(status_code=404, detail=f"plugin {plugin_id!r} not in catalog")- if spec.source != "community":+ if spec.source not in ("community", LOCAL_PLUGIN_SOURCE):raise HTTPException(status_code=409,detail=f"{plugin_id!r} is a built-in plugin — disconnect it instead of uninstalling",@@ -1933,3 +1984,88 @@ async def upload_plugin(item = spec.model_dump(mode="json")item["status"] = "not_connected"return {"ok": True, "plugin": item, "upload": result["upload"]}+++# ----------------------------------------------------------------------+# Custom connector — a remote MCP server added by name and address+# ----------------------------------------------------------------------+++class CustomConnectorBody(BaseModel):+ name: str = Field(default="", max_length=80)+ url: str = Field(min_length=1, max_length=2048)+ # "auto" asks the server; the others are the owner's override from the+ # dialog's advanced settings, still checked against what the server says.+ auth: str = Field(default="auto", pattern="^(auto|oauth|token|none)$")+ # The header an access token travels in; Authorization (Bearer) if unset.+ header_name: str | None = Field(default=None, max_length=64)++[email protected]("/connectors")+async def add_custom_connector(body: CustomConnectorBody) -> dict[str, Any]:+ """Adds a remote MCP server as a plugin, after asking it how to sign in.++ One call instead of inspect-then-install: the probe is the inspection,+ and a connector the server would refuse is never written. The response+ carries the catalog item, so the dialog can start the matching connect+ flow (browser sign-in, token dialog, or a plain enable) at once.+ """+ from jarvis.marketplace.community_install import install_plugin_spec+ from jarvis.marketplace.custom_connector import (+ ConnectorError,+ build_connector_spec,+ connector_id,+ connector_url,+ display_name_for,+ normalize_connector_url,+ normalize_header_name,+ probe_connector,+ resolve_auth,+ )++ try:+ url = normalize_connector_url(body.url)+ header_name = normalize_header_name(body.header_name)+ except ConnectorError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ catalog = load_catalog()+ for existing in catalog.plugins:+ if connector_url(existing) == url:+ raise HTTPException(+ status_code=409,+ detail=f"This server is already added as {existing.display_name}.",+ )++ try:+ probe = await probe_connector(url)+ auth = resolve_auth(body.auth, probe) # type: ignore[arg-type] # pattern-checked+ except ConnectorError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc++ display_name = display_name_for(body.name, url, probe)+ plugin_id = connector_id(display_name, url, (p.id for p in catalog.plugins))+ spec = build_connector_spec(+ plugin_id=plugin_id,+ display_name=display_name,+ url=url,+ auth=auth,+ probe=probe,+ header_name=header_name,+ )+ try:+ await asyncio.to_thread(install_plugin_spec, spec)+ except RuntimeError as exc:+ raise HTTPException(status_code=500, detail=str(exc)) from exc+ _refresh_plugin_in_live_registry(spec.id)+ item = spec.model_dump(mode="json")+ item["status"] = "not_connected"+ return {+ "ok": True,+ "plugin": item,+ "detected": {+ "auth": auth,+ "transport": probe.transport,+ "server_name": probe.server_name,+ },+ }diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 80a8467b18..21d015bfc3 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -2832,7 +2832,9 @@ class BaseUrlResponse(BaseModel):@router.put("/providers/{provider_id}/base-url")-async def set_provider_base_url(provider_id: str, body: BaseUrlBody) -> BaseUrlResponse:+async def set_provider_base_url(+ provider_id: str, body: BaseUrlBody, request: Request,+) -> BaseUrlResponse:"""Set (or clear) the server URL of a local/self-hosted provider.Only cards with ``supports_base_url`` accept one (400 otherwise). The URL@@ -2862,6 +2864,26 @@ async def set_provider_base_url(provider_id: str, body: BaseUrlBody) -> BaseUrlRfrom jarvis.core import config_writerconfig_writer.set_provider_base_url(provider_id, cleaned or None)+ # Cached Society and voice instances must not keep the previous server.+ from jarvis.core.config import BrainProviderConfig++ live_brain = getattr(request.app.state, "brain", None)+ for config in (_resolve_cfg(request), getattr(live_brain, "_config", None)):+ if config is None:+ continue+ previous = config.brain.providers.get(provider_id) or BrainProviderConfig()+ config.brain.providers[provider_id] = previous.model_copy(+ update={"base_url": cleaned or None},+ )+ reactivate = getattr(live_brain, "reactivate_provider", None)+ if callable(reactivate):+ reactivate(provider_id)+ await _get_model_catalog(request).invalidate(provider_id)+ from jarvis.agent_runtimes.gateway import invalidate_provider_metadata++ invalidate_provider_metadata(provider_id)+ _health_ledger.forget_providers([provider_id], modality=_health_ledger.MODALITY_BRAIN)+ _invalidate_section_health_state(request)return BaseUrlResponse(provider=provider_id,base_url=cleaned or None,diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 620494b44f..45cc3657b6 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -498,6 +498,7 @@ class WebServer:from .commands_routes import router as commands_routerfrom .computer_use_routes import router as computer_use_routerfrom .computers_routes import router as computers_router+ from .server_pairing_routes import router as server_pairing_routerfrom .contacts_routes import router as contacts_routerfrom .control_routes import router as control_routerfrom .costs_routes import router as costs_router@@ -707,6 +708,7 @@ class WebServer:# Contacts section — user-curated address book (pure file store, no Brain dep).app.include_router(contacts_router)# Settings -> Computers: the user's own servers and local VMs over SSH.+ app.include_router(server_pairing_router)app.include_router(computers_router)# Desktop pets — the `pet` overlay style's pets, look and visibility.app.include_router(pets_router)diff --git a/jarvis/ui/web/server_pairing_routes.py b/jarvis/ui/web/server_pairing_routes.pynew file mode 100644index 0000000000..de112113e3--- /dev/null+++ b/jarvis/ui/web/server_pairing_routes.py@@ -0,0 +1,216 @@+"""One-time server pairing and authenticated access to independent Jarvis instances."""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, HTTPException, Request+from fastapi.responses import HTMLResponse, JSONResponse+from pydantic import BaseModel, Field++from jarvis.computers.pairing_errors import PairingError+from jarvis.ui.web.surface_security import append_session_cookie, is_secure_or_loopback++router = APIRouter(prefix="/api/computers/pairing", tags=["computer-pairing"])+++def get_pairing() -> Any:+ """Keep credential storage and HTTP-client imports off the boot path."""+ from jarvis.computers.pairing import get_pairing as service++ return service()+++class CodeBody(BaseModel):+ code: str = Field(min_length=1, max_length=128, repr=False)+ name: str = Field(default="Jarvis client", min_length=1, max_length=120)+++class ConnectBody(BaseModel):+ host: str = Field(min_length=1, max_length=512)+ code: str = Field(min_length=1, max_length=128, repr=False)+++class TicketBody(BaseModel):+ ticket: str = Field(min_length=43, max_length=43, repr=False)+++def _secure(request: Request) -> None:+ if not is_secure_or_loopback(request.scope):+ raise HTTPException(403, "Server pairing requires HTTPS or a direct loopback connection.")+++def _credential(request: Request) -> str:+ _secure(request)+ scheme, _, value = request.headers.get("authorization", "").partition(" ")+ if scheme.lower() != "bearer" or not value.strip() or len(value) > 128:+ raise HTTPException(401, "A paired server credential is required.")+ return value.strip()+++def _failure(exc: PairingError) -> HTTPException:+ return HTTPException(exc.status, {"message": str(exc), "kind": "pairing"})+++def _json(value: Any) -> JSONResponse:+ return JSONResponse(value, headers={"Cache-Control": "no-store"})++[email protected]("/code", operation_id="computer_pairing_code")+def create_pairing_code(request: Request) -> JSONResponse:+ """Create a five-minute, single-use code granting access to this Jarvis instance."""+ _secure(request)+ try:+ return _json(get_pairing().issue_code())+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/redeem", operation_id="computer_pairing_redeem")+def redeem_pairing_code(request: Request, body: CodeBody) -> JSONResponse:+ """Exchange a one-use code for a revocable server credential."""+ _secure(request)+ try:+ return _json(get_pairing().redeem(body.code, body.name).model_dump())+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/status", operation_id="computer_pairing_status")+def paired_server_status(request: Request) -> JSONResponse:+ """Prove this server accepts the saved pairing credential without calling a model."""+ try:+ service = get_pairing()+ service.authenticate(_credential(request))+ return _json(service.identity().model_dump())+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/launch", operation_id="computer_pairing_launch")+def create_server_ticket(request: Request) -> JSONResponse:+ """Create a single-use browser opening ticket, valid for one minute."""+ try:+ return _json({"ticket": get_pairing().issue_ticket(_credential(request))})+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/disconnect", operation_id="computer_pairing_disconnect")+def disconnect_paired_client(request: Request) -> JSONResponse:+ """Revoke the presented client credential and its unredeemed opening links."""+ try:+ service = get_pairing()+ grant = service.authenticate(_credential(request))+ service.revoke(grant.id)+ return _json({"removed": True})+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/clients", operation_id="computer_pairing_clients")+def list_paired_clients() -> JSONResponse:+ """List clients authorized to open this instance, without their credentials."""+ return _json({"clients": get_pairing().clients()})++[email protected]("/clients/{client_id}", operation_id="computer_pairing_revoke")+def revoke_paired_client(client_id: str) -> JSONResponse:+ """Revoke a client's future access and pending opening links."""+ get_pairing().revoke(client_id)+ return _json({"removed": True})++[email protected]("/servers", operation_id="computer_servers_list")+def list_paired_servers() -> JSONResponse:+ """List saved independent Jarvis servers without their credentials."""+ return _json({"servers": [s.model_dump() for s in get_pairing().servers()]})++[email protected]("/servers", operation_id="computer_servers_add")+async def connect_server(request: Request, body: ConnectBody) -> JSONResponse:+ """Pair with a server and save its validated connection in the local keyring."""+ _secure(request)+ try:+ return _json((await get_pairing().add(body.host, body.code)).model_dump())+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/servers/{server_id}/check", operation_id="computer_servers_check")+async def check_server(server_id: str) -> JSONResponse:+ """Check one saved server with its own credential."""+ try:+ return _json((await get_pairing().check(server_id)).model_dump())+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/servers/{server_id}/open", operation_id="computer_servers_open")+async def open_server(request: Request, server_id: str) -> JSONResponse:+ """Return a one-use link opening the server's authenticated Jarvis UI."""+ _secure(request)+ try:+ return _json({"url": await get_pairing().launch(server_id)})+ except PairingError as exc:+ raise _failure(exc) from exc++[email protected]("/servers/{server_id}", operation_id="computer_servers_remove")+async def remove_server(server_id: str) -> JSONResponse:+ """Revoke the remote credential, then remove the saved connection locally."""+ try:+ await get_pairing().remove(server_id)+ return _json({"removed": True})+ except PairingError as exc:+ raise _failure(exc) from exc+++# The ticket travels only in the fragment, never in access logs or Referer.+# This self-contained page makes the final exchange at the server's own origin.+_ENTER_SCRIPT = """const ticket=location.hash.slice(1);+history.replaceState(null,'',location.pathname);+fetch(location.pathname,{+method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ticket})+}).then(r=>{if(!r.ok)throw Error();location.replace('/');})+.catch(()=>{document.getElementById('state').textContent=+'This link expired or could not connect. Open the server again from Computers.';});"""++[email protected]("/enter", operation_id="computer_pairing_enter_page", response_class=HTMLResponse)+def enter_server_page(request: Request) -> HTMLResponse:+ """Exchange a fragment-only ticket from the server's own browser origin."""+ import base64+ import hashlib++ _secure(request)+ script_hash = base64.b64encode(hashlib.sha256(_ENTER_SCRIPT.encode()).digest()).decode()+ return HTMLResponse(+ '<!doctype html><html lang="en"><meta charset="utf-8">'+ '<meta name="color-scheme" content="light dark">'+ '<title>Opening Jarvis</title><p id="state">Opening your Jarvis server…</p>'+ f"<script>{_ENTER_SCRIPT}</script></html>",+ headers={+ "Cache-Control": "no-store",+ "Referrer-Policy": "no-referrer",+ "Content-Security-Policy": (+ f"default-src 'none'; script-src 'sha256-{script_hash}'; "+ "connect-src 'self'; frame-ancestors 'none'; base-uri 'none'"+ ),+ },+ )++[email protected]("/enter", operation_id="computer_pairing_enter")+def enter_server(request: Request, body: TicketBody) -> JSONResponse:+ """Consume an opening ticket and mint the normal HttpOnly UI session cookie."""+ from jarvis.ui.web.missions_auth import issue_token++ _secure(request)+ try:+ get_pairing().consume_ticket(body.ticket)+ except PairingError as exc:+ raise _failure(exc) from exc+ return append_session_cookie(+ _json({"connected": True}), issue_token(), request.url.scheme == "https"+ )diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 42cefbd33d..bb041ad266 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -2913,7 +2913,8 @@ async def open_external(body: OpenExternalBody) -> dict[str, object]:from jarvis.platform.open_path import open_urlopened = await asyncio.to_thread(open_url, body.url)- log.info("open-external: opened=%s url=%s", opened, body.url)+ # Pairing and OAuth URLs may carry one-time credentials in their fragments.+ log.info("open-external: opened=%s host=%s", opened, parsed.hostname)return {"opened": bool(opened)}diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 710ec3249a..0856c6c035 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -24,6 +24,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom starlette.requests import HTTPConnectionfrom jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name+from jarvis.society.companion import CompanionSkinfrom jarvis.society.events import MsgTypefrom jarvis.society.failure_reasons import FailureReason, retry_actionfrom jarvis.society.memory import MEMORY_SHARE_CAPABILITY, MemoryRefused@@ -905,6 +906,32 @@ async def apply_seed_proposals(body: ApplySeedsBody, request: Request) -> dict[sreturn {"agents": created, "total": len(created)}+# --------------------------------------------------------------- designs++[email protected]("/designs", summary="The person's saved companion designs")+def get_designs() -> dict[str, Any]:+ from jarvis.society import design_library++ return {"designs": design_library.list_designs()}++[email protected]("/designs", summary="Save a companion design for any agent to wear")+def post_design(skin: CompanionSkin) -> dict[str, Any]:+ from jarvis.society import design_library++ return design_library.save_design(skin)++[email protected]("/designs/{design_id}", summary="Delete a saved companion design")+def delete_design(design_id: str) -> dict[str, Any]:+ from jarvis.society import design_library++ if not design_library.delete_design(design_id):+ raise HTTPException(404, "Design not found")+ return {"deleted": design_id}++# --------------------------------------------------------------- providersdiff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.pyindex 21628db2dc..fd571b84fa 100644--- a/jarvis/ui/web/surface_security.py+++ b/jarvis/ui/web/surface_security.py@@ -794,7 +794,16 @@ def _external_http_auth(path: str, method: str) -> bool:def _http_auth_exception(path: str, method: str) -> bool:return (- _is_static_request(path, method)+ # These exact routes authenticate a one-use pairing code, a scoped+ # paired credential, or a one-use opening ticket inside the handler.+ (path == "/api/computers/pairing/redeem" and method == "POST")+ or (path == "/api/computers/pairing/status" and method == "GET")+ or (+ path in {"/api/computers/pairing/launch", "/api/computers/pairing/disconnect"}+ and method == "POST"+ )+ or (path == "/api/computers/pairing/enter" and method in {"GET", "POST"})+ or _is_static_request(path, method)or (path == "/api/health" and method == "GET")or (path == "/api/ui/shell-painted" and method == "POST")# First-boot reads remain public. Mutations use the same authenticateddiff --git a/scripts/measure_boot.py b/scripts/measure_boot.pyindex bc6a3c78bf..3dc6a775cf 100644--- a/scripts/measure_boot.py+++ b/scripts/measure_boot.py@@ -152,6 +152,10 @@ def _bench_env(port: int) -> dict[str, str]:# coerce to bool False but -1 keeps the int field clean."JARVIS__TELEMETRY__FLIGHT_RECORDER_RETENTION_DAYS": "-1","JARVIS__OVERLAY__ENABLED": "false",+ # Desktop companions use ui.orb_style, not the legacy overlay flag.+ # Voice-ready benchmarks must not create a second pet/bar beside+ # the user's running app. Override only this child process's style.+ "JARVIS__UI__ORB_STYLE": "none","JARVIS_VOICE": "0",})diff --git a/tests/contract/fixtures/agent-companion.json b/tests/contract/fixtures/agent-companion.jsonindex b560f9c8b1..db282602e1 100644--- a/tests/contract/fixtures/agent-companion.json+++ b/tests/contract/fixtures/agent-companion.json@@ -5,7 +5,10 @@{"shape":"drop","color":"#FFAA00","eyes":"dots","enabled":true,"sizeM":0.8,"followDistanceM":0.5},{"shape":"hexagon","color":"#7ab6ef","accessories":{"head":"crown","mouth":"cigar","outfit":"suit","held":"future_item_2"}},{"shape":"drop","color":"#79c7c4","pet":"cocoa"},- {"shape":"circle","color":"#8b5cf6","pet":"u0123456789abcdef"}+ {"shape":"circle","color":"#8b5cf6","pet":"u0123456789abcdef"},+ {"shape":"circle","color":"#7a3fb8","skin":{"colors":["#e05cc5","#6a2fc2","#160f3d"],"pattern":"radial","angle":135,"effect":"stars","name":"Galaxy"}},+ {"shape":"drop","color":"#123456","skin":{"colors":["#000000","#FFFFFF"]}},+ {"shape":"hexagon","color":"#123456","skin":{"colors":["#111111","#222222","#333333","#444444"],"pattern":"linear","angle":359,"effect":"futureeffect","name":""}}],"invalid": [{"shape":"unknown","color":"#123456"},@@ -26,6 +29,20 @@{"shape":"circle","color":"#123456","pet":"Cocoa"},{"shape":"circle","color":"#123456","pet":"../pets/cocoa"},{"shape":"circle","color":"#123456","pet":""},- {"shape":"circle","color":"#123456","pet":7}+ {"shape":"circle","color":"#123456","pet":7},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111"]}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222","#333333","#444444","#555555"]}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#fff","#000000"]}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","url(x)"]}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"pattern":"conic"}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"angle":360}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"angle":-1}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"angle":12.5}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"angle":"90"}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"effect":"Stars!"}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"name":"line\nbreak"}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}},+ {"shape":"circle","color":"#123456","skin":{"colors":["#111111","#222222"],"url":"https://example.org"}},+ {"shape":"circle","color":"#123456","skin":"galaxy"}]}diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 6645e508ee..8b45b2b2d0 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -48,6 +48,16 @@ COVERED: Final[dict[str, str]] = {#: REST route -> why an MCP client does not get it. Each line is a decision.WITHHELD: Final[dict[str, str]] = {+ "GET /api/society/designs": (+ "the saved companion-design library belongs to the owner's appearance "+ "editor; a remote client changes an agent's look through its profile"+ ),+ "POST /api/society/designs": (+ "saving a companion design is an appearance-editor action for the owner"+ ),+ "DELETE /api/society/designs/{design_id}": (+ "deleting a saved companion design is an appearance-editor action for the owner"+ ),"GET /api/society/provider-prefs": ("which providers the agents may use is a settings page for the owner; ""a remote client already sees the effective seat on each agent"diff --git a/tests/contract/test_chat_tool_choices.py b/tests/contract/test_chat_tool_choices.pyindex 11ab9cc8bd..44d56a2f94 100644--- a/tests/contract/test_chat_tool_choices.py+++ b/tests/contract/test_chat_tool_choices.py@@ -203,7 +203,7 @@ def test_wire_category_and_fields_match_typescript():union = re.search(r"export type ToolCategory\s*=\s*([^;]+);", source).group(1)assert set(re.findall(r'"([a-z]+)"', union)) == set(get_args(Category))interface = source.split("export interface ToolChoice {", 1)[1].split("}", 1)[0]- assert set(re.findall(r"^\s*(\w+):", interface, re.M)) == set(ToolChoice.model_fields)+ assert set(re.findall(r"^\s*(\w+)\??:", interface, re.M)) == set(ToolChoice.model_fields)for locale in ("en", "de", "es"):data = json.loads((root / f"jarvis/ui/web/frontend/src/i18n/locales/{locale}.json").read_text(diff --git a/tests/contract/test_routine_chats.py b/tests/contract/test_routine_chats.pyindex 7f069cb7c6..cdf2338534 100644--- a/tests/contract/test_routine_chats.py+++ b/tests/contract/test_routine_chats.py@@ -54,6 +54,11 @@ async def test_persisted_run_links_survive_reopening_without_loading_main_chat(wawait store.close()+#: Hang guards, not speed budgets: a loaded Windows runner needs more than a+#: few seconds to start a chat turn, and a real hang still fails.+_HANG_GUARD_S = 15++async def test_busy_main_chat_queues_routine_without_mixing_transcripts(world, monkeypatch):runtime, service, main, brain = worldstarted = asyncio.Event()@@ -68,7 +73,7 @@ async def test_busy_main_chat_queues_routine_without_mixing_transcripts(world, mmonkeypatch.setattr(brain, "generate", respond)await service.send(main.session_id, "Main conversation")- await asyncio.wait_for(started.wait(), 2)+ await asyncio.wait_for(started.wait(), _HANG_GUARD_S)created = asyncio.Event()create_session = service.store.create_session@@ -82,10 +87,10 @@ async def test_busy_main_chat_queues_routine_without_mixing_transcripts(world, mrun_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail"))try:- await asyncio.wait_for(created.wait(), 2)+ await asyncio.wait_for(created.wait(), _HANG_GUARD_S)assert service.is_running(main.session_id)release.set()- assert await asyncio.wait_for(routine, 3) == brain.reply+ assert await asyncio.wait_for(routine, _HANG_GUARD_S) == brain.replymessages = [e for e in service.store.list_events(main.session_id) if e["kind"] == "user_message"]@@ -132,7 +137,7 @@ async def test_cancelling_routine_preserves_main_chat(world, monkeypatch, via_chrun_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail"))try:- await asyncio.wait_for(started.wait(), 2)+ await asyncio.wait_for(started.wait(), _HANG_GUARD_S)if via_chat:session = next(sdiff --git a/tests/unit/agent_runtimes/test_model_limits.py b/tests/unit/agent_runtimes/test_model_limits.pyindex aaa6509560..e532d98543 100644--- a/tests/unit/agent_runtimes/test_model_limits.py+++ b/tests/unit/agent_runtimes/test_model_limits.py@@ -53,6 +53,15 @@ def test_per_model_output_and_large_catalog_limits():assert resolve_limits(config(8192, 64000), "ollama", "small", small).max_output_tokens == 1024+def test_latest_alias_never_bypasses_a_saved_smaller_context():+ cfg = JarvisConfig()+ cfg.brain.providers["ollama"] = BrainProviderConfig(models={+ "example": OllamaModelOptions(num_ctx=8192, num_predict=1024),+ })+ metadata = ModelInfo("example:latest", "Example", context_length=131072)+ assert resolve_limits(cfg, "ollama", "example:latest", metadata) == ModelLimits(8192, 1024)++@pytest.mark.parametrize("context,output", [(8192, 1024), (1_000_000, 65536)])def test_both_runtime_configs_use_the_resolved_model(context, output, tmp_path):route = ModelRoute(diff --git a/tests/unit/agentic_ide/test_seat_handoff.py b/tests/unit/agentic_ide/test_seat_handoff.pynew file mode 100644index 0000000000..df15c45256--- /dev/null+++ b/tests/unit/agentic_ide/test_seat_handoff.py@@ -0,0 +1,167 @@+"""A conversation follows its agent from one subscription seat to another.++What these pin down is the one failure a seat switch must never have: the+agent restarting on the new seat with ``--resume <id>`` and finding nothing,+because each seat files its conversations inside its own directory.+"""++from __future__ import annotations++import json+import os+import time+from pathlib import Path++from jarvis.agentic_ide import seat_handoff++SID = "0f4d7c1e-1111-4222-8333-944455556666"+++def _claude_seat(root: Path, name: str, lines: list[dict], *, mtime: float | None = None) -> Path:+ home = root / name+ folder = home / "projects" / "C--work-repo"+ folder.mkdir(parents=True)+ transcript = folder / f"{SID}.jsonl"+ transcript.write_text("".join(json.dumps(line) + "\n" for line in lines), encoding="utf-8")+ if mtime is not None:+ os.utime(transcript, (mtime, mtime))+ return home+++def test_claude_conversation_is_carried_with_its_side_files(tmp_path: Path) -> None:+ source = _claude_seat(tmp_path, "a", [{"type": "user", "message": {"content": "hi"}}])+ (source / "projects" / "C--work-repo" / SID / "subagents").mkdir(parents=True)+ (source / "projects" / "C--work-repo" / SID / "subagents" / "x.jsonl").write_text("{}\n")+ (source / "file-history" / SID).mkdir(parents=True)+ (source / "file-history" / SID / "snap").write_text("v1")+ target = tmp_path / "b"++ assert seat_handoff.carry_conversation("claude_session", SID, target, [source, target])++ carried = target / "projects" / "C--work-repo" / f"{SID}.jsonl"+ assert carried.read_text(encoding="utf-8").startswith('{"type": "user"')+ assert (target / "projects" / "C--work-repo" / SID / "subagents" / "x.jsonl").is_file()+ assert (target / "file-history" / SID / "snap").read_text() == "v1"+++def test_the_newest_copy_wins_and_an_older_one_never_overwrites_it(tmp_path: Path) -> None:+ old = time.time() - 600+ stale = _claude_seat(tmp_path, "a", [{"n": 1}], mtime=old)+ fresh = _claude_seat(tmp_path, "b", [{"n": 1}, {"n": 2}], mtime=old + 300)++ # Switching back to the seat holding the older prefix brings the newest.+ assert seat_handoff.carry_conversation("claude_session", SID, stale, [stale, fresh])+ path = stale / "projects" / "C--work-repo" / f"{SID}.jsonl"+ assert path.read_text(encoding="utf-8").count("\n") == 2++ # The newer seat is left exactly as it is.+ assert seat_handoff.carry_conversation("claude_session", SID, fresh, [stale, fresh])+ assert (fresh / "projects" / "C--work-repo" / f"{SID}.jsonl").read_text().count("\n") == 2+++def test_nothing_to_carry_answers_honestly(tmp_path: Path) -> None:+ empty_a, empty_b = tmp_path / "a", tmp_path / "b"+ assert not seat_handoff.carry_conversation("claude_session", SID, empty_b, [empty_a, empty_b])+ assert not seat_handoff.carry_conversation("kimi_session", SID, empty_b, [empty_a])+ assert not seat_handoff.carry_conversation("claude_session", "../evil", empty_b, [empty_a])+++def test_codex_rollout_is_carried_to_the_same_day_folder(tmp_path: Path) -> None:+ source = tmp_path / "a"+ day = source / "sessions" / "2026" / "10" / "08"+ day.mkdir(parents=True)+ rollout = day / f"rollout-2026-10-08T10-00-00-{SID}.jsonl"+ rollout.write_text('{"type":"session_meta"}\n', encoding="utf-8")+ target = tmp_path / "b"++ assert seat_handoff.carry_conversation("codex_rollout", SID, target, [source, target])+ assert (target / "sessions" / "2026" / "10" / "08" / rollout.name).is_file()+++def test_grok_session_folder_is_carried(tmp_path: Path) -> None:+ source = tmp_path / "a"+ folder = source / "sessions" / "work%20repo" / SID+ folder.mkdir(parents=True)+ (folder / "updates.jsonl").write_text('{"sessionUpdate":"user_message_chunk"}\n')+ target = tmp_path / "b"++ assert seat_handoff.carry_conversation("grok_session", SID, target, [source, target])+ assert (target / "sessions" / "work%20repo" / SID / "updates.jsonl").is_file()+++# ------------------------------------------------------------- limit stops+++def _iso(at: float) -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(at))+++def _claude_limit(at: float) -> dict:+ return {+ "type": "assistant",+ "timestamp": _iso(at),+ "isApiErrorMessage": True,+ "error": "rate_limit",+ "apiErrorStatus": 429,+ "message": {"role": "assistant", "content": [{"type": "text", "text": "limit"}]},+ }+++def _claude_user(at: float, text: str = "go on") -> dict:+ return {"type": "user", "timestamp": _iso(at), "message": {"content": text}}+++def test_a_claude_turn_cut_off_by_the_limit_is_read_from_the_transcript(tmp_path: Path) -> None:+ now = time.time()+ home = _claude_seat(tmp_path, "a", [_claude_user(now - 60), _claude_limit(now - 30)])+ stop = seat_handoff.limit_stop("claude_session", SID, home, now=now)+ assert stop is not None and abs(stop - (now - 30)) < 2+++def test_a_limit_the_user_already_typed_past_is_history(tmp_path: Path) -> None:+ now = time.time()+ home = _claude_seat(+ tmp_path, "a", [_claude_limit(now - 90), _claude_user(now - 60, "continue")]+ )+ assert seat_handoff.limit_stop("claude_session", SID, home, now=now) is None+++def test_a_handled_stop_does_not_fire_again_on_the_new_seat(tmp_path: Path) -> None:+ now = time.time()+ home = _claude_seat(tmp_path, "a", [_claude_user(now - 60), _claude_limit(now - 30)])+ stop = seat_handoff.limit_stop("claude_session", SID, home, now=now)+ assert stop is not None+ assert seat_handoff.limit_stop("claude_session", SID, home, after=stop, now=now) is None+++def test_an_old_limit_stop_is_stale(tmp_path: Path) -> None:+ now = time.time()+ old = now - seat_handoff.LIMIT_STALE_S - 60+ home = _claude_seat(tmp_path, "a", [_claude_user(old - 5), _claude_limit(old)])+ assert seat_handoff.limit_stop("claude_session", SID, home, now=now) is None+++def test_an_ordinary_api_error_is_not_a_limit(tmp_path: Path) -> None:+ now = time.time()+ row = {**_claude_limit(now - 10), "error": "server_error", "apiErrorStatus": 529}+ home = _claude_seat(tmp_path, "a", [_claude_user(now - 60), row])+ assert seat_handoff.limit_stop("claude_session", SID, home, now=now) is None+++def test_a_codex_usage_limit_error_is_read(tmp_path: Path) -> None:+ now = time.time()+ home = tmp_path / "codex"+ day = home / "sessions" / "2026" / "10" / "08"+ day.mkdir(parents=True)+ rows = [+ {"timestamp": _iso(now - 60), "type": "event_msg", "payload": {"type": "user_message"}},+ {+ "timestamp": _iso(now - 20),+ "type": "event_msg",+ "payload": {"type": "error", "message": "You've hit your usage limit. Try again."},+ },+ ]+ (day / f"rollout-x-{SID}.jsonl").write_text(+ "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8"+ )+ assert seat_handoff.limit_stop("codex_rollout", SID, home, now=now) is not Nonediff --git a/tests/unit/agentic_ide/test_seat_move.py b/tests/unit/agentic_ide/test_seat_move.pynew file mode 100644index 0000000000..f2cbd980bd--- /dev/null+++ b/tests/unit/agentic_ide/test_seat_move.py@@ -0,0 +1,126 @@+"""A running pane moved to another subscription seat keeps its conversation.++End to end through the real registry: the agent's process is ended, the pane+is re-pointed at the new seat, the conversation file is carried into that+seat's history, and the CLI comes back with ``--resume <id>`` under the new+seat's config dir. The fake PTY stands in for the process; the files are real,+because "is the conversation there?" is the question under test.+"""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from jarvis import agent_accounts+from jarvis.agentic_ide import session as ide+from tests.fakes.fake_pty_manager import FakePtyManager++[email protected](autouse=True)+def _plain_shell(monkeypatch: pytest.MonkeyPatch) -> None:+ for marker in ide.PARENT_AGENT_SESSION_VARS:+ monkeypatch.delenv(marker, raising=False)+++class _ExitingPty(FakePtyManager):+ """Reports the exit of a closed process, as a real local PTY does."""++ def close(self, terminal_id: str) -> bool:+ callbacks = self._callbacks.get(terminal_id)+ closed = super().close(terminal_id)+ if callbacks is not None:+ asyncio.ensure_future(callbacks[1](terminal_id, 1))+ return closed+++def fake_pty() -> FakePtyManager:+ return _ExitingPty()+++def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> ide.Registry:+ monkeypatch.setattr(ide, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ return ide.Registry(pty_manager=fake_pty)+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def test_a_running_pane_resumes_its_conversation_on_the_new_seat(+ registry, fake_pty, tmp_path, existing_conversation+):+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit)+ term = registry.session.find("T1")+ conversation = term.resume.id+ existing_conversation(conversation) # written on the built-in seat+ first_process = term.pty_id++ outcome = await registry.move_to_seat(term, second.id)++ assert outcome == "moved"+ assert term.account == second.id and term.account_pinned is False+ assert first_process in fake_pty.closed+ spawn = fake_pty.spawns[-1]+ assert spawn["argv"][-2:] == ("--resume", conversation)+ assert spawn["env"]["CLAUDE_CONFIG_DIR"] == str(second.config_dir)+ carried = list((second.config_dir / "projects").glob(f"*/{conversation}.jsonl"))+ assert len(carried) == 1+ assert term.status == "live" and term.resumed is True+++async def test_moving_back_brings_the_newer_conversation_home(+ registry, fake_pty, tmp_path, existing_conversation+):+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit)+ term = registry.session.find("T1")+ conversation = term.resume.id+ existing_conversation(conversation)+ await registry.move_to_seat(term, second.id)+ # The agent worked on the second seat: its copy grew.+ on_second = next((second.config_dir / "projects").glob(f"*/{conversation}.jsonl"))+ on_second.write_text("{}\n{}\n{}\n", encoding="utf-8")++ await registry.move_to_seat(term, agent_accounts.builtin_id("claude"))++ home = Path(agent_accounts.native_dir("claude"))+ back = next((home / "projects").glob(f"*/{conversation}.jsonl"))+ assert back.read_text(encoding="utf-8").count("\n") == 3+ assert fake_pty.spawns[-1]["argv"][-2:] == ("--resume", conversation)+++async def test_a_stopped_pane_is_only_repointed(+ registry, fake_pty, tmp_path, existing_conversation+):+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit)+ term = registry.session.find("T1")+ existing_conversation(term.resume.id)+ await fake_pty.die(term.pty_id, 0)+ spawned = len(fake_pty.spawns)++ assert await registry.move_to_seat(term, second.id) == "repointed"+ assert term.account == second.id+ assert len(fake_pty.spawns) == spawned # nothing starts until the user asks+++async def test_a_pane_already_on_the_seat_is_left_alone(registry, fake_pty, tmp_path):+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "T1"}])+ await registry.attach("T1", 80, 24, _noop, _noop_exit)+ term = registry.session.find("T1")++ assert await registry.move_to_seat(term, term.account) == "unchanged"+ assert len(fake_pty.spawns) == 1diff --git a/tests/unit/agentic_ide/test_seat_switch.py b/tests/unit/agentic_ide/test_seat_switch.pynew file mode 100644index 0000000000..d8a97224f5--- /dev/null+++ b/tests/unit/agentic_ide/test_seat_switch.py@@ -0,0 +1,431 @@+"""Running agents follow a seat switch, and a spent seat hands its work on.++The registry here is a small stand-in with the four things the switch uses+(``sessions``, ``turn_in_progress``, ``move_to_seat``, ``send_prompt``); the+real restart path is covered by the Agentic-IDE suites. What these pin down is+the policy: who moves now, who waits for their turn, who never moves, and+where the work goes.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis import agent_accounts+from jarvis.agent_accounts import AccountSnapshot, AgentAccount+from jarvis.agent_usage import AccountUsage, UsageWindow+from jarvis.agentic_ide import seat_switch++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(agent_accounts, "_store_path", lambda: tmp_path / "accounts.json")+ monkeypatch.setattr(agent_accounts, "_accounts_root", lambda: tmp_path / "dirs")+ monkeypatch.setattr(+ agent_accounts, "_native_dir", lambda platform: tmp_path / "native" / platform+ )+ monkeypatch.setattr(seat_switch, "_handled_path", lambda: tmp_path / "handled.json")+ seat_switch.reset()+ yield+ seat_switch.reset()+++@dataclass+class _Pane:+ name: str+ account: str+ agent: str = "claude"+ status: str = "live"+ pty_id: str | None = "pty"+ computer_id: str = ""+ history_id: str = ""+ pending_account: str | None = None+ last_input_at: float | None = None+ busy: str = ""+ resume: Any = None+ limit_handled_at: float = 0.0++ def __post_init__(self) -> None:+ if self.resume is None:+ self.resume = SimpleNamespace(id=f"conv-{self.name}", captured_at=0.0)+++@dataclass+class _Workspace:+ id: str+ terminals: list[_Pane]+++@dataclass+class _Registry:+ sessions: list[_Workspace]+ moves: list[tuple[str, str]] = field(default_factory=list)+ prompts: list[str] = field(default_factory=list)++ async def turn_in_progress(self, term: _Pane) -> str:+ return term.busy++ async def move_to_seat(self, term: _Pane, account_id: str, *, idle: Any = None) -> str:+ live = term.status == "live"+ if live and idle is not None and not await idle(term):+ term.pending_account = account_id+ return "deferred"+ self.moves.append((term.name, account_id))+ term.account = account_id+ term.pending_account = None+ return "moved" if live else "repointed"++ async def send_prompt(self, wanted: str, text: str, **_kwargs: Any) -> None:+ self.prompts.append(wanted)+++def _seats(email_of: dict[str, str | None]) -> list[AgentAccount]:+ seats = [agent_accounts.active_account("claude")]+ for label in email_of:+ if label != "default":+ seats.append(agent_accounts.create_account("claude", label))+ return seats+++def _fake_snapshots(+ monkeypatch: pytest.MonkeyPatch, seats: list[AgentAccount], emails: list[str | None]+) -> None:+ def snapshots(platform: str) -> list[AccountSnapshot]:+ return [+ AccountSnapshot(+ account=seat,+ connected=True,+ mode="subscription",+ message="",+ email=email,+ )+ for seat, email in zip(seats, emails, strict=True)+ ]++ monkeypatch.setattr(agent_accounts, "snapshots", snapshots)+++def _usage(account: AgentAccount, percent: float) -> AccountUsage:+ return AccountUsage(+ account_id=account.id,+ platform="claude",+ status="ok",+ windows=(UsageWindow(kind="session", percent=percent, severity="normal"),),+ )+++def test_one_click_moves_idle_agents_now_and_working_ones_after_their_turn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Second": None, "Third": None})+ default, second, third = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x", "c@x"])+ idle = _Pane("T1", default.id)+ working = _Pane("T2", default.id, busy="working")+ stopped = _Pane("T3", third.id, status="exited", pty_id=None)+ remote = _Pane("T4", default.id, computer_id="vps")+ registry = _Registry([_Workspace("w", [idle, working, stopped, remote])])++ event = asyncio.run(seat_switch.switch_seat(registry, "claude", second.id))++ assert agent_accounts.active_account("claude").id == second.id+ assert sorted(registry.moves) == [("T1", second.id), ("T3", second.id)]+ assert working.pending_account == second.id+ assert remote.account == default.id # its CLI uses the server's own login+ assert (event.moved, event.queued) == (2, 1)+ assert registry.prompts == [] # nobody was cut off, nobody is told anything+++def test_a_pane_being_typed_into_waits(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Second": None})+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ typing = _Pane("T1", seats[0].id, last_input_at=seat_switch._now())+ registry = _Registry([_Workspace("w", [typing])])++ asyncio.run(seat_switch.switch_seat(registry, "claude", seats[1].id))++ assert registry.moves == []+ assert typing.pending_account == seats[1].id+++def test_panes_on_the_same_login_as_the_target_stay_put(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Twin": None})+ default, twin = seats+ _fake_snapshots(monkeypatch, seats, ["same@x", "same@x"])+ pane = _Pane("T1", default.id)+ registry = _Registry([_Workspace("w", [pane])])++ asyncio.run(seat_switch.switch_seat(registry, "claude", twin.id))++ assert registry.moves == [] # one subscription under two names: nothing to gain+++def test_the_next_seat_is_a_different_login_with_the_most_budget(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Twin": None, "Busy": None, "Fresh": None})+ default, twin, busy, fresh = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "a@x", "b@x", "c@x"])+ usage = {+ default.id: _usage(default, 99),+ twin.id: _usage(twin, 99),+ busy.id: _usage(busy, 60),+ fresh.id: _usage(fresh, 10),+ }+ assert seat_switch.choose_seat("claude", {default.id}, usage, 97).id == fresh.id+ # The active seat wins whenever it is eligible at all.+ assert seat_switch.choose_seat("claude", {default.id}, usage, 97, prefer=busy.id).id == busy.id+ # A seat past the threshold, or out of rotation, is never the answer.+ usage[fresh.id] = _usage(fresh, 98)+ seat_switch._STATE.exhausted[busy.id] = seat_switch._now() + 60+ assert seat_switch.choose_seat("claude", {default.id}, usage, 97) is None+++def test_a_window_that_already_reset_counts_as_empty() -> None:+ account = agent_accounts.active_account("claude")+ reading = AccountUsage(+ account_id=account.id,+ platform="claude",+ status="ok",+ windows=(+ UsageWindow(+ kind="session", percent=100, severity="critical", resets_at="2020-01-01T00:00:00Z"+ ),+ UsageWindow(kind="weekly", percent=40, severity="normal"),+ ),+ )+ assert seat_switch.spent_percent(reading) == 40+++def test_a_limit_stop_moves_the_work_and_tells_it_to_continue(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Second": None, "Other": None})+ default, second, other = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x", "c@x"])+ agent_accounts.set_active("claude", second.id)+ cut_off = _Pane("T1", default.id, history_id="h1", busy="working")+ sibling = _Pane("T2", default.id, history_id="h2")+ elsewhere = _Pane("T3", other.id, history_id="h3")+ registry = _Registry([_Workspace("w", [cut_off, sibling, elsewhere])])+ monkeypatch.setattr(+ seat_switch, "_limit_stops", lambda _r: [(registry.sessions[0], cut_off, 1000.0)]+ )+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: {})++ async def run() -> None:+ await seat_switch._handle_limit_stops(registry, 97.0)+ await asyncio.sleep(0) # let the continue prompt go out++ asyncio.run(run())++ # The active seat had budget, so the work went there — not to a third seat.+ assert sorted(registry.moves) == [("T1", second.id), ("T2", second.id)]+ assert elsewhere.account == other.id # a healthy seat's work is not touched+ assert registry.prompts == ["pane:h1"]+ assert cut_off.limit_handled_at == 1000.0+ assert seat_switch.is_exhausted(default.id)+++def test_with_no_seat_left_nothing_moves_and_it_is_said_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id, history_id="h1")+ registry = _Registry([_Workspace("w", [pane])])+ seat_switch._STATE.exhausted[second.id] = seat_switch._now() + 600+ monkeypatch.setattr(+ seat_switch, "_limit_stops", lambda _r: [(registry.sessions[0], pane, 1000.0)]+ )+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: {})++ asyncio.run(seat_switch._handle_limit_stops(registry, 97.0))+ asyncio.run(seat_switch._handle_limit_stops(registry, 97.0))++ assert registry.moves == []+ reports = [e for e in seat_switch.status()["events"] if e["reason"] == "no_seat"]+ assert len(reports) == 1+++def test_a_nearly_spent_seat_hands_its_idle_work_on(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id)+ working = _Pane("T2", default.id, busy="working")+ registry = _Registry([_Workspace("w", [pane, working])])+ readings = {default.id: _usage(default, 98), second.id: _usage(second, 20)}+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: readings)++ asyncio.run(seat_switch._check_thresholds(registry, 97.0))++ assert agent_accounts.active_account("claude").id == second.id+ assert registry.moves == [("T1", second.id)]+ assert working.pending_account == second.id+ assert registry.prompts == []+++def test_a_thread_on_a_spent_seat_runs_on_the_active_one(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ agent_accounts,+ "describe",+ lambda account: AccountSnapshot(+ account=account, connected=True, mode="subscription", message=""+ ),+ )+ default = agent_accounts.active_account("claude")+ second = agent_accounts.create_account("claude", "Second")+ agent_accounts.set_active("claude", second.id)+ assert seat_switch.preferred_seat("claude", default.id) is None+ seat_switch._STATE.exhausted[default.id] = seat_switch._now() + 60+ assert seat_switch.preferred_seat("claude", default.id) == second.id+ agent_accounts.set_auto_switch(enabled=False)+ assert seat_switch.preferred_seat("claude", default.id) is None+++def test_auto_switch_setting_defaults_on_clamps_and_survives_other_writes() -> None:+ assert agent_accounts.auto_switch().enabled is True+ assert agent_accounts.auto_switch().at_percent == agent_accounts.DEFAULT_SWITCH_AT_PERCENT+ assert agent_accounts.set_auto_switch(at_percent=10).at_percent == 50.0+ agent_accounts.set_auto_switch(enabled=False, at_percent=95)+ agent_accounts.create_account("claude", "Later") # another writer of the store+ choice = agent_accounts.auto_switch()+ assert (choice.enabled, choice.at_percent) == (False, 95.0)+++def test_a_one_model_budget_does_not_move_all_work_ahead_of_time(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id)+ registry = _Registry([_Workspace("w", [pane])])+ scoped = AccountUsage(+ account_id=default.id,+ platform="claude",+ status="ok",+ windows=(+ UsageWindow(kind="session", percent=20, severity="normal"),+ UsageWindow(kind="weekly_scoped", percent=100, severity="critical", scope_label="M"),+ ),+ )+ readings = {default.id: scoped, second.id: _usage(second, 5)}+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: readings)++ asyncio.run(seat_switch._check_thresholds(registry, 97.0))++ # Agents on other models still have the whole plan; a turn that does run+ # into the one-model budget is refused and moved by the limit-stop path.+ assert registry.moves == []+ assert seat_switch.spent_percent(scoped) == 100+ assert seat_switch.spent_percent(scoped, scoped=False) == 20+++def test_an_answered_stop_survives_a_restart(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id, history_id="h1")+ registry = _Registry([_Workspace("w", [pane])])+ monkeypatch.setattr(+ seat_switch, "_limit_stops", lambda _r: [(registry.sessions[0], pane, 1000.0)]+ )+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: {})+ asyncio.run(seat_switch._handle_limit_stops(registry, 97.0))+ assert pane.account == second.id++ # A restarted app has fresh panes and an empty memory, but the stop that+ # was answered must not move the work a second time.+ monkeypatch.setattr(seat_switch, "_HANDLED", None)+ assert seat_switch.handled_stop(pane.resume.id) == 1000.0+++def test_a_pane_that_became_busy_is_not_cut_off(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Second": None})+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", seats[0].id)+ registry = _Registry([_Workspace("w", [pane])])+ original = registry.move_to_seat++ async def prompt_lands_first(term: _Pane, account_id: str, *, idle: Any = None) -> str:+ term.busy = "working" # a prompt arrived while the switch was on its way+ return await original(term, account_id, idle=idle)++ monkeypatch.setattr(registry, "move_to_seat", prompt_lands_first)+ event = asyncio.run(seat_switch.switch_seat(registry, "claude", seats[1].id))++ assert registry.moves == []+ assert pane.pending_account == seats[1].id+ assert (event.moved, event.queued) == (0, 1)+++def test_a_manual_pick_is_not_undone_by_the_threshold(monkeypatch: pytest.MonkeyPatch) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id)+ registry = _Registry([_Workspace("w", [pane])])+ asyncio.run(seat_switch.switch_seat(registry, "claude", default.id))+ readings = {default.id: _usage(default, 98), second.id: _usage(second, 5)}+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: readings)++ asyncio.run(seat_switch._check_thresholds(registry, 97.0))++ assert registry.moves == []+ assert agent_accounts.active_account("claude").id == default.id+++def test_a_thread_is_never_rerouted_onto_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ default = agent_accounts.active_account("claude")+ keyed = agent_accounts.create_account("claude", "Key")+ agent_accounts.set_active("claude", keyed.id)+ seat_switch._STATE.exhausted[default.id] = seat_switch._now() + 60+ monkeypatch.setattr(+ agent_accounts,+ "describe",+ lambda account: AccountSnapshot(+ account=account, connected=True, mode="api_key", message=""+ ),+ )+ assert seat_switch.preferred_seat("claude", default.id) is None+++def test_with_nowhere_to_go_a_refilled_seat_carries_on_in_place(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seats = _seats({"default": None, "Second": None})+ default, second = seats+ _fake_snapshots(monkeypatch, seats, ["a@x", "b@x"])+ pane = _Pane("T1", default.id, history_id="h1")+ registry = _Registry([_Workspace("w", [pane])])+ seat_switch._STATE.exhausted[second.id] = seat_switch._now() + 600+ monkeypatch.setattr(+ seat_switch, "_limit_stops", lambda _r: [(registry.sessions[0], pane, 1000.0)]+ )+ readings: dict[str, AccountUsage] = {default.id: _usage(default, 100)}+ monkeypatch.setattr(seat_switch, "_cached_usage", lambda _p: readings)++ async def run() -> None:+ await seat_switch._handle_limit_stops(registry, 97.0) # still spent: waits+ assert registry.prompts == []+ seat_switch._STATE.exhausted[default.id] = seat_switch._now() - 1 # refill time passed+ readings[default.id] = _usage(default, 3) # and the reading agrees+ await seat_switch._handle_limit_stops(registry, 97.0)+ await asyncio.sleep(0)++ asyncio.run(run())++ assert registry.moves == []+ assert registry.prompts == ["pane:h1"]+ assert seat_switch.handled_stop(pane.resume.id) == 1000.0diff --git a/tests/unit/brain/test_turn_override.py b/tests/unit/brain/test_turn_override.pyindex 6247f1b178..86e433c0a7 100644--- a/tests/unit/brain/test_turn_override.py+++ b/tests/unit/brain/test_turn_override.py@@ -72,7 +72,7 @@ def test_override_chain_is_exactly_the_pick() -> None:assert mgr._router_lead_key is None-def test_override_on_a_tool_incapable_pick_keeps_the_router_lead() -> None:+def test_override_on_a_tool_incapable_pick_never_bills_another_provider() -> None:mgr = _manager()scoped, unscoped = _seed(mgr, scoped_text="x")unscoped.supports_tools = False # the capability probe reads the unscoped instance@@ -89,9 +89,9 @@ def test_override_on_a_tool_incapable_pick_keeps_the_router_lead() -> None:chain = mgr._build_fallback_chain("deep")finally:_TURN_OVERRIDE.reset(token)- assert chain == [("gemini", "gemini-flash"), (PICK, PICK_MODEL)]- assert mgr._router_lead_key == ("gemini", "gemini-flash")- assert seen["exclude"] == PICK, "the lead is picked around the PICK, not the active brain"+ assert chain == [(PICK, PICK_MODEL)]+ assert mgr._router_lead_key is None+ assert seen == {}, "an explicit pick does not authorize helper providers"def test_without_an_override_the_chain_is_the_classic_one() -> None:@@ -210,10 +210,8 @@ async def test_a_voice_turn_feeds_the_brain_tabs_health() -> None:@pytest.mark.asyncio-async def test_a_fall_through_to_the_pick_never_announces_a_brain_switch() -> None:- """Review 2026-08-25: the router lead falls through to the pick at chain index 1,- and that used to publish BrainProviderSwitched — the sidebar then showed- "Brain -> <chat model>" although the live brain had not moved."""+async def test_a_tool_incapable_pick_never_calls_or_announces_a_helper() -> None:+ """The selected seat answers without billing or announcing another provider."""from jarvis.core.events import BrainProviderSwitchedmgr = _manager()@@ -240,8 +238,8 @@ async def test_a_fall_through_to_the_pick_never_announces_a_brain_switch() -> No)assert "PICK_ANSWER" in reply and "LEAD_TALKED" not in reply- assert lead.calls and scoped.calls, "the lead ran first, the pick answered"- assert switches == [], "a pick answering after its lead is the plan, not a switch"+ assert not lead.calls and scoped.calls, "only the selected seat may answer"+ assert switches == [], "an explicit model pick leaves the active voice brain alone"assert mgr._active_name == TALKERdiff --git a/tests/unit/ci/test_boot_benchmark_overlay.py b/tests/unit/ci/test_boot_benchmark_overlay.pynew file mode 100644index 0000000000..675aa6630f--- /dev/null+++ b/tests/unit/ci/test_boot_benchmark_overlay.py@@ -0,0 +1,47 @@+"""Boot measurements must not draw a second desktop companion."""++from __future__ import annotations++import os+from pathlib import Path++import pytest++from jarvis.core.config import load_config+from jarvis.core.instance import InstanceIdentity+from jarvis.ui.desktop_app import boot_overlay_style+from jarvis.ui.overlay_styles import OVERLAY_STYLES+from scripts.measure_boot import _bench_env++[email protected]("style", OVERLAY_STYLES)[email protected]("voice", (False, True), ids=("window-only", "voice-ready"))+def test_benchmark_disables_companion_without_changing_user_settings(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, style: str, voice: bool+) -> None:+ for key in tuple(os.environ):+ if key.startswith("JARVIS_"):+ monkeypatch.delenv(key)+ config_file = tmp_path / "jarvis.toml"+ saved = f'[ui]\norb_style = "{style}"\n[overlay]\nenabled = true\n'+ config_file.write_text(saved, encoding="utf-8")+ # An inherited preference must not defeat the benchmark's isolation either.+ monkeypatch.setenv("JARVIS__UI__ORB_STYLE", style)+ parent_env = dict(os.environ)++ env = _bench_env(49152)+ if voice:+ # The desktop TTU harness re-enables speech after building this env.+ env["JARVIS_VOICE"] = "1"+ assert dict(os.environ) == parent_env+ with monkeypatch.context() as child:+ for key, value in env.items():+ child.setenv(key, value)+ config = load_config(config_file=config_file, profile="default")+ assert boot_overlay_style(+ config.ui.orb_style, instance=InstanceIdentity("default")+ ) == "none"+ assert os.environ["JARVIS_VOICE"] == ("1" if voice else "0")++ assert config_file.read_text(encoding="utf-8") == saved+ assert dict(os.environ) == parent_envdiff --git a/tests/unit/computers/test_api_parity.py b/tests/unit/computers/test_api_parity.pynew file mode 100644index 0000000000..041e338e00--- /dev/null+++ b/tests/unit/computers/test_api_parity.py@@ -0,0 +1,46 @@+"""Every field of the computer records reaches the TypeScript client (AP-4).++The REST rows are ``model_dump`` of these models; ``lib/computersApi.ts``+declares the same shapes by hand. A field added on one side only is a value+the UI silently never sees (or reads as ``undefined``), so the two sides are+compared name for name.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest+from pydantic import BaseModel++from jarvis.computers.models import Computer, ComputerFacts, ComputerHealth, ComputerRoute++TS_FILE = Path(__file__).resolve().parents[3] / "jarvis/ui/web/frontend/src/lib/computersApi.ts"+++def _ts_fields(interface: str) -> set[str]:+ text = TS_FILE.read_text(encoding="utf-8")+ match = re.search(rf"export interface {interface} \{{(.*?)\n\}}", text, re.S)+ assert match, f"interface {interface} not found in computersApi.ts"+ body = re.sub(r"/\*.*?\*/|//[^\n]*", "", match.group(1), flags=re.S)+ return set(re.findall(r"^\s*([a-z_][a-z0-9_]*)\??:", body, re.M))+++ ("model", "interface"),+ [+ (Computer, "Computer"),+ (ComputerHealth, "ComputerHealth"),+ (ComputerFacts, "ComputerFacts"),+ (ComputerRoute, "ComputerRoute"),+ ],+)+def test_python_and_typescript_shapes_match(model: type[BaseModel], interface: str) -> None:+ python = set(model.model_fields)+ typescript = _ts_fields(interface)+ # Added by the route on top of the record (``_row``), not model fields.+ typescript -= {"busy", "provider_name"}++ assert python - typescript == set(), f"missing in TypeScript: {python - typescript}"+ assert typescript - python == set(), f"missing in Python: {typescript - python}"diff --git a/tests/unit/computers/test_placement_and_github.py b/tests/unit/computers/test_placement_and_github.pynew file mode 100644index 0000000000..dcfcb3cb16--- /dev/null+++ b/tests/unit/computers/test_placement_and_github.py@@ -0,0 +1,293 @@+""" "Automatic" placement over this PC and the computers, and GitHub sharing."""++from __future__ import annotations++import os+import random+import shutil+import stat+import subprocess+import sys+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.computers import github_access, identity, placement, remote_os, service+from jarvis.computers.models import Computer, ComputerHealth+from jarvis.computers.service import ComputerError, ComputerService+from jarvis.computers.store import ComputerStore+from jarvis.ui.web import computers_routes+from tests.fakes.fake_ssh_server import FakeSshServer++# -- placement ---------------------------------------------------------------------+++def _machine(+ cid: str, *, weight: int = 2, status: str = "online", enabled: bool = True+) -> Computer:+ return Computer(+ id=cid,+ name=cid,+ host="203.0.113.1",+ created_at=1.0,+ placement_weight=weight,+ enabled=enabled,+ health=ComputerHealth(status=status), # type: ignore[arg-type]+ )+++def test_only_switched_on_online_computers_with_a_share_are_candidates() -> None:+ computers = [+ _machine("c_ok"),+ _machine("c_more", weight=3),+ _machine("c_never", weight=0),+ _machine("c_off", enabled=False),+ _machine("c_down", status="offline"),+ ]++ pool = placement.candidates(+ placement.PlacementSettings(enabled=True, local_weight=1), computers+ )++ assert pool == [(None, 1), ("c_ok", 2), ("c_more", 4)]+++def test_pick_follows_the_shares() -> None:+ computers = [_machine("c_a", weight=3), _machine("c_b", weight=1)]+ settings = placement.PlacementSettings(enabled=True, local_weight=0)+ rng = random.Random(7) # noqa: S311 — a seeded test, not a secret++ picks = [placement.pick(settings, computers, rng=rng) for _ in range(2000)]++ share_a = picks.count("c_a") / len(picks)+ assert 0.75 < share_a < 0.85 # 4 : 1+ assert None not in picks+++def test_with_nothing_else_this_pc_takes_the_work() -> None:+ settings = placement.PlacementSettings(enabled=True, local_weight=0)++ assert placement.pick(settings, [_machine("c_x", status="offline")]) is None+ assert placement.pick(settings, []) is None+++def test_settings_round_trip_and_survive_garbage(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ path = tmp_path / "computers" / "placement.json"+ monkeypatch.setattr(placement, "_path", lambda: path)++ assert placement.load() == placement.PlacementSettings()+ placement.save(placement.PlacementSettings(enabled=True, local_weight=3))+ assert placement.load() == placement.PlacementSettings(enabled=True, local_weight=3)+ path.write_text('{"enabled": true, "local_weight": 9}', encoding="utf-8")+ assert placement.load() == placement.PlacementSettings(enabled=True, local_weight=2)+ path.write_text("not json", encoding="utf-8")+ assert placement.load() == placement.PlacementSettings()+++def test_a_share_outside_the_scale_is_refused(computer_service: ComputerService) -> None:+ computer_service._store.add(_machine("c_w")) # noqa: SLF001++ with pytest.raises(ComputerError):+ computer_service.update("c_w", placement_weight=5)+ assert computer_service.update("c_w", placement_weight=0).placement_weight == 0+++def client(+ computer_service: ComputerService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> TestClient:+ monkeypatch.setattr(computers_routes, "get_service", lambda: computer_service)+ monkeypatch.setattr(placement, "_path", lambda: tmp_path / "placement.json")+ app = FastAPI()+ app.include_router(computers_routes.router)+ return TestClient(app)+++def test_placement_routes(client: TestClient, computer_service: ComputerService) -> None:+ assert client.get("/api/computers/placement").json() == {"enabled": False, "local_weight": 2}+ assert client.put("/api/computers/placement", json={"enabled": True}).json() == {+ "enabled": True,+ "local_weight": 2,+ }+ assert client.put("/api/computers/placement", json={"local_weight": 0}).json() == {+ "enabled": True,+ "local_weight": 0,+ }+ assert client.put("/api/computers/placement", json={"local_weight": 7}).status_code == 422+ computer_service._store.add(_machine("c_only")) # noqa: SLF001++ assert client.post("/api/computers/placement/pick").json() == {"computer_id": "c_only"}+ assert (+ client.patch("/api/computers/c_only", json={"placement_weight": 0}).json()[+ "placement_weight"+ ]+ == 0+ )+ assert client.post("/api/computers/placement/pick").json() == {"computer_id": None}+++# -- GitHub sharing -----------------------------------------------------------------+++def computers(tmp_path: Path, secret_box, monkeypatch: pytest.MonkeyPatch) -> ComputerService: # noqa: ANN001+ path = tmp_path / "computers.json"+ monkeypatch.setattr("jarvis.computers.store.default_path", lambda: path)+ svc = ComputerService(ComputerStore(path))+ monkeypatch.setattr(service, "_SERVICE", svc)+ return svc+++async def ssh_server(tmp_path: Path): # noqa: ANN201+ home = tmp_path / "remote-home"+ home.mkdir()+ server = FakeSshServer(sftp_root=home)+ server.state.authorized.add(identity.public_key_line())+ await server.start()+ try:+ yield server+ finally:+ await server.stop()+++async def box(computers: ComputerService, ssh_server: FakeSshServer): # noqa: ANN201+ return await computers.add_server(name="Box", host="127.0.0.1", port=ssh_server.port)+++TOKEN = "gho_" + "x" * 36 # noqa: S105 — a fixture, not a credential+++def _token(monkeypatch: pytest.MonkeyPatch, value: str | None) -> None:+ from jarvis.agentic_ide import github_link++ monkeypatch.setattr(+ github_link,+ "credential",+ lambda: github_link.Credential(token=value, source="gh") if value else None,+ )+++async def test_sharing_writes_an_owner_only_env_file_and_the_helper(+ box, # noqa: ANN001+ ssh_server: FakeSshServer,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _token(monkeypatch, TOKEN)++ shared = await github_access.share(box.id)++ saved = ssh_server.sftp_root / ".config" / "jarvis" / "github.env"+ text = saved.read_text(encoding="utf-8")+ assert f"export GH_TOKEN={TOKEN}\n" in text and f"export GITHUB_TOKEN={TOKEN}\n" in text+ if sys.platform != "win32":+ assert stat.S_IMODE(saved.stat().st_mode) == 0o600+ assert shared.github_shared_at is not None+ # The token travelled only in the file, never on a command line or in a script.+ assert not any(TOKEN in command for command in ssh_server.state.commands)+ assert any(github_access.HELPER in command for command in ssh_server.state.commands)++ removed = await github_access.unshare(box.id)+ assert removed.github_shared_at is None+ assert any(remote_os.GITHUB_ENV_FILE in command for command in ssh_server.state.commands)+++async def test_sharing_without_a_github_login_says_how_to_connect(+ box, # noqa: ANN001+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _token(monkeypatch, None)++ with pytest.raises(ComputerError) as caught:+ await github_access.share(box.id)++ assert caught.value.kind == "github_missing"+++def test_every_launcher_sources_the_github_file_after_the_agent_file() -> None:+ lines = remote_os._source_agent_env().splitlines() # noqa: SLF001++ assert remote_os.AGENT_ENV_FILE in lines[0]+ assert remote_os.GITHUB_ENV_FILE in lines[1]+++def _real_bash() -> str | None:+ found = shutil.which("bash")+ if found is None or "system32" in found.lower(): # WSL's launcher, not a POSIX bash+ return None+ return found if shutil.which("git") else None++[email protected](_real_bash() is None, reason="needs bash and git")+def test_the_helper_hands_git_the_token_and_is_removed_cleanly(tmp_path: Path) -> None:+ bash = _real_bash()+ assert bash is not None+ home = tmp_path / "home"+ (home / ".config" / "jarvis").mkdir(parents=True)+ (home / ".config" / "jarvis" / "github.env").write_text(+ github_access.env_file_body(TOKEN), encoding="utf-8"+ )+ env = {+ **os.environ,+ "HOME": str(home),+ "GIT_CONFIG_NOSYSTEM": "1",+ "GIT_TERMINAL_PROMPT": "0",+ "GH_TOKEN": "",+ }+ env.pop("XDG_CONFIG_HOME", None)++ def bash_run(script: str, **extra: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run( # noqa: S603 — a fixed local bash in a temp HOME+ [bash, "-c", script],+ capture_output=True,+ text=True,+ env={**env, **extra},+ check=False,+ timeout=60,+ )++ assert bash_run(github_access.helper_script(True)).returncode == 0+ fill = bash_run(+ '. "$HOME/.config/jarvis/github.env"; '+ "printf 'protocol=https\\nhost=github.com\\n\\n' | git credential fill"+ )+ assert f"password={TOKEN}" in fill.stdout, fill.stderr+ assert "username=x-access-token" in fill.stdout++ assert bash_run(github_access.helper_script(False)).returncode == 0+ left = bash_run("git config --global --get-all credential.https://github.com.helper")+ assert left.stdout.strip() == ""+ assert not (home / ".config" / "jarvis" / "github.env").exists()+++def test_unsharing_keeps_a_helper_the_user_set_themselves(tmp_path: Path) -> None:+ bash = _real_bash()+ if bash is None:+ pytest.skip("needs bash and git")+ home = tmp_path / "home"+ home.mkdir()+ env = {**os.environ, "HOME": str(home), "GIT_CONFIG_NOSYSTEM": "1"}+ env.pop("XDG_CONFIG_HOME", None)+ key = "credential.https://github.com.helper"+ subprocess.run( # noqa: S603+ [bash, "-c", f"git config --global {key} store"], env=env, check=True, timeout=60+ )++ subprocess.run( # noqa: S603+ [bash, "-c", github_access.helper_script(False)], env=env, check=True, timeout=60+ )++ kept = subprocess.run( # noqa: S603+ [bash, "-c", f"git config --global --get {key}"],+ env=env,+ capture_output=True,+ text=True,+ check=False,+ timeout=60,+ )+ assert kept.stdout.strip() == "store"diff --git a/tests/unit/computers/test_routes_and_switch.py b/tests/unit/computers/test_routes_and_switch.pynew file mode 100644index 0000000000..6a623ec25d--- /dev/null+++ b/tests/unit/computers/test_routes_and_switch.py@@ -0,0 +1,341 @@+"""Several addresses per computer, the on/off switch and the check's trace id.++Runs against real in-process SSH servers: a closed port stands in for an+address that is down, a second server with its own host key for a stranger+answering on an address.+"""++from __future__ import annotations++import json+import socket++import pytest++from jarvis.computers import identity+from jarvis.computers.models import PRIMARY_ROUTE_ID, Computer+from jarvis.computers.service import ComputerError, ComputerService+from jarvis.computers.store import ComputerStore+from tests.fakes.fake_ssh_server import FakeSshServer+++async def ssh_server(): # noqa: ANN201+ server = FakeSshServer()+ await server.start()+ try:+ yield server+ finally:+ await server.stop()+++async def stranger(): # noqa: ANN201+ server = FakeSshServer()+ await server.start()+ try:+ yield server+ finally:+ await server.stop()+++def _closed_port() -> int:+ """A local port nothing listens on (bound, read, released)."""+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++async def _online(service: ComputerService, server: FakeSshServer) -> Computer:+ server.state.authorized.add(identity.public_key_line())+ computer = await service.add_server(name="box", host="127.0.0.1", port=server.port)+ assert computer.health.status == "online", computer.health.message+ return computer+++# -- the record ---------------------------------------------------------------+++def test_a_record_from_before_routes_gets_its_address_as_the_only_route(tmp_path) -> None: # noqa: ANN001+ path = tmp_path / "computers.json"+ legacy = {"id": "c_1", "name": "old", "host": "203.0.113.5", "port": 2222, "created_at": 1.0}+ path.write_text(json.dumps({"version": 1, "computers": [legacy]}), encoding="utf-8")++ (computer,) = ComputerStore(path).all()++ assert computer.enabled is True+ assert [(r.id, r.host, r.port) for r in computer.routes] == [+ (PRIMARY_ROUTE_ID, "203.0.113.5", 2222)+ ]+ assert computer.active_route_id == PRIMARY_ROUTE_ID+++def test_routes_survive_a_round_trip_through_the_store(tmp_path) -> None: # noqa: ANN001+ store = ComputerStore(tmp_path / "computers.json")+ computer = Computer(id="c_1", name="n", host="10.0.0.2", created_at=1.0)+ store.add(computer)+ store.update(+ "c_1",+ lambda row: row.model_copy(+ update={+ "routes": [+ *row.routes,+ row.routes[0].model_copy(update={"id": "r_x", "host": "box.ts.net"}),+ ]+ }+ ),+ )++ (again,) = ComputerStore(tmp_path / "computers.json").all()+ assert [r.host for r in again.routes] == ["10.0.0.2", "box.ts.net"]+++# -- switching off ------------------------------------------------------------+++async def test_a_switched_off_computer_is_not_connected_or_checked(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)++ off = computer_service.update(computer.id, enabled=False)+ assert off.enabled is False++ with pytest.raises(ComputerError) as caught:+ await computer_service.run(computer.id, "uptime")+ assert caught.value.kind == "disabled" and caught.value.status == 409+ with pytest.raises(ComputerError):+ await computer_service.connect(computer.id)+ # A check leaves the record as it was instead of reporting it offline.+ assert (await computer_service.check(computer.id)).health == off.health+ assert [c.id for c in await computer_service.check_all()] == [computer.id]++ on = computer_service.update(computer.id, enabled=True)+ assert on.enabled is True+ assert (await computer_service.run(computer.id, "uptime")).exit_status == 0+++async def test_check_all_skips_switched_off_computers(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ computer_service.update(computer.id, enabled=False)+ await ssh_server.stop() # would turn an ordinary check "offline"++ (after,) = await computer_service.check_all()++ assert after.health.status == "online"+++# -- routes -------------------------------------------------------------------+++def _set_port(service: ComputerService, computer_id: str, route_id: str, port: int) -> None:+ """Point one stored route at another port without the edit's identity reset."""++ def change(row: Computer) -> Computer:+ routes = [+ r.model_copy(update={"port": port}) if r.id == route_id else r for r in row.routes+ ]+ return row.model_copy(update={"routes": routes})++ service._store.update(computer_id, change) # noqa: SLF001 — simulate a network change+++async def test_an_unreachable_preferred_route_falls_through_to_the_next(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ both = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)+ preferred, fallback = both.routes+ _set_port(computer_service, computer.id, preferred.id, _closed_port())++ checked = await computer_service.check(computer.id)++ assert checked.health.status == "online", checked.health.message+ assert checked.active_route_id == fallback.id+ assert (checked.host, checked.port) == ("localhost", ssh_server.port)+ # An ordinary connection now skips the dead address straight away.+ assert (await computer_service.run(computer.id, "uptime")).exit_status == 0+++async def test_a_check_moves_back_to_the_preferred_route_once_it_answers(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ both = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)+ preferred, fallback = both.routes+ _set_port(computer_service, computer.id, preferred.id, _closed_port())+ assert (await computer_service.check(computer.id)).active_route_id == fallback.id++ _set_port(computer_service, computer.id, preferred.id, ssh_server.port)+ checked = await computer_service.check(computer.id)++ assert checked.active_route_id == preferred.id+ assert checked.host == "127.0.0.1"+++async def test_every_route_down_reports_the_preferred_address(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ both = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)+ dead = _closed_port()+ _set_port(computer_service, computer.id, both.routes[0].id, dead)+ _set_port(computer_service, computer.id, both.routes[1].id, _closed_port())++ checked = await computer_service.check(computer.id)++ assert checked.health.status == "offline"+ assert str(dead) in (checked.health.message or "")+++async def test_a_stranger_on_a_new_address_is_refused(+ computer_service: ComputerService, ssh_server: FakeSshServer, stranger: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)++ with pytest.raises(ComputerError) as caught:+ await computer_service.add_route(computer.id, host="127.0.0.1", port=stranger.port)++ assert caught.value.kind == "host_key_changed"+ assert len(computer_service.get(computer.id).routes) == 1+++async def test_a_stranger_behind_a_stored_route_is_never_trusted(+ computer_service: ComputerService, ssh_server: FakeSshServer, stranger: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ added = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)+ # The machine moves away from its preferred address and a stranger takes it.+ computer_service.order_routes(computer.id, [added.routes[1].id, added.routes[0].id])+ stranger.state.authorized.add(identity.public_key_line())+ second_id = added.routes[1].id++ def swap(row: Computer) -> Computer:+ routes = [+ r.model_copy(update={"port": stranger.port}) if r.id == second_id else r+ for r in row.routes+ ]+ return row.model_copy(update={"routes": routes})++ computer_service._store.update(computer.id, swap) # noqa: SLF001 — simulate the swap++ checked = await computer_service.check(computer.id)++ assert checked.health.status == "host_key_changed"+ assert checked.health.trace_id and checked.health.trace_id.startswith("cmp-")+++async def test_an_unreachable_new_address_is_not_added(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)++ with pytest.raises(ComputerError) as caught:+ await computer_service.add_route(computer.id, host="127.0.0.1", port=_closed_port())++ assert caught.value.kind == "unreachable"+++async def test_route_add_needs_a_pinned_identity(computer_service: ComputerService) -> None:+ computer = Computer(id="c_new", name="n", host="203.0.113.9", created_at=1.0)+ computer_service._store.add(computer) # noqa: SLF001 — a never-reached record++ with pytest.raises(ComputerError) as caught:+ await computer_service.add_route("c_new", host="203.0.113.10")++ assert caught.value.status == 409+++async def test_duplicate_and_last_routes_are_refused(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)++ with pytest.raises(ComputerError):+ await computer_service.add_route(computer.id, host="127.0.0.1", port=ssh_server.port)+ with pytest.raises(ComputerError) as caught:+ computer_service.remove_route(computer.id, computer.routes[0].id)+ assert caught.value.status == 409+++async def test_removing_the_active_route_falls_back_to_the_next(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ added = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)++ left = computer_service.remove_route(computer.id, added.routes[0].id)++ assert [r.host for r in left.routes] == ["localhost"]+ assert left.active_route_id == left.routes[0].id+ assert left.host == "localhost"+++async def test_order_must_name_every_route_once(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)+ added = await computer_service.add_route(computer.id, host="localhost", port=ssh_server.port)+ ids = [r.id for r in added.routes]++ with pytest.raises(ComputerError):+ computer_service.order_routes(computer.id, ids[:1])+ reordered = computer_service.order_routes(computer.id, list(reversed(ids)))++ assert [r.id for r in reordered.routes] == list(reversed(ids))+++async def test_editing_the_address_moves_the_active_route(+ computer_service: ComputerService, ssh_server: FakeSshServer+) -> None:+ computer = await _online(computer_service, ssh_server)++ edited = computer_service.update(computer.id, host="localhost")++ assert edited.routes[0].host == "localhost"+ assert edited.host_key is None # a new address is a new machine until proven+++async def test_a_failed_check_carries_a_trace_id(+ computer_service: ComputerService, ssh_server: FakeSshServer, caplog: pytest.LogCaptureFixture+) -> None:+ computer = await _online(computer_service, ssh_server)+ await ssh_server.stop()++ checked = await computer_service.check(computer.id)++ assert checked.health.status == "offline"+ assert checked.health.trace_id+ assert checked.health.trace_id in caplog.text+++async def test_keep_working_never_moves_panes_to_a_switched_off_computer(+ tmp_path, # noqa: ANN001+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from types import SimpleNamespace++ from jarvis.agentic_ide import offload_on_quit+ from jarvis.computers import store as store_module++ path = tmp_path / "computers.json"+ monkeypatch.setattr(store_module, "default_path", lambda: path)+ ComputerStore(path).add(+ Computer(id="c_off", name="off", host="203.0.113.8", created_at=1.0, enabled=False)+ )+ monkeypatch.setattr(offload_on_quit, "target", lambda: "c_off")+ placed: list[str] = []++ async def place_workspace(workspace_id: str, *, computer_id: str) -> None:+ placed.append(workspace_id)++ running = SimpleNamespace(pty_id="p1", computer_id="")+ registry = SimpleNamespace(+ sessions=[SimpleNamespace(id="ws1", name="app", terminals=[running])],+ place_workspace=place_workspace,+ )++ assert await offload_on_quit.offload_before_quit(registry) == []+ assert placed == []diff --git a/tests/unit/computers/test_server_pairing.py b/tests/unit/computers/test_server_pairing.pynew file mode 100644index 0000000000..74a792d4ca--- /dev/null+++ b/tests/unit/computers/test_server_pairing.py@@ -0,0 +1,264 @@+"""Real two-sided pairing over ASGI HTTP, including the global auth boundary."""++from __future__ import annotations++import asyncio+import json+from concurrent.futures import ThreadPoolExecutor+from urllib.parse import urlsplit++import httpx+import pytest+from fastapi import FastAPI++from jarvis.computers import pairing+from jarvis.core.http_pool import HttpClientPool+from jarvis.ui.web import server_pairing_routes+from jarvis.ui.web.missions_auth import reset_tokens+from jarvis.ui.web.surface_security import SurfaceSecurity+++async def paired_environment(tmp_path, monkeypatch, secret_box):+ for name in ("get_secret", "set_secret", "delete_secret"):+ monkeypatch.setattr(pairing, name, getattr(secret_box, name.split("_")[0]))+ remote = pairing.ServerPairing(tmp_path / "remote.json")+ monkeypatch.setattr(server_pairing_routes, "get_pairing", lambda: remote)+ app = FastAPI()+ app.include_router(server_pairing_routes.router)++ @app.get("/api/private-proof")+ def private_ui():+ return {"authenticated": True}++ secured = SurfaceSecurity(+ app,+ trusted_hosts=["remote.test"],+ control_key_validator=lambda value: value == "owner-only-test-credential",+ )+ pool = HttpClientPool(transport=httpx.ASGITransport(app=secured))+ local = pairing.ServerPairing(tmp_path / "local.json", pool)+ yield remote, local, pool.client(), secret_box+ await local.pool.aclose()+ reset_tokens()+++async def issue(client):+ response = await client.post(+ "https://remote.test/api/computers/pairing/code",+ headers={"Authorization": "Bearer owner-only-test-credential"},+ )+ assert response.status_code == 200+ assert response.headers["cache-control"] == "no-store"+ return response.json()["code"]+++async def test_pair_save_reload_check_open_and_revoke(paired_environment, monkeypatch):+ remote, local, client, box = paired_environment+ code = await issue(client)+ server = await local.add("remote.test", code)+ credential = box.get(pairing._slot(server.id))+ assert server.url == "https://remote.test" and server.online+ assert credential and credential != code+ assert code not in local.path.read_text() and credential not in local.path.read_text()+ assert code not in remote.path.read_text() and credential not in remote.path.read_text()+ # Both durable sides survive a new service instance. Codes and tickets do not.+ restarted_remote = pairing.ServerPairing(remote.path)+ monkeypatch.setattr(server_pairing_routes, "get_pairing", lambda: restarted_remote)+ reloaded = pairing.ServerPairing(local.path, local.pool)+ assert (await reloaded.check(server.id)).online+ assert (+ await client.get(+ "https://remote.test/api/private-proof",+ headers={+ "Authorization": "Bearer " + credential,+ },+ )+ ).status_code == 401+ link = urlsplit(await reloaded.launch(server.id))+ assert link.netloc == "remote.test" and not link.query+ page = await client.get("https://remote.test" + link.path)+ assert (+ page.status_code == 200 and "script-src 'sha256-" in page.headers["content-security-policy"]+ )+ response = await client.post("https://remote.test" + link.path, json={"ticket": link.fragment})+ assert response.status_code == 200+ cookie = response.headers["set-cookie"].lower()+ assert "httponly" in cookie and "samesite=strict" in cookie and "secure" in cookie+ assert (await client.get("https://remote.test/api/private-proof")).status_code == 200+ assert (+ await client.post("https://remote.test" + link.path, json={"ticket": link.fragment})+ ).status_code == 401+ await reloaded.remove(server.id)+ assert reloaded.servers() == []+ assert box.get(pairing._slot(server.id)) is None+ assert restarted_remote.clients() == []+ assert (+ await client.get(+ "https://remote.test/api/computers/pairing/status",+ headers={+ "Authorization": "Bearer " + credential,+ },+ )+ ).status_code == 401+ await local.pool.aclose()+++async def test_boundary_requires_owner_for_issuing_codes_and_tls_for_redemption(paired_environment):+ _, local, client, _ = paired_environment+ for path, method in [("code", "POST"), ("clients", "GET"), ("servers", "GET")]:+ assert (+ await client.request(method, "https://remote.test/api/computers/pairing/" + path)+ ).status_code == 401+ code = await issue(client)+ response = await client.post(+ "http://remote.test/api/computers/pairing/redeem", json={"code": code}+ )+ assert response.status_code == 403+ response = await client.post(+ "https://remote.test/api/computers/pairing/redeem",+ json={"code": code},+ headers={"Origin": "https://untrusted.test"},+ )+ assert response.status_code == 403+ assert (await local.add("https://remote.test", code)).online+ await local.pool.aclose()+++def test_one_code_can_only_be_consumed_once_and_expires(tmp_path, monkeypatch):+ service = pairing.ServerPairing(tmp_path / "state.json")+ code = service.issue_code()["code"]++ def redeem():+ try:+ return service.redeem(code, "test").credential+ except pairing.PairingError:+ return None++ with ThreadPoolExecutor(max_workers=4) as executor:+ assert sum(value is not None for value in executor.map(lambda _: redeem(), range(4))) == 1+ invitation = service.issue_code()+ monkeypatch.setattr(pairing.time, "time", lambda: invitation["expires_at"] + 1)+ with pytest.raises(pairing.PairingError, match="expired"):+ service.redeem(invitation["code"], "test")+++async def test_bad_code_redirect_and_protocol_do_not_save(paired_environment):+ _, local, client, box = paired_environment+ with pytest.raises(pairing.PairingError):+ await local.add("remote.test", "wrong-code")+ assert not local.servers() and not box.values+ await local.pool.aclose()+ requests = []++ def redirect(request):+ requests.append(request)+ return httpx.Response(307, headers={"Location": "https://other.test/collect"})++ local.pool = HttpClientPool(transport=httpx.MockTransport(redirect))+ with pytest.raises(pairing.PairingError):+ await local.add("https://remote.test", "private-example-code")+ assert len(requests) == 1 and requests[0].url.host == "remote.test"+ assert not local.servers()+ await local.pool.aclose()+ local.pool = HttpClientPool(+ transport=httpx.MockTransport(+ lambda request: httpx.Response(+ 200,+ json={+ "name": "other app",+ "platform": "Linux",+ "credential": "a" * 43,+ },+ )+ )+ )+ with pytest.raises(pairing.PairingError, match="incompatible"):+ await local.add("remote.test", "another-code")+ assert not local.servers()+ await local.pool.aclose()+++async def test_offline_check_and_failed_credential_save_are_honest(paired_environment, monkeypatch):+ _, local, client, box = paired_environment+ monkeypatch.setattr(pairing, "set_secret", lambda key, value: False)+ with pytest.raises(pairing.PairingError, match="could not be saved"):+ await local.add("remote.test", await issue(client))+ assert not local.servers()+ monkeypatch.setattr(pairing, "set_secret", box.set)+ server = await local.add("remote.test", await issue(client))+ await local.pool.aclose()+ local.pool = HttpClientPool(transport=httpx.MockTransport(lambda request: httpx.Response(503)))+ assert not (await local.check(server.id)).online+ with pytest.raises(pairing.PairingError):+ await local.remove(server.id)+ assert len(local.servers()) == 1 and box.get(pairing._slot(server.id))+ await local.pool.aclose()+++def test_revoked_grant_invalidates_pending_tickets(tmp_path, monkeypatch):+ service = pairing.ServerPairing(tmp_path / "state.json")+ grant = service.redeem(service.issue_code()["code"], "test")+ ticket = service.issue_ticket(grant.credential)+ service.revoke(service.clients()[0]["id"])+ with pytest.raises(pairing.PairingError):+ service.consume_ticket(ticket)+ with pytest.raises(pairing.PairingError):+ service.issue_ticket(grant.credential)+ state = json.loads(service.path.read_text())+ assert state["grants"] == []+++async def test_disconnect_finishes_before_repairing_the_same_origin(paired_environment):+ remote, local, client, box = paired_environment+ original = await local.add("remote.test", await issue(client))+ next_code = await issue(client)+ arrived, release = asyncio.Event(), asyncio.Event()+ original_transport = local.pool._transport++ class GatedTransport(httpx.AsyncBaseTransport):+ async def handle_async_request(self, request):+ if request.url.path.endswith("/disconnect"):+ arrived.set()+ await release.wait()+ return await original_transport.handle_async_request(request)++ await local.pool.aclose()+ local.pool = HttpClientPool(transport=GatedTransport())+ removal = asyncio.create_task(local.remove(original.id))+ await asyncio.wait_for(arrived.wait(), timeout=2)+ addition = asyncio.create_task(local.add("remote.test", next_code))+ await asyncio.sleep(0)+ assert not addition.done()+ release.set()+ await removal+ replacement = await addition+ assert local.servers() == [replacement]+ assert box.get(pairing._slot(replacement.id))+ assert len(remote.clients()) == 1+++ "value",+ [+ "http://remote.test",+ "https://a:[email protected]",+ "https://remote.test/?key=private",+ "file:///tmp/test",+ "https://remote.test/path",+ ],+)+def test_rejects_unsafe_server_origins(value):+ with pytest.raises(pairing.PairingError):+ pairing.normalize_server(value)+++def test_openapi_pairs_request_and_response_models():+ app = FastAPI()+ app.include_router(server_pairing_routes.router)+ schema = app.openapi()+ operations = [+ operation["operationId"] for path in schema["paths"].values() for operation in path.values()+ ]+ assert len(set(operations)) == len(operations)+ assert "computer_servers_add" in operations and "computer_pairing_redeem" in operationsdiff --git a/tests/unit/computers/test_ssh_config_and_tailscale.py b/tests/unit/computers/test_ssh_config_and_tailscale.pynew file mode 100644index 0000000000..29c1fc02af--- /dev/null+++ b/tests/unit/computers/test_ssh_config_and_tailscale.py@@ -0,0 +1,401 @@+"""This PC's ~/.ssh/config and known_hosts, and its Tailscale network."""++from __future__ import annotations++import json+from pathlib import Path++import asyncssh+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.computers import identity, ssh, ssh_config, tailscale+from jarvis.computers.models import Computer, ComputerFacts, ComputerRoute+from jarvis.computers.service import ComputerService+from jarvis.ui.web import computers_routes+from tests.fakes.fake_ssh_server import FakeSshServer+++def _home(tmp_path: Path, config: str, known_hosts: str = "") -> Path:+ ssh_dir = tmp_path / ".ssh"+ ssh_dir.mkdir(parents=True, exist_ok=True)+ (ssh_dir / "config").write_text(config, encoding="utf-8")+ if known_hosts:+ (ssh_dir / "known_hosts").write_text(known_hosts, encoding="utf-8")+ return tmp_path+++# -- ~/.ssh/config ---------------------------------------------------------------+++def test_first_value_wins_and_wildcard_blocks_fill_the_gaps(tmp_path: Path) -> None:+ home = _home(+ tmp_path,+ """+# a comment+Host vps+ HostName 203.0.113.7+ Port 2222++Host vps other+ User deploy+ Port 9999++Host *+ User root+ ServerAliveInterval 30+""",+ )++ hosts = {h.alias: h for h in ssh_config.discover(home)}++ assert set(hosts) == {"vps", "other"}+ assert (hosts["vps"].host, hosts["vps"].port, hosts["vps"].username) == (+ "203.0.113.7",+ 2222,+ "deploy",+ )+ assert (hosts["other"].host, hosts["other"].port, hosts["other"].username) == (+ "other",+ 9999,+ "deploy",+ )+++def test_patterns_negations_and_match_blocks_are_never_listed(tmp_path: Path) -> None:+ home = _home(+ tmp_path,+ """+Host *.internal !secret.internal web?+ User ops+Match host foo+ User nobody+Host real+ HostName real.example.com+""",+ )++ aliases = [h.alias for h in ssh_config.discover(home)]++ assert aliases == ["real"]+++def test_include_globs_relative_to_dot_ssh_are_followed(tmp_path: Path) -> None:+ home = _home(tmp_path, "Include conf.d/*.conf\nHost main\n HostName 10.0.0.1\n")+ conf_d = home / ".ssh" / "conf.d"+ conf_d.mkdir()+ (conf_d / "a.conf").write_text("Host alpha\n HostName 10.0.0.2\n", encoding="utf-8")+ (conf_d / "b.conf").write_text("Host beta\n HostName 10.0.0.3\n", encoding="utf-8")+ (conf_d / "skip.txt").write_text("Host never\n", encoding="utf-8")++ assert sorted(h.alias for h in ssh_config.discover(home)) == ["alpha", "beta", "main"]+++def test_an_include_loop_ends(tmp_path: Path) -> None:+ home = _home(tmp_path, "Include ~/.ssh/config\nHost loop\n HostName 10.0.0.9\n")++ assert [h.alias for h in ssh_config.discover(home)] == ["loop"]+++def test_identity_files_accumulate_and_only_existing_ones_count(tmp_path: Path) -> None:+ home = _home(+ tmp_path,+ """+Host box+ HostName %h.example.com+ IdentityFile ~/.ssh/box_key+ IdentityFile ~/.ssh/missing_key+Host *+ IdentityFile ~/.ssh/fallback_key+""",+ )+ (home / ".ssh" / "box_key").write_text("x", encoding="utf-8")+ (home / ".ssh" / "fallback_key").write_text("x", encoding="utf-8")++ (box,) = ssh_config.discover(home)++ assert box.host == "box.example.com"+ assert [Path(p).name for p in box.identity_files] == ["box_key", "fallback_key"]+++def test_a_jump_host_is_marked(tmp_path: Path) -> None:+ home = _home(tmp_path, "Host inner\n ProxyJump bastion\nHost bastion\n HostName 1.2.3.4\n")++ hosts = {h.alias: h for h in ssh_config.discover(home)}++ assert hosts["inner"].needs_proxy is True+ assert hosts["bastion"].needs_proxy is False+++def test_key_equals_value_and_quoted_values(tmp_path: Path) -> None:+ home = _home(tmp_path, 'Host=eq\n HostName=10.1.1.1\n User "my user"\n')++ (host,) = ssh_config.discover(home)++ assert (host.host, host.username) == ("10.1.1.1", "my user")+++def test_no_config_and_no_known_hosts_is_simply_nothing(tmp_path: Path) -> None:+ assert ssh_config.discover(tmp_path) == []+++def test_a_bad_port_falls_back_to_22(tmp_path: Path) -> None:+ home = _home(tmp_path, "Host p\n Port seventy\nHost q\n Port 70000\n")++ assert {h.alias: h.port for h in ssh_config.discover(home)} == {"p": 22, "q": 22}+++# -- known_hosts -----------------------------------------------------------------+++def test_known_hosts_formats() -> None:+ text = """+# comment+203.0.113.1 ssh-ed25519 AAAA+[203.0.113.2]:2200,[alias.example]:2200 ssh-ed25519 AAAA+|1|hashed=|salt= ssh-ed25519 AAAA+@cert-authority *.example.com ssh-ed25519 AAAA+host-a,host-b ecdsa-sha2-nistp256 AAAA+2001:db8::1 ssh-ed25519 AAAA+*.wild ssh-ed25519 AAAA+"""+ assert ssh_config.parse_known_hosts(text) == [+ ("203.0.113.1", 22),+ ("203.0.113.2", 2200),+ ("alias.example", 2200),+ ("host-a", 22),+ ("host-b", 22),+ ("2001:db8::1", 22),+ ]+++def test_known_hosts_skips_forges_localhost_and_config_hosts(tmp_path: Path) -> None:+ home = _home(+ tmp_path,+ "Host vps\n HostName 203.0.113.7\n",+ "github.com ssh-ed25519 A\nlocalhost ssh-ed25519 A\n203.0.113.7 ssh-ed25519 A\n"+ "198.51.100.4 ssh-ed25519 A\n",+ )++ hosts = ssh_config.discover(home)++ assert [(h.alias, h.source) for h in hosts] == [+ ("vps", "ssh_config"),+ ("198.51.100.4", "known_hosts"),+ ]+ assert hosts[1].username is None+++# -- the auto login offers the config's IdentityFile ------------------------------+++async def test_auto_login_uses_the_identity_file_the_config_names(+ computer_service: ComputerService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ key = asyncssh.generate_private_key("ssh-ed25519")+ key_path = tmp_path / ".ssh" / "hetzner"+ home = _home(tmp_path, f"Host hz\n HostName 127.0.0.1\n IdentityFile {key_path}\n")+ key.write_private_key(str(key_path))+ monkeypatch.setattr(ssh_config, "home_dir", lambda: home)+ monkeypatch.setattr(ssh, "this_pc_keys", lambda: [])+ monkeypatch.setattr(ssh, "THIS_PC_AGENT", None)+ server = FakeSshServer()+ await server.start()+ try:+ server.state.authorized.add(key.export_public_key("openssh").decode().strip())++ tested = await computer_service.test_connection(+ host="127.0.0.1", port=server.port, auth="auto", ssh_alias="hz"+ )+ assert tested["ok"] is True, tested+ computer = await computer_service.add_server(+ name="hz", host="127.0.0.1", port=server.port, auth="auto", ssh_alias="hz"+ )+ finally:+ await server.stop()++ assert computer.auth == "key"+ assert any(identity.public_key_line().split()[1] in k for k in server.state.authorized)+++async def test_without_the_alias_the_same_server_refuses(+ computer_service: ComputerService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ key = asyncssh.generate_private_key("ssh-ed25519")+ monkeypatch.setattr(ssh, "this_pc_keys", lambda: [])+ monkeypatch.setattr(ssh, "THIS_PC_AGENT", None)+ server = FakeSshServer()+ await server.start()+ try:+ server.state.authorized.add(key.export_public_key("openssh").decode().strip())+ tested = await computer_service.test_connection(+ host="127.0.0.1", port=server.port, auth="auto"+ )+ finally:+ await server.stop()++ assert tested["ok"] is False+++def test_an_encrypted_or_broken_key_file_is_skipped(tmp_path: Path) -> None:+ locked = tmp_path / "locked"+ asyncssh.generate_private_key("ssh-ed25519").write_private_key(+ str(locked),+ passphrase="secret", # noqa: S106 — a throwaway test key+ )+ broken = tmp_path / "broken"+ broken.write_text("not a key", encoding="utf-8")+ good = tmp_path / "good"+ asyncssh.generate_private_key("ssh-ed25519").write_private_key(str(good))++ keys = ssh.key_files((str(locked), str(broken), str(good), str(tmp_path / "gone")))++ assert len(keys) == 1+++# -- Tailscale ---------------------------------------------------------------------++STATUS = {+ "Self": {"HostName": "this-pc"},+ "Peer": {+ "k1": {+ "HostName": "vps-01",+ "DNSName": "vps-01.tail1234.ts.net.",+ "TailscaleIPs": ["100.64.0.5", "fd7a::5"],+ "Online": True,+ "OS": "linux",+ },+ "k2": {+ "HostName": "laptop",+ "DNSName": "",+ "TailscaleIPs": ["100.64.0.9"],+ "Online": False,+ "OS": "windows",+ },+ "k3": {"HostName": "noaddr", "DNSName": "", "TailscaleIPs": []},+ },+}+++def test_status_json_is_read_into_peers() -> None:+ peers = tailscale.parse_status(json.dumps(STATUS))++ assert [(p.host_name, p.address, p.online) for p in peers] == [+ ("vps-01", "vps-01.tail1234.ts.net", True),+ ("laptop", "100.64.0.9", False),+ ]+ assert tailscale.parse_status("not json") == []+ assert tailscale.parse_status("[]") == []+++def _computer(cid: str, host: str, *, hostname: str | None = None, port: int = 22) -> Computer:+ return Computer(+ id=cid,+ name=cid,+ host=host,+ port=port,+ created_at=1.0,+ facts=ComputerFacts(hostname=hostname) if hostname else None,+ )+++def test_suggestions_match_by_reported_hostname_or_known_address() -> None:+ peers = tailscale.parse_status(json.dumps(STATUS))+ by_name = _computer("c_a", "192.168.1.20", hostname="VPS-01.fritz.box", port=2222)+ by_ip = _computer("c_b", "100.64.0.9")+ stranger = _computer("c_c", "10.0.0.1", hostname="other")+ already = _computer("c_d", "192.168.1.30", hostname="vps-01").model_copy(+ update={+ "routes": [+ ComputerRoute(id="r_main", host="192.168.1.30"),+ ComputerRoute(id="r_ts", host="vps-01.tail1234.ts.net"),+ ]+ }+ )+ vm = _computer("c_e", "100.64.0.5").model_copy(update={"kind": "local_vm"})++ found = tailscale.suggestions([by_name, by_ip, stranger, already, vm], peers)++ assert found == {+ "c_a": [+ {"host": "vps-01.tail1234.ts.net", "port": 2222, "label": "Tailscale", "online": True}+ ]+ }+++async def test_no_tailscale_cli_means_no_peers(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(tailscale, "binary", lambda: None)++ assert await tailscale.peers() == []+++# -- REST ------------------------------------------------------------------------------+++def client(computer_service: ComputerService, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ monkeypatch.setattr(computers_routes, "get_service", lambda: computer_service)+ app = FastAPI()+ app.include_router(computers_routes.router)+ return TestClient(app)+++def test_ssh_hosts_route_is_not_swallowed_by_the_id_route(+ client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ home = _home(tmp_path, "Host vps\n HostName 203.0.113.7\n User deploy\n")+ monkeypatch.setattr(ssh_config, "home_dir", lambda: home)++ response = client.get("/api/computers/ssh-hosts")++ assert response.status_code == 200+ (host,) = response.json()["hosts"]+ assert host["alias"] == "vps" and host["username"] == "deploy" and host["added_as"] is None+++def test_tailscale_route_without_tailscale(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(tailscale, "binary", lambda: None)++ response = client.get("/api/computers/tailscale")++ assert response.json() == {"available": False, "peers": [], "suggestions": {}}+++def test_patch_switches_a_computer_off_and_the_row_carries_routes(+ client: TestClient, computer_service: ComputerService+) -> None:+ computer_service._store.add(_computer("c_x", "203.0.113.3")) # noqa: SLF001++ off = client.patch("/api/computers/c_x", json={"enabled": False}).json()++ assert off["enabled"] is False+ assert off["routes"] == [+ {+ "id": "r_main",+ "host": "203.0.113.3",+ "port": 22,+ "label": None,+ "source": "manual",+ "last_ok_at": None,+ }+ ]+ assert off["active_route_id"] == "r_main"+ assert off["health"]["trace_id"] is None+++def test_route_endpoints_refuse_unknown_and_last_routes(+ client: TestClient, computer_service: ComputerService+) -> None:+ computer_service._store.add(_computer("c_y", "203.0.113.4")) # noqa: SLF001++ assert client.delete("/api/computers/c_y/routes/r_main").status_code == 409+ assert client.delete("/api/computers/c_y/routes/r_nope").status_code == 404+ assert (+ client.put("/api/computers/c_y/routes/order", json={"route_ids": ["r_x"]}).status_code+ == 400+ )+ assert client.post("/api/computers/c_y/routes", json={"host": "10.0.0.5"}).status_code == 409+ assert client.post("/api/computers/c_nope/routes", json={"host": "10.0.0.5"}).status_code == 404diff --git a/tests/unit/computers/test_windows_remote.py b/tests/unit/computers/test_windows_remote.pyindex b98e850f4b..5719797286 100644--- a/tests/unit/computers/test_windows_remote.py+++ b/tests/unit/computers/test_windows_remote.py@@ -175,8 +175,10 @@ def test_launcher_keeps_every_argument_intact() -> None:script = remote_os.launcher_script(host, f"{HOME}/jarvis-agents/scout", argv, {"CI": "1"})lines = script.splitlines()agent_env = '"$HOME/.config/jarvis/agent.env"'+ github_env = '"$HOME/.config/jarvis/github.env"'assert lines[0] == f"[ -f {agent_env} ] && . {agent_env}"- assert lines[1] == f"cd -- {HOME}/jarvis-agents/scout || exit 97"+ assert lines[1] == f"[ -f {github_env} ] && . {github_env}"+ assert lines[2] == f"cd -- {HOME}/jarvis-agents/scout || exit 97"assert "export CI=1" in linesassert "MSYS_NO_PATHCONV=1" in scriptassert "PATH=" not in script, "Git Bash brings the Windows PATH itself"diff --git a/tests/unit/hardware/test_accelerator_probe.py b/tests/unit/hardware/test_accelerator_probe.pyindex affebc0d83..dec1cab3ee 100644--- a/tests/unit/hardware/test_accelerator_probe.py+++ b/tests/unit/hardware/test_accelerator_probe.py@@ -186,7 +186,7 @@ def test_a_metal_budget_beats_the_ram_guess_on_a_mac(monkeypatch: pytest.MonkeyPmonkeypatch.setattr(detection.sys, "platform", "darwin")monkeypatch.setattr(detection.platform, "machine", lambda: "arm64")monkeypatch.setattr(detection, "_detect_ram", lambda: (32768, 16384))- assert detection.usable_accelerator_gb() == (21.3, "ollama-runtime")+ assert detection.usable_accelerator_gb() == (21.3, "apple-unified")def test_a_box_with_nothing_readable_says_so_and_does_not_guess(diff --git a/tests/unit/marketplace/test_catalog_load.py b/tests/unit/marketplace/test_catalog_load.pyindex 4c5caa8785..d0086a87ca 100644--- a/tests/unit/marketplace/test_catalog_load.py+++ b/tests/unit/marketplace/test_catalog_load.py@@ -35,6 +35,7 @@ def test_every_plugin_has_a_resolvable_auth_block() -> None:"hosted_mcp_allowlist","local","instance_browser",+ "hosted_mcp_open",}for plugin in catalog.plugins:assert plugin.id, "plugin without id"diff --git a/tests/unit/marketplace/test_custom_api_setup.py b/tests/unit/marketplace/test_custom_api_setup.pynew file mode 100644index 0000000000..ea60830d43--- /dev/null+++ b/tests/unit/marketplace/test_custom_api_setup.py@@ -0,0 +1,441 @@+"""Name/key provisioning and inherited native actions across service descriptions."""++from __future__ import annotations++import json+import logging+from uuid import uuid4++import httpx+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.core.protocols import ExecutionContext+from jarvis.marketplace.catalog import PluginCatalog+from jarvis.marketplace.custom_api import ApiConnectionInfo, ApiDefinition, CustomApiStore+from jarvis.marketplace.custom_api_connect import verify_api_key+from jarvis.marketplace.custom_api_discovery import ApiDiscovery, ApiDiscoveryError+from jarvis.marketplace.custom_api_openapi import api_auth, api_base_url, compile_openapi+from jarvis.marketplace.custom_api_runtime import CustomApiRuntime+from jarvis.marketplace.plugin_registry import PluginToolRegistry+from jarvis.marketplace.token_store import InMemoryBackend, TokenStore+from jarvis.ui.web.custom_api_routes import router++BASE = "https://93.184.216.34"+KEY = "fixture-only-service-key"+++def test_import_counts_incompatible_auth_and_path_server_as_omitted():+ spec = document()+ spec["components"]["securitySchemes"]["second"] = {+ "type": "apiKey",+ "in": "header",+ "name": "Second-Key",+ }+ spec["paths"]["/v1/user"]["get"]["security"] = [{"key": [], "second": []}]+ spec["paths"]["/transcribe"]["servers"] = [{"url": "https://another.example"}]+ actions, _, omitted = compile_openapi(spec, api_auth(spec), BASE)+ assert omitted == 2+ assert {a.path for a in actions} == {"/speak/{voice}", "/voices/{voice}"}+++def test_optional_body_and_hyphenated_path_parameter():+ from jsonschema import Draft202012Validator++ spec = document()+ operation = spec["paths"].pop("/speak/{voice}")+ operation["post"]["parameters"][0]["name"] = "voice-id"+ spec["paths"]["/speak/{voice-id}"] = operation+ actions, _, _ = compile_openapi(spec, api_auth(spec), BASE)+ action = next(a for a in actions if a.path == "/speak/{voice-id}")+ assert Draft202012Validator(action.input_schema()).is_valid({"path": {"voice-id": "voice"}})+++async def test_search_cannot_choose_a_service_named_subdomain_on_unrelated_host():+ async def search(name):+ return [{"url": "https://sample.attacker.example/openapi.json"}]++ discovery = ApiDiscovery(directory={}, search=search)+ discovery._brands = []+ try:+ with pytest.raises(ApiDiscoveryError, match="service_not_found"):+ await discovery.resolve("sample")+ finally:+ await discovery.close()+++def document():+ return {+ "openapi": "3.1.0",+ "info": {"title": "Sample Cloud", "version": "1"},+ "servers": [{"url": BASE}],+ "components": {+ "securitySchemes": {"key": {"type": "apiKey", "in": "header", "name": "X-API-Key"}},+ "schemas": {+ "Message": {+ "type": "object",+ "properties": {"text": {"type": "string"}},+ "required": ["text"],+ }+ },+ },+ "paths": {+ "/v1/user": {+ "get": {"operationId": "get_user", "summary": "Read account", "tags": ["Account"]}+ },+ "/speak/{voice}": {+ "post": {+ "operationId": "speak",+ "summary": "Generate speech",+ "tags": ["Speech"],+ "parameters": [+ {+ "in": "path",+ "name": "voice",+ "required": True,+ "schema": {"type": "string"},+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {"schema": {"$ref": "#/components/schemas/Message"}}+ }+ },+ }+ },+ "/transcribe": {+ "post": {+ "operationId": "transcribe",+ "summary": "Transcribe an audio file",+ "tags": ["Speech"],+ "requestBody": {+ "content": {+ "multipart/form-data": {+ "schema": {+ "type": "object",+ "properties": {+ "file": {"type": "string", "format": "binary"},+ "language": {"type": "string"},+ },+ "required": ["file"],+ }+ }+ }+ },+ }+ },+ "/voices/{voice}": {+ "delete": {+ "operationId": "delete_voice",+ "summary": "Delete voice",+ "tags": ["Voices"],+ "parameters": [+ {+ "in": "path",+ "name": "voice",+ "required": True,+ "schema": {"type": "string"},+ }+ ],+ }+ },+ },+ }+++def definition(count: int = 4):+ source = document()+ for i in range(count - 4):+ source["paths"][f"/objects/{i}"] = {"get": {"summary": f"Read object {i}"}}+ auth = api_auth(source)+ actions, categories, omitted = compile_openapi(source, auth, BASE)+ assert omitted == 0+ return ApiDefinition(+ name="Sample Cloud",+ base_url=BASE,+ auth=auth,+ actions=actions,+ connection=ApiConnectionInfo(+ service_id="sample-cloud",+ website=BASE,+ spec_url=BASE + "/openapi.json",+ categories=categories,+ ),+ )+++def store(tmp_path):+ return CustomApiStore(tmp_path / "services", TokenStore(InMemoryBackend()))+++def ctx():+ return ExecutionContext(+ trace_id=uuid4(), user_utterance="Use my service", config={}, memory_read=None+ )+++def test_openapi_compilation_resolves_refs_auth_paths_and_uploads():+ spec = definition()+ speak = next(a for a in spec.actions if a.path == "/speak/{voice}")+ assert speak.input_schema()["properties"]["body"]["required"] == ["text"]+ assert speak.parameters[0].location == "path"+ upload = next(a for a in spec.actions if a.path == "/transcribe")+ assert upload.body_encoding == "multipart" and upload.file_fields == ["file"]+ assert next(a for a in spec.actions if a.method == "DELETE").risk_tier == "ask"+ assert api_base_url(document(), BASE + "/openapi.json") == BASE+++async def test_hundreds_of_actions_are_inherited_without_hundreds_of_prompt_tools(store):+ spec = definition(125)+ store.save(spec, KEY)+ calls = []++ def respond(request):+ calls.append(str(request.url))+ assert request.headers["X-API-Key"] == KEY+ return httpx.Response(200, json={"ok": True})++ runtime = CustomApiRuntime(store, transport=httpx.MockTransport(respond))+ await runtime.refresh()+ assert len(runtime.tools) == 2+ search = runtime.tools[f"api_{spec.id}_actions"]+ call = runtime.tools[f"api_{spec.id}_call"]+ assert search.yields_instructions_only and not search.is_action_tool+ first = await search.execute({}, ctx())+ assert first.output["total"] == 125 and first.output["next_offset"] == 15+ assert calls == []+ action = next(a for a in spec.actions if a.path == "/objects/120")+ schema = await search.execute({"action": action.id}, ctx())+ assert schema.success and "input_schema" in schema.output+ result = await call.execute({"action": action.id, "arguments": {}}, ctx())+ assert result.success and calls == [BASE + "/objects/120"]+ store.delete(spec.id)+ assert not (await call.execute({"action": action.id, "arguments": {}}, ctx())).success+ await runtime.stop()+++async def test_dynamic_risk_and_multipart_upload(store, tmp_path):+ spec = definition()+ store.save(spec, KEY)+ audio = tmp_path / "sample.wav"+ audio.write_bytes(b"RIFF-example-audio")+ requests = []++ def respond(request):+ requests.append(request)+ assert "multipart/form-data; boundary=" in request.headers["Content-Type"]+ assert b"RIFF-example-audio" in request.content+ assert b'name="file"' in request.content+ return httpx.Response(200, json={"text": "Hello"})++ runtime = CustomApiRuntime(store, transport=httpx.MockTransport(respond))+ await runtime.refresh()+ tool = runtime.tools[f"api_{spec.id}_call"]+ delete = next(a for a in spec.actions if a.method == "DELETE")+ assert tool.risk_tier_for_args({"action": delete.id}) == "ask"+ assert tool.describe_args({"action": delete.id})["level"] == "modify"+ action = next(a for a in spec.actions if a.path == "/transcribe")+ result = await tool.execute(+ {"action": action.id, "arguments": {"body": {"file": str(audio)}}}, ctx()+ )+ assert result.success and result.output == {"text": "Hello"}+ assert len(requests) == 1+ await runtime.stop()+++async def test_query_credentials_reach_service_but_not_http_logs_or_results(store, caplog):+ spec = definition()+ spec.auth.mode = "query"+ spec.auth.header_name = "appid"+ store.save(spec, KEY)++ def respond(request):+ assert request.url.params["appid"] == KEY+ return httpx.Response(200, json={"echo": KEY})++ runtime = CustomApiRuntime(store, transport=httpx.MockTransport(respond))+ await runtime.refresh()+ action = spec.actions[0]+ with caplog.at_level(logging.INFO, logger="httpx"):+ result = await runtime.tools[f"api_{spec.id}_call"].execute(+ {"action": action.id, "arguments": {}}, ctx()+ )+ assert result.success and result.output == {"echo": "[redacted]"}+ assert KEY not in caplog.text+ await runtime.stop()+++ "status, expected", [(200, "verified"), (403, "limited"), (503, "configured")]+)+async def test_setup_only_uses_a_documented_account_read(status, expected):+ calls = []++ def respond(request):+ calls.append(request)+ assert request.method == "GET" and request.url.path == "/v1/user"+ assert request.headers["X-API-Key"] == KEY+ return httpx.Response(status)++ assert (+ await verify_api_key(definition(), KEY, transport=httpx.MockTransport(respond)) == expected+ )+ assert len(calls) == 1+++async def test_rejected_key_never_installs_a_connection():+ with pytest.raises(ApiDiscoveryError, match="invalid_key"):+ await verify_api_key(+ definition(), KEY, transport=httpx.MockTransport(lambda request: httpx.Response(401))+ )+++async def test_unlisted_service_is_discovered_from_public_brand_documentation():+ class Discovery(ApiDiscovery):+ def __init__(self):+ super().__init__(directory={})+ self._brands = [{"title": "Sample Cloud", "source": BASE + "/brand"}]+ self.urls = []++ async def _fetch(self, url, maximum=0):+ self.urls.append(url)+ assert KEY not in url+ return json.dumps(document()).encode(), url++ async def _logo(self, domain, image_url=""):+ return ""++ discovery = Discovery()+ spec = await discovery.resolve("Sample Cloud")+ assert spec.name == "Sample Cloud" and len(spec.actions) == 4+ assert spec.base_url == BASE+ assert discovery.urls == [BASE + "/openapi.json"]+ await discovery.close()+++def test_directory_match_is_not_a_fixed_service_allowlist():+ index = {+ "sample.example": {+ "preferred": "1",+ "versions": {+ "1": {+ "info": {"title": "Sample Cloud"},+ "swaggerUrl": BASE + "/openapi.json",+ }+ },+ }+ }+ assert ApiDiscovery._match("Sample Cloud", index)[0] == "sample.example"+ assert ApiDiscovery._match("Different brand", index) is None+ with pytest.raises(ApiDiscoveryError) as error:+ ApiDiscovery._match("Sampl Cloud", index)+ assert error.value.code == "ambiguous_service"+ assert error.value.suggestions == ["Sample Cloud"]+++def test_name_and_key_route_keeps_credentials_out_of_discovery_and_summaries(store):+ calls = []++ class Discovery:+ async def resolve(self, name):+ calls.append(name)+ assert KEY not in name+ return definition(125)++ async def verify(spec, credential):+ assert credential == KEY+ return "verified"++ app = FastAPI()+ app.state.custom_api_store = store+ app.state.custom_api_discovery = Discovery()+ app.state.custom_api_verifier = verify+ app.state.plugin_registry = PluginToolRegistry(+ catalog=PluginCatalog(version=1, schema_version="1", plugins=[]),+ custom_api_runtime=CustomApiRuntime(store),+ )+ app.include_router(router)+ with TestClient(app) as client:+ identifier = uuid4().hex+ response = client.post(+ "/api/custom-apis/connect",+ json={"id": identifier, "name": "Sample Cloud", "credential": KEY},+ )+ assert response.status_code == 200, response.text+ assert response.json()["action_count"] == 125+ assert response.json()["tools_ready"] and response.json()["status"] == "verified"+ assert KEY not in response.text and "body_schema" not in response.text+ assert calls == ["Sample Cloud"]+ assert len(app.state.plugin_registry.active_tools()) == 2+ assert client.get("/api/custom-apis/connections").json() == [response.json()]+ assert (+ len(client.get(f"/api/custom-apis/connections/{identifier}/actions").json()["actions"])+ == 125+ )+ paused = client.patch(f"/api/custom-apis/connections/{identifier}", json={"enabled": False})+ assert not paused.json()["tools_ready"]+ assert len(app.state.plugin_registry.active_tools()) == 0+ assert client.delete(f"/api/custom-apis/{identifier}").status_code == 200+++def test_api_definition_cache_cannot_be_mutated_by_a_caller(store):+ spec = definition()+ store.save(spec, KEY)+ first = store.get(spec.id)+ first.name = "Changed in memory"+ first.actions[0].path = "/changed"+ assert store.get(spec.id) == spec+++async def test_managed_service_reaches_composer_society_and_mission_with_existing_denies(store):+ from types import SimpleNamespace++ from jarvis.agent_chat.tool_catalog import build_catalog, resolve_choices, selection_tools+ from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+ from jarvis.core import runtime_refs+ from jarvis.missions.init import _custom_api_worker_tools+ from jarvis.missions.workers.worker_tool_broker import worker_tool_name_allowed+ from jarvis.society.capabilities import build_catalog as society_catalog+ from jarvis.society.capabilities import select_tools++ spec = definition(125)+ spec.connection.brand_id = "sample"+ store.save(spec, KEY)+ runtime = CustomApiRuntime(store)+ await runtime.refresh()+ previous = runtime_refs.get_supervisor_tool_gateway()+ runtime_refs.set_supervisor_tool_gateway(+ BrainSupervisorToolGateway(SimpleNamespace(_tools=runtime.tools))+ )+ try:+ rows = build_catalog(runtime.tools)+ assert len(rows) == 1 and rows[0].brand == "sample"+ choices = resolve_choices([rows[0].id], rows)+ assert selection_tools(choices, runtime.tools) == runtime.tools+ names = _custom_api_worker_tools("Use " + spec.name)+ assert len(names) == 2 and all(worker_tool_name_allowed(n) for n in names)+ assert select_tools(runtime.tools, grant_mode="all", grants=[], focus=[], denies=[]) == (+ runtime.tools+ )+ denied = select_tools(+ runtime.tools,+ grant_mode="all",+ grants=[],+ focus=[],+ denies=[row.id for row in society_catalog(runtime.tools)],+ )+ assert not denied+ assert KEY not in str(rows) + str(names)+ finally:+ runtime_refs.set_supervisor_tool_gateway(previous)+ await runtime.stop()diff --git a/tests/unit/marketplace/test_custom_connector.py b/tests/unit/marketplace/test_custom_connector.pynew file mode 100644index 0000000000..ca4c7e55f3--- /dev/null+++ b/tests/unit/marketplace/test_custom_connector.py@@ -0,0 +1,370 @@+"""Custom connectors: an MCP server added by name and address.++The probe is the whole inspection, so these tests pin what it concludes from+each answer a real server can give: a handshake (no sign-in), a 401 that+points at OAuth metadata, a 401 with nothing to discover (a key is needed),+an old SSE endpoint, and the answers that mean "this is not an MCP address".+Every request runs against an ``httpx.MockTransport``; nothing leaves the box.+"""++from __future__ import annotations++import json++import httpx+import pytest++from jarvis.marketplace.catalog import PluginSpec+from jarvis.marketplace.custom_connector import (+ ConnectorError,+ ConnectorProbe,+ build_connector_spec,+ connector_auth_headers,+ connector_id,+ display_name_for,+ normalize_connector_url,+ normalize_header_name,+ probe_connector,+ resolve_auth,+)+from jarvis.marketplace.plugin_mcp import plugin_to_mcp_server_spec+from jarvis.marketplace.token_store import Tokens++URL = "https://mcp.example.com/mcp"+++def _initialize_reply(name: str = "Example Server") -> dict:+ return {+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "protocolVersion": "2025-06-18",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": name, "version": "1.0.0"},+ },+ }+++def _transport(routes: dict[tuple[str, str], httpx.Response], seen: list | None = None):+ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ key = (request.method, str(request.url))+ if key in routes:+ return routes[key]+ return httpx.Response(404)++ return httpx.MockTransport(handler)+++# ----------------------------------------------------------------------+# Address, id and header rules+# ----------------------------------------------------------------------+++def test_a_bare_host_becomes_an_https_address() -> None:+ assert normalize_connector_url("mcp.example.com/mcp") == URL+++def test_the_fragment_is_dropped_and_the_host_lowercased() -> None:+ assert normalize_connector_url(" https://MCP.Example.com/mcp#x ") == URL+++ "url",+ ["http://localhost:8000/mcp", "http://127.0.0.1:3000/mcp", "http://192.168.1.20/mcp",+ "http://nas/mcp", "http://homeassistant.local:8123/mcp_server/sse"],+)+def test_plain_http_is_accepted_on_this_computer_and_the_local_network(url: str) -> None:+ assert normalize_connector_url(url).startswith("http://")+++ ("url", "fragment"),+ [+ ("", "Enter the address"),+ ("http://mcp.example.com/mcp", "https://"),+ ("ftp://mcp.example.com", "https://"),+ ("https://user:[email protected]/mcp", "user name and password"),+ ],+)+def test_addresses_that_cannot_be_used_are_refused_with_a_reason(url: str, fragment: str) -> None:+ with pytest.raises(ConnectorError, match=fragment):+ normalize_connector_url(url)+++def test_the_id_comes_from_the_name_and_never_collides() -> None:+ assert connector_id("Linear Tools", URL, []) == "linear-tools"+ assert connector_id("Linear Tools", URL, ["linear-tools"]) == "linear-tools-2"+ assert connector_id("Linear Tools", URL, ["linear-tools", "linear-tools-2"]) == "linear-tools-3"+++def test_an_id_from_a_name_without_ascii_falls_back_to_the_host() -> None:+ assert connector_id("Café Tools", URL, []) == "cafe-tools"+ assert connector_id("日本", "https://mcp.acme.io/mcp", []) == "acme"+++def test_a_blank_name_uses_the_servers_own_name() -> None:+ probe = ConnectorProbe(auth="none", transport="http", status=200, server_name="Acme MCP")+ assert display_name_for(" ", URL, probe) == "Acme MCP"+ assert display_name_for("", "https://mcp.acme.io/mcp") == "Acme"+++def test_header_names_default_to_authorization_and_refuse_transport_headers() -> None:+ assert normalize_header_name(None) == "Authorization"+ assert normalize_header_name("X-API-Key") == "X-API-Key"+ with pytest.raises(ConnectorError):+ normalize_header_name("Content-Type")+ with pytest.raises(ConnectorError):+ normalize_header_name("X API Key")+++# ----------------------------------------------------------------------+# Probe+# ----------------------------------------------------------------------+++async def test_a_server_that_answers_needs_no_sign_in() -> None:+ transport = _transport({("POST", URL): httpx.Response(200, json=_initialize_reply())})++ probe = await probe_connector(URL, transport=transport)++ assert probe.auth == "none"+ assert probe.transport == "http"+ assert probe.server_name == "Example Server"+++async def test_an_sse_formatted_handshake_is_read_from_its_first_event() -> None:+ body = f"event: message\ndata: {json.dumps(_initialize_reply('Streamer'))}\n\n"+ reply = httpx.Response(200, text=body, headers={"content-type": "text/event-stream"})+ probe = await probe_connector(URL, transport=_transport({("POST", URL): reply}))++ assert probe.auth == "none"+ assert probe.server_name == "Streamer"+++async def test_the_session_a_probe_opened_is_closed_again() -> None:+ seen: list[httpx.Request] = []+ reply = httpx.Response(200, json=_initialize_reply(), headers={"mcp-session-id": "s-1"})+ transport = _transport(+ {("POST", URL): reply, ("DELETE", URL): httpx.Response(204)}, seen+ )++ await probe_connector(URL, transport=transport)++ closing = [r for r in seen if r.method == "DELETE"]+ assert closing and closing[0].headers["mcp-session-id"] == "s-1"+++async def test_a_401_with_resource_metadata_and_registration_is_oauth() -> None:+ resource = "https://mcp.example.com/.well-known/oauth-protected-resource/mcp"+ transport = _transport(+ {+ ("POST", URL): httpx.Response(+ 401, headers={"www-authenticate": f'Bearer resource_metadata="{resource}"'}+ ),+ ("GET", resource): httpx.Response(+ 200,+ json={"resource": URL, "authorization_servers": ["https://auth.example.com"]},+ ),+ ("GET", "https://auth.example.com/.well-known/oauth-authorization-server"):+ httpx.Response(+ 200,+ json={+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ "registration_endpoint": "https://auth.example.com/register",+ },+ ),+ }+ )++ probe = await probe_connector(URL, transport=transport)++ assert probe.auth == "oauth"+ assert probe.discovery_url == resource+ assert probe.registration is True+ assert resolve_auth("auto", probe) == "oauth"+++async def test_oauth_without_self_registration_is_named_not_attempted() -> None:+ root_meta = "https://mcp.example.com/.well-known/oauth-authorization-server"+ transport = _transport(+ {+ ("POST", URL): httpx.Response(401),+ ("GET", root_meta): httpx.Response(+ 200,+ json={+ "authorization_endpoint": "https://mcp.example.com/authorize",+ "token_endpoint": "https://mcp.example.com/token",+ },+ ),+ }+ )++ probe = await probe_connector(URL, transport=transport)++ assert probe.auth == "oauth"+ assert probe.registration is False+ with pytest.raises(ConnectorError, match="Access token"):+ resolve_auth("auto", probe)+ # The owner's own pick of a token stays possible.+ assert resolve_auth("token", probe) == "token"+++async def test_a_401_with_nothing_to_discover_needs_a_token() -> None:+ probe = await probe_connector(URL, transport=_transport({("POST", URL): httpx.Response(401)}))++ assert probe.auth == "token"+ assert resolve_auth("auto", probe) == "token"+++async def test_a_token_in_the_headers_turns_the_probe_into_a_credential_check() -> None:+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ if request.headers.get("x-api-key") == "good":+ return httpx.Response(200, json=_initialize_reply())+ return httpx.Response(401)++ transport = httpx.MockTransport(handler)++ accepted = await probe_connector(URL, headers={"X-API-Key": "good"}, transport=transport)+ refused = await probe_connector(URL, headers={"X-API-Key": "bad"}, transport=transport)++ assert accepted.auth == "none"+ assert refused.auth == "token"+++async def test_an_old_sse_endpoint_is_found_behind_a_405() -> None:+ sse = "https://mcp.example.com/sse"+ transport = _transport(+ {+ ("POST", sse): httpx.Response(405),+ ("GET", sse): httpx.Response(+ 200, text="event: endpoint\ndata: /messages\n\n",+ headers={"content-type": "text/event-stream"},+ ),+ }+ )++ probe = await probe_connector(sse, transport=transport)++ assert probe.transport == "sse"+ assert probe.auth == "none"+++async def test_a_web_page_is_not_an_mcp_server() -> None:+ page = httpx.Response(200, text="<html></html>", headers={"content-type": "text/html"})+ with pytest.raises(ConnectorError, match="web page"):+ await probe_connector(URL, transport=_transport({("POST", URL): page}))+++async def test_a_web_page_that_refuses_post_is_still_named_a_web_page() -> None:+ page = httpx.Response(200, text="<html></html>", headers={"content-type": "text/html"})+ transport = _transport({("POST", URL): httpx.Response(405), ("GET", URL): page})+ with pytest.raises(ConnectorError, match="web page"):+ await probe_connector(URL, transport=transport)+++async def test_an_unexpected_status_names_the_likely_fix() -> None:+ with pytest.raises(ConnectorError, match="/mcp"):+ await probe_connector(URL, transport=_transport({("POST", URL): httpx.Response(500)}))+++async def test_a_redirect_to_another_host_is_refused() -> None:+ moved = httpx.Response(307, headers={"location": "http://169.254.169.254/latest"})+ with pytest.raises(ConnectorError, match="different address"):+ await probe_connector(URL, transport=_transport({("POST", URL): moved}))+++async def test_an_unreachable_server_is_a_readable_sentence() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused", request=request)++ with pytest.raises(ConnectorError, match="could not reach mcp.example.com"):+ await probe_connector(URL, transport=httpx.MockTransport(handler))+++# ----------------------------------------------------------------------+# Decision and catalog entry+# ----------------------------------------------------------------------+++def test_the_owner_cannot_force_a_sign_in_the_server_does_not_have() -> None:+ answered = ConnectorProbe(auth="none", transport="http", status=200)+ wants_key = ConnectorProbe(auth="token", transport="http", status=401)+ with pytest.raises(ConnectorError):+ resolve_auth("oauth", answered)+ with pytest.raises(ConnectorError):+ resolve_auth("oauth", wants_key)+ with pytest.raises(ConnectorError):+ resolve_auth("none", wants_key)+ assert resolve_auth("token", answered) == "token"+++def _oauth_probe() -> ConnectorProbe:+ return ConnectorProbe(+ auth="oauth",+ transport="http",+ status=401,+ discovery_url="https://mcp.example.com/.well-known/oauth-protected-resource",+ )+++def test_an_oauth_connector_uses_the_dcr_flow_and_a_bearer_header() -> None:+ spec = build_connector_spec(+ plugin_id="acme", display_name="Acme", url=URL, auth="oauth", probe=_oauth_probe()+ )++ assert isinstance(spec, PluginSpec)+ assert spec.source == "local"+ assert spec.category == "Custom"+ assert spec.auth.mode == "hosted_mcp_oauth_dcr"+ assert spec.auth.discovery_url == _oauth_probe().discovery_url+ resolved = plugin_to_mcp_server_spec(spec, Tokens(access="tok"))+ assert resolved is not None+ assert resolved[0].url == URL+ assert resolved[0].headers == {"Authorization": "Bearer tok"}+++def test_a_token_connector_sends_the_key_in_the_chosen_header() -> None:+ probe = ConnectorProbe(auth="token", transport="http", status=401)+ spec = build_connector_spec(+ plugin_id="acme", display_name="Acme", url=URL, auth="token", probe=probe,+ header_name="X-API-Key",+ )++ assert spec.auth.mode == "pat_paste"+ assert spec.auth.validation_method == "mcp_initialize"+ assert spec.auth.validation_endpoint == URL+ assert connector_auth_headers(spec, "k-1") == {"X-API-Key": "k-1"}+ resolved = plugin_to_mcp_server_spec(spec, Tokens(access="k-1"))+ assert resolved is not None and resolved[0].headers == {"X-API-Key": "k-1"}+++def test_an_open_connector_sends_no_credential_and_keeps_its_transport() -> None:+ probe = ConnectorProbe(auth="none", transport="sse", status=200)+ spec = build_connector_spec(+ plugin_id="acme", display_name="Acme", url=URL, auth="none", probe=probe+ )++ assert spec.auth.mode == "hosted_mcp_open"+ resolved = plugin_to_mcp_server_spec(spec, Tokens(access="open"))+ assert resolved is not None+ assert resolved[0].transport == "sse"+ assert resolved[0].headers == {}diff --git a/tests/unit/marketplace/test_custom_connector_routes.py b/tests/unit/marketplace/test_custom_connector_routes.pynew file mode 100644index 0000000000..ff8f9ccdb4--- /dev/null+++ b/tests/unit/marketplace/test_custom_connector_routes.py@@ -0,0 +1,223 @@+"""Custom connector routes: add by URL, connect, remove.++Runs the real router with every data/ path redirected into tmp, an in-memory+token store, and the probe replaced by a fake that answers the way a given+server would. The point is the wiring: the entry a connector writes must be+an ordinary plugin to every route that already exists.+"""++from __future__ import annotations++from pathlib import Path++import httpx+import pytest+from fastapi import FastAPI++from jarvis.marketplace import catalog_data, custom_connector+from jarvis.marketplace.custom_connector import ConnectorError, ConnectorProbe+from jarvis.marketplace.token_store import InMemoryBackend, TokenStore+from jarvis.marketplace.usage_cards import loader as cards_loader+from jarvis.ui.web import marketplace_routes as routes++URL = "https://mcp.acme.example/mcp"+++class FakeServer:+ """Answers probes like one MCP server; records the headers it was sent."""++ def __init__(self, probe: ConnectorProbe | None = None, *, accepts: str | None = None):+ self.probe = probe or ConnectorProbe(auth="none", transport="http", status=200)+ self.accepts = accepts+ self.calls: list[tuple[str, dict]] = []+ self.down = False++ async def __call__(self, url: str, *, headers=None, transport=None) -> ConnectorProbe:+ self.calls.append((url, dict(headers or {})))+ if self.down:+ raise ConnectorError("Jarvis could not reach mcp.acme.example.")+ if headers and self.accepts is not None:+ ok = self.accepts in headers.values()+ return ConnectorProbe(+ auth="none" if ok else "token", transport="http", status=200 if ok else 401+ )+ return self.probe+++def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(catalog_data, "_DEFAULT_CATALOG_PATH", tmp_path / "plugin_catalog.json")+ monkeypatch.setattr(cards_loader, "_DATA_CARDS_DIR", tmp_path / "usage_cards")+ store = TokenStore(InMemoryBackend())+ monkeypatch.setattr(routes, "TokenStore", lambda: store)+ refreshed: list[str] = []+ monkeypatch.setattr(routes, "_refresh_plugin_in_live_registry", refreshed.append)+ server = FakeServer()+ monkeypatch.setattr(custom_connector, "probe_connector", server)+ catalog_data.clear_cache()+ cards_loader.load_usage_card.cache_clear()+ yield {"store": store, "server": server, "refreshed": refreshed}+ catalog_data.clear_cache()+ cards_loader.load_usage_card.cache_clear()+++def _client() -> httpx.AsyncClient:+ app = FastAPI()+ app.include_router(routes.router)+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")+++async def _add(client: httpx.AsyncClient, **body) -> httpx.Response:+ return await client.post("/api/marketplace/connectors", json={"url": URL, **body})+++async def test_an_added_connector_is_an_ordinary_plugin(env) -> None:+ async with _client() as client:+ added = await _add(client, name="Acme Tools")+ listed = await client.get("/api/marketplace/plugins")++ assert added.status_code == 200+ item = added.json()["plugin"]+ assert item["id"] == "acme-tools"+ assert item["source"] == "local"+ assert item["status"] == "not_connected"+ assert added.json()["detected"] == {"auth": "none", "transport": "http", "server_name": None}+ entry = next(p for p in listed.json()["plugins"] if p["id"] == "acme-tools")+ assert entry["auth"]["mode"] == "hosted_mcp_open"+ assert entry["mcp_server"]["url"] == URL+ assert env["refreshed"] == ["acme-tools"]+++async def test_the_same_server_cannot_be_added_twice(env) -> None:+ async with _client() as client:+ await _add(client, name="Acme")+ again = await _add(client, name="Acme again", url="mcp.acme.example/mcp")++ assert again.status_code == 409+ assert "already added as Acme" in again.json()["detail"]+++async def test_a_name_that_matches_a_built_in_gets_its_own_id(env) -> None:+ async with _client() as client:+ added = await _add(client, name="Notion")++ assert added.status_code == 200+ assert added.json()["plugin"]["id"] == "notion-2"+++async def test_an_unreachable_server_writes_nothing(env) -> None:+ env["server"].down = True+ async with _client() as client:+ refused = await _add(client, name="Acme")+ listed = await client.get("/api/marketplace/plugins")++ assert refused.status_code == 422+ assert "could not reach" in refused.json()["detail"]+ assert all(p["source"] != "local" for p in listed.json()["plugins"])+++async def test_a_bad_address_is_a_400_before_anything_is_contacted(env) -> None:+ async with _client() as client:+ refused = await _add(client, url="http://mcp.acme.example/mcp")++ assert refused.status_code == 400+ assert env["server"].calls == []+++async def test_an_open_connector_connects_after_one_answered_handshake(env) -> None:+ async with _client() as client:+ await _add(client, name="Acme")+ started = await client.post("/api/marketplace/plugins/acme/connect/start")+ listed = await client.get("/api/marketplace/plugins")++ assert started.status_code == 200+ assert started.json()["kind"] == "local"+ assert env["store"].load("acme") is not None+ assert next(p for p in listed.json()["plugins"] if p["id"] == "acme")["status"] == "connected"+++async def test_an_open_connector_that_now_wants_sign_in_is_not_marked_connected(env) -> None:+ async with _client() as client:+ await _add(client, name="Acme")+ env["server"].probe = ConnectorProbe(auth="token", transport="http", status=401)+ started = await client.post("/api/marketplace/plugins/acme/connect/start")++ assert started.status_code == 409+ assert env["store"].load("acme") is None+++async def test_a_token_connector_checks_the_key_with_an_mcp_handshake(env) -> None:+ env["server"].probe = ConnectorProbe(auth="token", transport="http", status=401)+ env["server"].accepts = "Bearer good-key"+ async with _client() as client:+ added = await _add(client, name="Acme")+ assert added.json()["plugin"]["auth"]["mode"] == "pat_paste"+ refused = await client.post(+ "/api/marketplace/plugins/acme/connect/pat", json={"token": "bad-key"}+ )+ accepted = await client.post(+ "/api/marketplace/plugins/acme/connect/pat", json={"token": "good-key"}+ )++ assert refused.status_code == 401+ assert accepted.status_code == 200+ assert env["store"].load("acme").access == "good-key"+ assert env["server"].calls[-1] == (URL, {"Authorization": "Bearer good-key"})+++async def test_a_custom_header_name_carries_the_key(env) -> None:+ env["server"].probe = ConnectorProbe(auth="token", transport="http", status=401)+ env["server"].accepts = "k-1"+ async with _client() as client:+ await _add(client, name="Acme", auth="token", header_name="X-API-Key")+ accepted = await client.post(+ "/api/marketplace/plugins/acme/connect/pat", json={"token": "k-1"}+ )++ assert accepted.status_code == 200+ assert env["server"].calls[-1][1] == {"X-API-Key": "k-1"}+++async def test_oauth_without_self_registration_is_refused_with_the_way_out(env) -> None:+ env["server"].probe = ConnectorProbe(+ auth="oauth", transport="http", status=401,+ discovery_url="https://mcp.acme.example/.well-known/oauth-authorization-server",+ registration=False,+ )+ async with _client() as client:+ refused = await _add(client, name="Acme")++ assert refused.status_code == 422+ assert "Access token" in refused.json()["detail"]+++async def test_a_connector_the_owner_added_can_be_removed(env) -> None:+ async with _client() as client:+ await _add(client, name="Acme")+ await client.post("/api/marketplace/plugins/acme/connect/start")+ removed = await client.delete("/api/marketplace/community/plugins/acme")+ listed = await client.get("/api/marketplace/plugins")++ assert removed.status_code == 200+ assert removed.json()["removed"] is True+ assert env["store"].load("acme") is None+ assert all(p["id"] != "acme" for p in listed.json()["plugins"])+++async def test_a_built_in_plugin_still_cannot_be_removed(env) -> None:+ async with _client() as client:+ refused = await client.delete("/api/marketplace/community/plugins/notion")++ assert refused.status_code == 409diff --git a/tests/unit/platform/test_open_url_credentials.py b/tests/unit/platform/test_open_url_credentials.pynew file mode 100644index 0000000000..82ba524d05--- /dev/null+++ b/tests/unit/platform/test_open_url_credentials.py@@ -0,0 +1,28 @@+"""Browser launcher diagnostics must never expose pairing or OAuth credentials."""++import logging+import subprocess++from jarvis.platform import open_path+++def test_opener_timeout_does_not_log_credential(monkeypatch, caplog):+ url = "https://example.test/enter#private-example-ticket"++ def timeout(argv, **kwargs):+ raise subprocess.TimeoutExpired(argv, 8)++ monkeypatch.setattr(open_path.subprocess, "run", timeout)+ with caplog.at_level(logging.DEBUG):+ assert not open_path._run_opener_checked(["open", url])+ assert "private-example-ticket" not in caplog.text+ assert "TimeoutExpired" in caplog.text+++def test_browser_success_does_not_log_url_fragment(monkeypatch, caplog):+ monkeypatch.setattr(open_path, "_windows_browser_candidates", lambda: ["browser"])+ monkeypatch.setattr(open_path.subprocess, "Popen", lambda *args, **kwargs: object())+ with caplog.at_level(logging.DEBUG):+ assert open_path._open_url_windows("https://example.test/enter#private-example-ticket")+ assert "private-example-ticket" not in caplog.text+ assert "example.test" in caplog.textdiff --git a/tests/unit/plugins/brain/test_ollama.py b/tests/unit/plugins/brain/test_ollama.pyindex 489b7b02cd..30b022ee17 100644--- a/tests/unit/plugins/brain/test_ollama.py+++ b/tests/unit/plugins/brain/test_ollama.py@@ -88,6 +88,7 @@ def test_client_defaults_to_localhost_v1_with_dummy_key(monkeypatch) -> None:assert _FakeOpenAI.last_kwargs["base_url"] == "http://localhost:11434/v1"# Keyless: the SDK insists on a non-empty key, Ollama ignores it.assert _FakeOpenAI.last_kwargs["api_key"] == "ollama"+ assert _FakeOpenAI.last_kwargs["max_retries"] == 0def test_client_uses_config_override_root(monkeypatch) -> None:@@ -371,9 +372,9 @@ async def test_image_turn_without_a_vision_download_errors_honestly(monkeypatch,with pytest.raises(RuntimeError) as err:await brain._resolve_model(need_vision=True)assert f"ollama pull {RECOMMENDED_VISION_PULL}" in str(err.value)- # The instance corrects its own advertisement so the next synchronous- # resolver question gets the informed answer.- assert brain.supports_vision is False+ # Auto-discovery may see a new download on the next turn. This failed+ # attempt must not permanently disable the retained provider instance.+ assert brain.supports_vision is Trueasync def test_unprobeable_model_is_never_used_for_an_image_turn(monkeypatch, fake_tags) -> None:diff --git a/tests/unit/plugins/brain/test_ollama_agent_recovery.py b/tests/unit/plugins/brain/test_ollama_agent_recovery.pynew file mode 100644index 0000000000..93d0643479--- /dev/null+++ b/tests/unit/plugins/brain/test_ollama_agent_recovery.py@@ -0,0 +1,76 @@+"""Ollama agents retain explicit budgets and recover without changing seats."""++import httpx+import pytest++from jarvis.brain.model_catalog import parse_models_response+from jarvis.core.config import BrainConfig, BrainProviderConfig, JarvisConfig, OllamaModelOptions+from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock+from jarvis.plugins.brain.ollama import OllamaBrain+from tests.fakes.fake_ollama_server import FakeOllamaServer+from tests.fakes.provider_config import install_provider_config++[email protected]("selected,configured", [("local", "local:latest"),+ ("local:latest", "local"), ("local:4b", "local:4b")])+def test_explicit_context_is_available_before_first_request(monkeypatch, selected, configured):+ install_provider_config(monkeypatch, JarvisConfig(brain=BrainConfig(providers={+ "ollama": BrainProviderConfig(models={configured: OllamaModelOptions(num_ctx=4096)}),+ })))+ assert OllamaBrain(model=selected).context_window == 4096+++def server(monkeypatch):+ install_provider_config(monkeypatch, JarvisConfig(brain=BrainConfig(providers={+ "ollama": BrainProviderConfig(base_url="http://ollama.test"),+ })))+ fake = FakeOllamaServer()+ real_client = httpx.AsyncClient+ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(+ **{**kwargs, "transport": fake.transport()},+ ))+ return fake+++async def test_transient_capability_failure_is_retried(server):+ server.add("model", capabilities=("completion", "tools", "vision"))+ brain = OllamaBrain(model="model")+ server.offline = True+ assert await brain._capabilities("model", "http://ollama.test") is None+ server.offline = False+ assert "vision" in await brain._capabilities("model", "http://ollama.test")+++async def test_pinned_text_model_refuses_tool_work_without_switching_model(server):+ server.add("text", capabilities=("completion",))+ server.add("tools", capabilities=("completion", "tools"))+ brain = OllamaBrain(model="text")+ with pytest.raises(RuntimeError, match="does not support tools"):+ await brain._resolve_model(need_tools=True)+ assert brain._model == "text" and not brain.can_call_tools()+++async def test_temporary_vision_probe_failure_does_not_disable_future_turns(server):+ server.add("model", capabilities=("completion", "tools", "vision"))+ brain = OllamaBrain(model="model")+ brain._client = object() # No inference is reached while native metadata is unavailable.+ request = BrainRequest(messages=(BrainMessage("user", "Describe", images=(+ ImageBlock(mime="image/png", data_b64="aGk="),)),))+ server.offline = True+ with pytest.raises(RuntimeError, match="Check the server connection and retry"):+ _ = [delta async for delta in brain.complete(request)]+ assert brain.supports_vision+ server.offline = False+ assert await brain._pinned_model_can_see("model")+++async def test_discovery_skips_internal_profiles_but_keeps_user_imports(server):+ server.add("local-jarvis-deadbeef:latest", size=1)+ server.add("local-voice-8k:latest", size=2)+ server.add("llamacpp:custom", size=3)+ assert await OllamaBrain()._resolve_model(need_tools=True) == "llamacpp:custom"+ models = parse_models_response("ollama", {"models": [+ {"name": name} for name in server.models+ ]})+ assert [model.id for model in models] == ["llamacpp:custom"]diff --git a/tests/unit/society/test_design_library.py b/tests/unit/society/test_design_library.pynew file mode 100644index 0000000000..2d05964d50--- /dev/null+++ b/tests/unit/society/test_design_library.py@@ -0,0 +1,94 @@+"""Saved companion designs: stored for any agent to wear, deduplicated,+capped, tolerant of a damaged file, and reachable over the society API."""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.society import design_library+from jarvis.society.companion import CompanionSkin+from jarvis.ui.web.society_routes import router++GALAXY = {+ "colors": ["#e05cc5", "#6a2fc2", "#160f3d"],+ "pattern": "radial",+ "angle": 135,+ "effect": "stars",+ "name": "Galaxy",+}++[email protected](autouse=True)+def data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))+ return tmp_path+++def test_nothing_saved_lists_nothing() -> None:+ assert design_library.list_designs() == []+++def test_saved_design_round_trips_newest_first() -> None:+ first = design_library.save_design(CompanionSkin.model_validate(GALAXY))+ second = design_library.save_design(+ CompanionSkin.model_validate({"colors": ["#ffffff", "#000000"], "name": "Ink"})+ )+ designs = design_library.list_designs()+ assert [d["id"] for d in designs] == [second["id"], first["id"]]+ assert designs[1]["skin"] == GALAXY+++def test_saving_the_same_look_again_renames_instead_of_duplicating() -> None:+ first = design_library.save_design(CompanionSkin.model_validate(GALAXY))+ again = design_library.save_design(+ CompanionSkin.model_validate({**GALAXY, "colors": ["#E05CC5", "#6a2fc2", "#160f3d"],+ "name": "Milky Way"})+ )+ designs = design_library.list_designs()+ assert again["id"] == first["id"]+ assert [d["skin"]["name"] for d in designs] == ["Milky Way"]+++def test_the_collection_is_capped(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(design_library, "MAX_DESIGNS", 3)+ for angle in range(5):+ design_library.save_design(CompanionSkin.model_validate({**GALAXY, "angle": angle}))+ assert [d["skin"]["angle"] for d in design_library.list_designs()] == [4, 3, 2]+++def test_delete_removes_one_design() -> None:+ saved = design_library.save_design(CompanionSkin.model_validate(GALAXY))+ assert design_library.delete_design(saved["id"]) is True+ assert design_library.delete_design(saved["id"]) is False+ assert design_library.list_designs() == []+++def test_a_damaged_entry_is_skipped_and_a_broken_file_reads_empty() -> None:+ path = design_library._path()+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps({"designs": [+ {"id": "dbad", "skin": {"colors": ["#fff"]}},+ {"id": "dgood", "skin": GALAXY, "created": 1.0},+ "junk",+ ]}), encoding="utf-8")+ assert [d["id"] for d in design_library.list_designs()] == ["dgood"]+ path.write_text("{not json", encoding="utf-8")+ assert design_library.list_designs() == []+++def test_designs_api_saves_lists_and_deletes() -> None:+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)+ saved = client.post("/api/society/designs", json=GALAXY)+ assert saved.status_code == 200+ design_id = saved.json()["id"]+ assert client.get("/api/society/designs").json()["designs"][0]["skin"] == GALAXY+ assert client.post("/api/society/designs", json={"colors": ["#123456"]}).status_code == 422+ assert client.delete(f"/api/society/designs/{design_id}").status_code == 200+ assert client.delete(f"/api/society/designs/{design_id}").status_code == 404diff --git a/tests/unit/ui/test_desktop_detached_windows.py b/tests/unit/ui/test_desktop_detached_windows.pyindex 402fb04ab6..1dcfdc4bc5 100644--- a/tests/unit/ui/test_desktop_detached_windows.py+++ b/tests/unit/ui/test_desktop_detached_windows.py@@ -29,6 +29,7 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom jarvis.ui.desktop_app import DETACHABLE_VIEWS, WINDOW_TITLE, DesktopApp+from jarvis.ui.section_windows import WINDOW_GROUPS, section_windowfrom jarvis.ui.web.desktop_routes import router as desktop_router@@ -39,7 +40,9 @@ class _FakeWindow:self.destroyed = Falseself.shown = 0self.evaluated: list[str] = []- self.events = SimpleNamespace(loaded=_List(), closed=_List(), closing=_List())+ self.events = SimpleNamespace(+ loaded=_List(), closed=_List(), closing=_List(), shown=_List(),+ )def show(self) -> None:self.shown += 1@@ -131,7 +134,7 @@ def test_open_detached_creates_titled_solo_window(monkeypatch, platform) -> Noneassert window.frameless is (platform != "darwin")assert window.resizable is True# Distinct title: FindWindowW-exact focus and the icon setter key on it.- assert window.title == f"{WINDOW_TITLE} — Agents"+ assert window.title == f"{WINDOW_TITLE} — Agentic IDE"assert window.title != WINDOW_TITLEassert "?view=agentic-ide&solo=1" in window.urlassert app._detached_windows == {"agentic-ide": window}@@ -162,12 +165,62 @@ def test_open_detached_is_idempotent_and_focuses(monkeypatch) -> None:def test_open_detached_rejects_unknown_view(monkeypatch) -> None:app = _app(monkeypatch)- assert app.open_detached_window("settings") == {+ assert app.open_detached_window("nonexistent") == {"ok": False,"reason": "unknown_view",}[email protected]("owner,tabs", WINDOW_GROUPS.items())+def test_tabs_share_one_window_and_keep_the_requested_initial_page(+ monkeypatch, owner, tabs,+) -> None:+ import sys++ app = _app(monkeypatch)+ created: list[_FakeWindow] = []+ monkeypatch.setitem(sys.modules, "webview", _fake_webview(created))+ initial = tabs[-1]+ app.open_detached_window(initial)+ assert f"?view={initial}&solo=1&window={owner}" in created[0].url+ for tab in tabs:+ assert app.open_detached_window(tab)["already_open"] is True+ assert len(created) == 1+ assert app.detached_views_snapshot() == [owner]+ assert app.close_detached_window(initial)["ok"] is True+ assert created[0].destroyed is True++[email protected]("view", ["agents", "docs", "memory", "board", "sessions", "marketplace"])+def test_primary_sections_have_independent_windows(monkeypatch, view) -> None:+ import sys++ app = _app(monkeypatch)+ created: list[_FakeWindow] = []+ monkeypatch.setitem(sys.modules, "webview", _fake_webview(created))+ app.open_detached_window("profile")+ app.open_detached_window("agentic-ide")+ assert app.open_detached_window(view)["ok"] is True+ assert len(created) == 3+ assert len({window.title for window in created}) == 3+++def test_missing_detached_window_never_closes_main(monkeypatch) -> None:+ app = _app(monkeypatch)+ result = app.window_command("close", "settings")+ assert result["ok"] is False+ assert app._window.destroyed is False+++def test_window_command_targets_the_settings_owner(monkeypatch) -> None:+ app = _app(monkeypatch)+ settings = _FakeWindow()+ app._detached_windows["settings"] = settings+ assert app.window_command("close", "profile")["ok"] is True+ assert settings.destroyed is True+ assert app._window.destroyed is False++def test_open_detached_reports_backend_failure_with_fallback(monkeypatch) -> None:import sys@@ -487,7 +540,6 @@ def test_detachable_views_have_distinct_titles_per_label() -> None:# shares one label deliberately: only one coding view can be live at once# (single-IDE rule), so their titles can never coexist.app = DesktopApp.__new__(DesktopApp)- coding = {"agentic-ide", "agentic-ide-classic", "chat-workspace"}seen: dict[str, str] = {}for view in DETACHABLE_VIEWS:title = app._detached_title(view)@@ -495,7 +547,7 @@ def test_detachable_views_have_distinct_titles_per_label() -> None:assert title.startswith(WINDOW_TITLE)clash = seen.get(title)if clash is not None:- assert view in coding and clash in coding, (+ assert section_window(view) == section_window(clash), (f"'{view}' and '{clash}' share the title '{title}' but can be ""detached simultaneously")diff --git a/tests/unit/ui/test_pet_context_popup.py b/tests/unit/ui/test_pet_context_popup.pynew file mode 100644index 0000000000..0f15a0ed0f--- /dev/null+++ b/tests/unit/ui/test_pet_context_popup.py@@ -0,0 +1,218 @@+"""Branded popup geometry, keyboard/mouse selection and focus/grab cleanup."""++from types import SimpleNamespace++import pytest+from PIL import ImageColor++from jarvis.platform import monitors+from jarvis.ui.pets import context_menu, menu_renderer+from jarvis.ui.theme import POPOVER_COLORS+from ui.orb import pet_context_menu as popup+++class _Top:+ def __init__(self, parent):+ self.parent = parent+ self.grabbed = False+ self.focus = self+ self.pending = None+ self.cancelled = []++ def bind(self, *args):+ pass++ def grab_set(self):+ self.grabbed = True++ def grab_current(self):+ return self if self.grabbed else None++ def grab_release(self):+ self.grabbed = False++ def focus_force(self):+ pass++ def focus_displayof(self):+ return self.focus++ def winfo_toplevel(self):+ return self++ def after_idle(self, fn):+ self.pending = fn+ return "focus-check"++ def after_cancel(self, identifier):+ self.cancelled.append(identifier)++ def wait_window(self):+ self.parent.on_wait()++ def winfo_rootx(self):+ return self.x++ def winfo_rooty(self):+ return self.y+++class _Surface:+ def __init__(self, parent, size, **kwargs):+ self.top = _Top(parent)+ self.canvas = SimpleNamespace(focus_set=lambda: None)+ self.frames = []+ self.destroyed = False+ parent.surface = self++ def bind(self, *args):+ pass++ def move(self, x, y):+ self.top.x, self.top.y = x, y++ def present(self, frame):+ self.frames.append(frame)++ def show(self):+ pass++ def destroy(self):+ self.destroyed = True+++def menu(monkeypatch):+ monkeypatch.setattr(popup, "AlphaWindow", _Surface)+ monkeypatch.setattr(popup, "appearance", lambda: "dark")+ monkeypatch.setattr(monitors, "work_area_at", lambda x, y: (-1920, 0, 1920, 1080))+ parent = SimpleNamespace(on_wait=lambda: None)+ panel = popup.PetContextMenu(parent, scale=1.5)+ calls = []+ panel.add_command(label="Open app", command=lambda: calls.append("open"), state="disabled")+ panel.add_command(label="Reset position", command=lambda: calls.append("reset"))+ panel.add_separator()+ panel.add_command(+ label="Hide pet",+ accelerator="Alt+Win+P",+ command=lambda: calls.append(("hide", parent.surface.destroyed)),+ )+ return panel, parent, calls+++def test_keyboard_skips_disabled_rows_and_separator_and_closes_before_action(menu):+ panel, parent, calls = menu++ def interact():+ for expected in (1, 3, 1):+ panel._key(SimpleNamespace(keysym="Down"))+ assert panel.selected == expected+ panel._key(SimpleNamespace(keysym="End"))+ panel._key(SimpleNamespace(keysym="Return"))+ panel._activate(3)++ parent.on_wait = interact+ panel.tk_popup(-100, 1000)+ assert calls == [("hide", True)]+ assert not parent.surface.top.grabbed+ assert panel.surface is None+++def test_outside_click_dismisses_without_running_a_command(menu):+ panel, parent, calls = menu+ parent.on_wait = lambda: panel._click(SimpleNamespace(x_root=300, y_root=300))+ panel.tk_popup(-200, 200)+ assert parent.surface.destroyed+ assert not parent.surface.top.grabbed+ assert calls == []+++def test_mouse_hit_testing_uses_scaled_global_coordinates(menu):+ panel, parent, calls = menu++ def interact():+ top = parent.surface.top+ event = SimpleNamespace(x_root=top.x + 50 * panel.scale, y_root=top.y + 100 * panel.scale)+ panel._motion(event)+ assert panel.selected == 3+ panel._click(event)++ parent.on_wait = interact+ panel.tk_popup(-800, 200)+ assert calls == [("hide", True)]++[email protected]("key", ["Escape", "Tab"])+def test_cancel_keys_never_invoke_an_action(menu, key):+ panel, parent, calls = menu+ parent.on_wait = lambda: panel._key(SimpleNamespace(keysym=key))+ panel.tk_popup(-800, 200)+ assert parent.surface.destroyed+ assert calls == []+++def test_focus_loss_closes_and_cancels_pending_idle_callback(menu):+ panel, parent, calls = menu++ def interact():+ panel._focus_out(None)+ top = parent.surface.top+ top.pending()+ assert panel.surface is not None # A child receiving focus keeps the popup.+ panel._focus_out(None)+ top.focus = None+ top.pending()+ assert parent.surface.destroyed++ parent.on_wait = interact+ panel.tk_popup(-800, 200)+ assert not parent.surface.top.grabbed+ assert calls == []+++def test_paint_failure_releases_all_popup_resources(menu, monkeypatch):+ panel, parent, calls = menu++ def fail():+ raise RuntimeError("paint failed")++ monkeypatch.setattr(panel, "_paint", fail)+ with pytest.raises(RuntimeError, match="paint failed"):+ panel.tk_popup(-800, 200)+ assert parent.surface.destroyed+ assert panel.surface is None+++def test_popup_clamps_to_secondary_monitor_work_area():+ assert popup.popup_position(-10, 1070, (360, 198), (-1920, 0, 1920, 1080)) == (-368, 874)+++def test_unsupported_transparency_uses_neutral_corners(menu, monkeypatch):+ panel, parent, _ = menu+ monkeypatch.setattr(popup.sys, "platform", "linux")+ panel.tk_popup(-800, 200)+ assert parent.surface.frames[0].getpixel((0, 0)) == (28, 28, 28, 255)++[email protected]("theme", ["dark", "light"])+def test_actual_renderer_uses_app_tokens_and_transparent_corners(theme):+ entries = [+ menu_renderer.MenuEntry("Open app"),+ menu_renderer.MenuEntry("Reset position", icon="reset"),+ None,+ menu_renderer.MenuEntry("Hide pet", "Alt+Win+P", icon="hide"),+ ]+ frame = menu_renderer.render_menu(entries, theme, selected=1)+ assert frame.size == menu_renderer.menu_size(entries)+ assert frame.getpixel((0, 0))[3] == 0+ assert frame.getpixel((120, 5))[:3] == ImageColor.getrgb(POPOVER_COLORS[theme]["background"])+ assert frame.getpixel((120, 47))[:3] == ImageColor.getrgb(POPOVER_COLORS[theme]["hover"])+++def test_current_appearance_follows_settings_and_system_mode(tmp_path, monkeypatch):+ path = tmp_path / "menu.toml"+ path.write_text('[ui]\ntheme="light"')+ assert context_menu.appearance(path) == "light"+ path.write_text('[ui]\ntheme="system"')+ monkeypatch.setattr("jarvis.ui.theme.detect_os_theme", lambda: "dark")+ assert context_menu.appearance(path) == "dark"diff --git a/tests/unit/ui/test_pet_right_click.py b/tests/unit/ui/test_pet_right_click.pyindex 830f3ff938..2c33be46a1 100644--- a/tests/unit/ui/test_pet_right_click.py+++ b/tests/unit/ui/test_pet_right_click.py@@ -1,7 +1,9 @@-"""The pet's right-click hides the whole surface until its global shortcut."""+"""The pet context menu offers dismissal without hiding on the opening click."""from __future__ import annotations+from types import SimpleNamespace+import pytestfrom jarvis.core.bus import EventBus@@ -9,6 +11,8 @@ from jarvis.core.events import PetVisibilityToggleRequestedfrom jarvis.ui.jarvisbar import hostfrom jarvis.ui.jarvisbar.modes import MODESfrom jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlay+from jarvis.ui.pets import context_menu+from ui.orb import overlay, pet_context_menufrom ui.orb.bus_bridge import OrbBusBridgefrom ui.orb.overlay import OrbOverlay, PetControlStrip@@ -31,9 +35,42 @@ class _Window:def lift(self) -> None:pass+ def winfo_pointerxy(self) -> tuple[int, int]:+ return (100, 200)+++class _Menu:+ def __init__(self, root, **kwargs) -> None:+ self.commands = []+ self.position = None+ self.released = False+ self.destroyed = False++ def add_command(self, **kwargs) -> None:+ self.commands.append(kwargs)++ def add_separator(self) -> None:+ pass++ def tk_popup(self, x, y) -> None:+ self.position = (x, y)++ def grab_release(self) -> None:+ self.released = True++ def destroy(self) -> None:+ self.destroyed = True++ def choose(self, label) -> None:+ next(row for row in self.commands if row["label"] == label)["command"]()+@pytest.fixturedef pet(monkeypatch):+ monkeypatch.setattr(pet_context_menu, "PetContextMenu", _Menu)+ monkeypatch.setattr(context_menu, "preferences", lambda: (+ context_menu.LABELS["en"], "Alt+Win+P",+ ))surface = OrbOverlay(style="pet", pet_id="ember")surface._mac_transparent = Falsesurface._root = _Window()@@ -47,10 +84,19 @@ def pet(monkeypatch):return surface-def test_right_click_hides_figure_strip_and_cards_without_opening_window(pet) -> None:+def test_right_click_opens_menu_then_hide_dismisses_figure_strip_and_cards(pet) -> None:opened = []pet.set_on_show_window(lambda: opened.append(True))- pet._on_right_click()+ pet._on_right_click(SimpleNamespace(x_root=-400, y_root=300))+ assert not pet.pet_user_hidden+ assert pet._root.visible+ assert pet._context_menu.position == (-400, 300)+ assert pet._context_menu.released+ assert [row["label"] for row in pet._context_menu.commands] == [+ "Open app", "Reset position", "Hide pet",+ ]+ assert pet._context_menu.commands[-1]["accelerator"] == "Alt+Win+P"+ pet._context_menu.choose("Hide pet")assert pet.pet_user_hiddenassert not openedassert all(not window.visible for window in (@@ -63,6 +109,7 @@ async def test_voice_updates_stay_hidden_until_existing_hotkey_event(pet) -> Nonbridge = OrbBusBridge(bus, pet)bridge.attach()pet._on_right_click()+ pet._context_menu.choose("Hide pet")for mode in MODES:pet.show(mode)assert not pet._root.visible@@ -75,10 +122,13 @@ async def test_voice_updates_stay_hidden_until_existing_hotkey_event(pet) -> Nonassert pet.pet_user_hidden-def test_strip_right_click_uses_the_same_pet_dismissal(pet) -> None:+def test_strip_right_click_opens_the_same_menu_without_hiding(pet) -> None:strip = PetControlStrip.__new__(PetControlStrip)strip._on_context = pet._on_right_clickstrip._on_context_event(None)+ assert not pet.pet_user_hidden+ assert pet._context_menu.position == (100, 200)+ pet._context_menu.choose("Hide pet")assert pet.pet_user_hiddenassert not pet._root.visible@@ -91,6 +141,8 @@ def test_host_reports_right_click_and_restores_hidden_pet_after_respawn(pet, monmonkeypatch.setattr(proxy, "_send", lambda msg: host.dispatch(pet, msg))host._wire_surface_events(pet)pet._on_right_click()+ assert not proxy.pet_user_hidden+ pet._context_menu.choose("Hide pet")assert proxy.pet_user_hiddenreplay = []monkeypatch.setattr(proxy, "_send", replay.append)@@ -103,12 +155,68 @@ def test_host_reports_right_click_and_restores_hidden_pet_after_respawn(pet, monassert pet._root.visible-def test_right_click_is_safe_without_window_or_with_failed_observer() -> None:+def test_right_click_without_a_window_does_not_hide_the_pet() -> None:pet = OrbOverlay(style="pet")+ pet._on_right_click()+ assert not pet.pet_user_hidden+++def test_menu_hide_survives_a_failed_observer(pet) -> None:def fail(visible):raise RuntimeError("observer unavailable")pet.set_on_visibility_changed(fail)pet._on_right_click()+ pet._context_menu.choose("Hide pet")assert pet.pet_user_hidden+++def test_open_and_reset_actions_do_not_hide_the_pet(pet, monkeypatch) -> None:+ calls = []+ pet.set_on_show_window(lambda: calls.append("open"))+ monkeypatch.setattr(pet, "_on_reset_double_click", lambda: calls.append("reset"))+ pet._on_right_click()+ pet._context_menu.choose("Open app")+ pet._context_menu.choose("Reset position")+ assert calls == ["open", "reset"]+ assert not pet.pet_user_hidden+++def test_repeated_right_click_replaces_the_previous_menu(pet) -> None:+ pet._on_right_click()+ previous = pet._context_menu+ pet._on_right_click()+ assert previous.destroyed+ assert pet._context_menu is not previous+ assert not pet.pet_user_hidden+++def test_hiding_pet_from_another_action_also_dismisses_its_popup(pet) -> None:+ pet._on_right_click()+ menu = pet._context_menu+ pet.set_visible(False)+ assert menu.destroyed+ assert pet.pet_user_hidden+++def test_failed_popup_releases_grab_without_hiding_pet(pet, monkeypatch, caplog) -> None:+ def fail(menu, x, y):+ raise overlay.tk.TclError("window unavailable")++ monkeypatch.setattr(_Menu, "tk_popup", fail)+ pet._on_right_click()+ assert pet._context_menu.released+ assert not pet.pet_user_hidden+ assert "Pet context menu could not be opened" in caplog.text++[email protected]("language", context_menu.LABELS)+def test_menu_reads_current_language_and_explicit_shortcut(tmp_path, language) -> None:+ config = tmp_path / "menu.toml"+ config.write_text(f'[ui]\nlanguage="{language}"\n[trigger]\nhotkey_pet_toggle="ctrl+alt+p"')+ labels, shortcut = context_menu.preferences(config)+ assert labels == context_menu.LABELS[language]+ assert shortcut == "Ctrl+Alt+P"+ config.write_text('[trigger]\nhotkey_pet_toggle=""')+ assert context_menu.preferences(config)[1] == ""diff --git a/tests/unit/ui/test_section_window_contract.py b/tests/unit/ui/test_section_window_contract.pynew file mode 100644index 0000000000..7f29acdf66--- /dev/null+++ b/tests/unit/ui/test_section_window_contract.py@@ -0,0 +1,28 @@+"""The desktop registry accepts each window offered by the frontend."""++import re+from pathlib import Path++from jarvis.ui.desktop_app import DETACHABLE_VIEWS+from jarvis.ui.section_windows import WINDOW_GROUPS++FRONTEND = Path(__file__).parents[3] / "jarvis/ui/web/frontend/src"+++def _ids(source: str, name: str) -> set[str]:+ block = re.search(rf"{name}[^=]*=\s*\[(.*?)\];", source, re.S)+ assert block, name+ return set(re.findall(r'"([a-z-]+)"', block[1]))+++def test_every_offered_section_can_open_natively():+ source = (FRONTEND / "lib/sectionWindows.ts").read_text(encoding="utf-8")+ offered = _ids(source, "DETACHABLE_SECTIONS")+ assert offered <= DETACHABLE_VIEWS.keys()+ assert "chats" not in offered+ assert "dictation" not in offered+++def test_settings_tabs_share_exactly_one_window_on_both_sides():+ source = (FRONTEND / "components/layout/navGroups.ts").read_text(encoding="utf-8")+ assert _ids(source, "SETTINGS_HUB_IDS") == set(WINDOW_GROUPS["settings"])diff --git a/tests/unit/ui/web/test_local_models_routes.py b/tests/unit/ui/web/test_local_models_routes.pyindex dbe9a77d8c..1e84b8d89c 100644--- a/tests/unit/ui/web/test_local_models_routes.py+++ b/tests/unit/ui/web/test_local_models_routes.py@@ -397,6 +397,26 @@ def test_options_without_a_bakeable_knob_have_no_alias(server, fake, option_writassert body["options"] == {"temperature": 0.2}+def test_option_save_and_reset_refresh_the_next_agent_budget(server, option_writes, monkeypatch):+ from types import SimpleNamespace++ from jarvis.agent_runtimes import gateway+ from jarvis.agent_runtimes.model_limits import ModelLimits++ refreshed = []+ server.app.state.brain = SimpleNamespace(reactivate_provider=refreshed.append)+ grant = gateway.Grant("agent", "ollama")+ monkeypatch.setattr(gateway, "_MODEL_LIMITS", {grant: {"model": ModelLimits(128_000)}})+ with TestClient(server.app) as client:+ saved = client.put(f"{BASE}/models/qwen3.5:4b/options", json={"num_ctx": 4096})+ assert saved.status_code == 200 and refreshed == ["ollama"]+ assert grant not in gateway._MODEL_LIMITS+ gateway._MODEL_LIMITS[grant] = {"model": ModelLimits(4096)}+ reset = client.delete(f"{BASE}/models/qwen3.5:4b/options")+ assert reset.status_code == 200 and refreshed == ["ollama", "ollama"]+ assert grant not in gateway._MODEL_LIMITS++def test_suggested_options_are_judged_against_this_machine(server, fake, monkeypatch) -> None:monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (16.0, "nvidia-smi"))monkeypatch.setattr(ollama_pull, "total_memory_gb", lambda: 32.0)diff --git a/tests/unit/ui/web/test_provider_base_url_routes.py b/tests/unit/ui/web/test_provider_base_url_routes.pyindex f86ba09784..759a3d066a 100644--- a/tests/unit/ui/web/test_provider_base_url_routes.py+++ b/tests/unit/ui/web/test_provider_base_url_routes.py@@ -18,11 +18,14 @@ from jarvis.ui.web.server import WebServer@pytest.fixture-def server() -> WebServer:+def server(tmp_path) -> WebServer:+ from jarvis.brain.model_catalog import ModelCatalog+cfg = JarvisConfig()cfg.ui.dev_mode = Truesrv = WebServer(cfg, bus=EventBus())srv.app.state.config = cfg+ srv.app.state.model_catalog = ModelCatalog(cache_path=tmp_path / "catalog.json")return srv@@ -62,6 +65,45 @@ def test_put_clear_resets_to_vendor_default(assert recorded_writes == [("ollama", None)]+def test_endpoint_change_releases_scoped_clients_and_old_catalog(+ server, recorded_writes, monkeypatch,+):+ import time++ from jarvis.agent_runtimes import gateway+ from jarvis.agent_runtimes.model_limits import ModelLimits+ from jarvis.brain.model_catalog import ModelInfo+ from jarvis.core.config import BrainProviderConfig+ from tests.unit.brain.test_turn_override import _manager++ brain = _manager()+ brain._config.brain.providers["ollama"] = BrainProviderConfig(base_url="http://old:11434")+ brain._brain_cache[("ollama", "model")] = object()+ brain._brain_cache[("ollama@society/test", "model")] = object()+ unrelated = object()+ brain._brain_cache[("other@society/test", "model")] = unrelated+ server.app.state.brain = brain+ catalog = server.app.state.model_catalog+ catalog._cache["ollama"] = (time.time(), [ModelInfo("old-model", "Old model")])+ catalog._fetch_failed_at["ollama"] = time.time()+ local_grant = gateway.Grant("test", "ollama")+ remote_grant = gateway.Grant("test", "openai")+ monkeypatch.setattr(gateway, "_CATALOG", object())+ monkeypatch.setattr(gateway, "_MODEL_LIMITS", {+ local_grant: {"model": ModelLimits(128_000)},+ remote_grant: {"model": ModelLimits(200_000)},+ })+ with TestClient(server.app) as client:+ response = client.put("/api/providers/ollama/base-url", json={"base_url": "http://new:11434"})+ assert response.status_code == 200+ assert brain._config.brain.providers["ollama"].base_url == "http://new:11434"+ assert not any(key[0].startswith("ollama") for key in brain._brain_cache)+ assert brain._brain_cache[("other@society/test", "model")] is unrelated+ assert "ollama" not in catalog._cache and "ollama" not in catalog._fetch_failed_at+ assert gateway._CATALOG is None and local_grant not in gateway._MODEL_LIMITS+ assert gateway._MODEL_LIMITS[remote_grant]["model"].context_window == 200_000++def test_put_rejects_non_http_scheme(server: WebServer, recorded_writes: list[tuple[str, str | None]]) -> None:diff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex fab465dd1f..82e904ce32 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -2286,6 +2286,7 @@ class OrbOverlay:# itself stays bus-agnostic (same contract as the mute toggle).self._on_show_window: Callable[[], None] | None = Noneself._on_visibility_changed: Callable[[bool], None] | None = None+ self._context_menu = None# The control row's actions. Each is optional: wired, the callback# decides (the macOS host forwards it to the parent process, which is# the only place a SpeechPipeline exists); unwired, the row falls back@@ -2566,7 +2567,7 @@ class OrbOverlay:# <B1-Motion> → drag-update (only fires while LMB held)# <ButtonRelease-1> → drag-finish (or no-op if it was a click)# <Double-Button-1> → mute toggle (fires after Button-1+Release)- # <Button-3> → raise the main desktop window (spec 2026-06-02)+ # <Button-3> → pet context menu, or raise the main window# <Button-2> → reset position (moved off the old right-click menu)# User spec 2026-05-17: double-click on the orb mutes Jarvis.# Spec 2026-06-02: right-click now opens the Jarvis window (same as the@@ -3321,10 +3322,43 @@ class OrbOverlay:self._on_show_window = callbackdef _on_right_click(self, _event: tk.Event | None = None) -> None:- """Dismiss the pet; other orb styles raise the main desktop window."""+ """Open the pet's menu; other orb styles raise the main window."""if self._style == "pet":- self.set_visible(False)+ self._show_pet_context_menu(_event)return+ self._open_main_window()++ def _show_pet_context_menu(self, event: tk.Event | None = None) -> None:+ root = self._root+ if root is None:+ return+ from jarvis.ui.pets.context_menu import preferences+ from ui.orb.pet_context_menu import PetContextMenu++ try:+ if self._context_menu is not None:+ self._context_menu.destroy()+ labels, shortcut = preferences()+ menu = PetContextMenu(root, scale=getattr(self, "_dpi_ratio", 1.0))+ self._context_menu = menu+ menu.add_command(+ label=labels[0], command=self._open_main_window,+ state="normal" if self._on_show_window is not None else "disabled",+ )+ menu.add_command(label=labels[1], command=self._on_reset_double_click)+ menu.add_separator()+ menu.add_command(+ label=labels[2], accelerator=shortcut, command=lambda: self.set_visible(False),+ )+ x, y = (event.x_root, event.y_root) if event is not None else root.winfo_pointerxy()+ try:+ menu.tk_popup(int(x), int(y))+ finally:+ menu.grab_release()+ except tk.TclError:+ logging.getLogger("jarvis.orb").exception("Pet context menu could not be opened")++ def _open_main_window(self) -> None:callback = self._on_show_windowif callback is None:return@@ -3624,6 +3658,9 @@ class OrbOverlay:def _actually_hide(self) -> None:self._pending_hide_after_id = None+ menu = getattr(self, "_context_menu", None)+ if menu is not None:+ menu.destroy()# The controls belong to the orb, not to the desktop: a row of buttons# left floating where the sphere used to be is a widget with nothing# behind it.diff --git a/ui/orb/pet_context_menu.py b/ui/orb/pet_context_menu.pynew file mode 100644index 0000000000..2dc35b7e70--- /dev/null+++ b/ui/orb/pet_context_menu.py@@ -0,0 +1,192 @@+"""A small keyboard-accessible pet popup using the app's native RGBA surface."""++from __future__ import annotations++import logging+import sys+import tkinter as tk++from PIL import Image, ImageColor++from jarvis.ui.pets.context_menu import appearance+from jarvis.ui.pets.menu_renderer import MenuEntry, hit_test, menu_size, render_menu+from jarvis.ui.theme import POPOVER_COLORS+from ui.orb.layered_surface import AlphaWindow++log = logging.getLogger(__name__)+++def popup_position(x, y, size, area):+ """Keep the complete panel on the pointer's monitor, including negative origins."""+ left, top, width, height = area+ return (+ max(left + 8, min(x, left + width - size[0] - 8)),+ max(top + 8, min(y, top + height - size[1] - 8)),+ )+++class PetContextMenu:+ def __init__(self, parent, *, scale=1.0, **_kwargs):+ self.parent = parent+ self.scale = max(0.75, min(3.0, float(scale)))+ self.entries: list[MenuEntry | None] = []+ self.commands = []+ self.surface = None+ self.selected = None+ self.keyboard = False+ self._focus_check = None+ self.theme = appearance()++ def add_command(self, *, label, command, accelerator="", state="normal"):+ index = sum(entry is not None for entry in self.entries)+ icon = ("open", "reset", "hide")[min(index, 2)]+ self.entries.append(MenuEntry(label, accelerator, state != "disabled", icon))+ self.commands.append(command)++ def add_separator(self):+ self.entries.append(None)+ self.commands.append(None)++ def tk_popup(self, x, y):+ from jarvis.platform.monitors import work_area_at++ size = menu_size(self.entries, self.scale)+ area = work_area_at(x, y) or (+ 0,+ 0,+ self.parent.winfo_screenwidth(),+ self.parent.winfo_screenheight(),+ )+ x, y = popup_position(x, y, size, area)+ self.surface = AlphaWindow(+ self.parent,+ size,+ backdrop=ImageColor.getrgb(POPOVER_COLORS[self.theme]["background"]),+ name="pet context menu",+ )+ surface = self.surface+ try:+ surface.move(x, y)+ surface.bind("<Motion>", self._motion)+ surface.bind("<Leave>", self._leave)+ surface.bind("<ButtonPress-1>", self._click)+ surface.bind("<ButtonPress-3>", lambda event: self.destroy())+ surface.bind("<KeyPress>", self._key)+ surface.top.bind("<FocusOut>", self._focus_out)+ self._paint()+ surface.show()+ surface.top.grab_set()+ surface.top.focus_force()+ surface.canvas.focus_set()+ # Tk keeps servicing its event queue while the popup owns keyboard input.+ surface.top.wait_window()+ finally:+ self.destroy()++ def _paint(self):+ if self.surface is not None:+ frame = render_menu(+ self.entries,+ self.theme,+ selected=self.selected,+ keyboard=self.keyboard,+ scale=self.scale,+ )+ if sys.platform not in ("win32", "darwin"):+ # Tk on X11/Wayland has no Windows colour key or Cocoa clear backing.+ # Opaque neutral corners are preferable to exposing the magenta key.+ backing = Image.new("RGBA", frame.size, POPOVER_COLORS[self.theme]["background"])+ backing.alpha_composite(frame)+ frame = backing+ self.surface.present(frame)++ def _hit(self, event):+ if self.surface is None or self.surface.top is None:+ return None+ top = self.surface.top+ x = (event.x_root - top.winfo_rootx()) / self.scale+ y = (event.y_root - top.winfo_rooty()) / self.scale+ return hit_test(self.entries, x, y, menu_size(self.entries)[0])++ def _motion(self, event):+ selected = self._hit(event)+ if selected != self.selected or self.keyboard:+ self.selected, self.keyboard = selected, False+ self._paint()++ def _leave(self, _event):+ self.selected = None+ self._paint()++ def _click(self, event):+ selected = self._hit(event)+ if selected is None:+ self.destroy()+ else:+ self._activate(selected)+ return "break"++ def _key(self, event):+ key = event.keysym+ if key in ("Escape", "Tab"):+ self.destroy()+ elif key in ("Return", "space") and self.selected is not None:+ self._activate(self.selected)+ elif key in ("Up", "Down", "Home", "End"):+ enabled = [+ i for i, entry in enumerate(self.entries) if entry is not None and entry.enabled+ ]+ if not enabled:+ return "break"+ if key in ("Home", "End") or self.selected not in enabled:+ self.selected = enabled[-1] if key in ("Up", "End") else enabled[0]+ else:+ self.selected = enabled[+ (enabled.index(self.selected) + (1 if key == "Down" else -1)) % len(enabled)+ ]+ self.keyboard = True+ self._paint()+ return "break"++ def _activate(self, index):+ entry = self.entries[index]+ if entry is None or not entry.enabled or self.surface is None:+ return+ command = self.commands[index]+ self.destroy()+ command()++ def _focus_out(self, _event):+ if self.surface is not None and self._focus_check is None:+ self._focus_check = self.surface.top.after_idle(self._close_if_unfocused)++ def _close_if_unfocused(self):+ self._focus_check = None+ if self.surface is None:+ return+ top = self.surface.top+ focus = top.focus_displayof()+ if focus is None or focus.winfo_toplevel() != top:+ self.destroy()++ def grab_release(self):+ if self.surface is not None and self.surface.top is not None:+ try:+ if self.surface.top.grab_current() == self.surface.top:+ self.surface.top.grab_release()+ except tk.TclError:+ log.debug("Pet popup grab already released", exc_info=True)++ def destroy(self):+ surface = self.surface+ if surface is None:+ return+ self.grab_release()+ if self._focus_check is not None:+ try:+ surface.top.after_cancel(self._focus_check)+ except tk.TclError:+ log.debug("Pet popup focus check already cancelled", exc_info=True)+ self._focus_check = None+ self.surface = None+ surface.destroy()