Skip to content

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

chore(release): publish v2.1.0 with current product changes

rubenluetke10-beep0ccd53cbd460
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8050c93fb..516c32aa4c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,73 @@ versioning per [SemVer](https://semver.org/).
---
+## [2.1.0] — 2026-09-07
+
+The Society becomes a living world: agents walk an
+island, talk to each other, learn skills, run routines, and propose changes the
+person confirms. The Agentic IDE gains a chat view for every coding session, the
+local-model surface wires Ollama end-to-end, and the UI settles into its neutral
+design-token system.
+
+### Added
+
+- **Chat tool picker.** Search and select tools, skills, plugins and connectors
+ for each message, with capability filters and provider logos.
+- **Agent Studio.** Edit agent instructions, models, appearance, permissions
+ and routines from the agent card.
+- **Internal agent messages.** Preserve sender identity and delivery status
+ when agents communicate through their chats.
+- **Agent Society island.** A 3D world where agents live, walk between
+ buildings, talk to each other, and carry out quests. Sixteen biomes at ten
+ heights, graded roads, shore-driven water, clouds, and a toon-shaded M3a
+ look.
+- **Agent card and foundry.** A model card shows each agent's profile, tools,
+ approval rules, focus, and routines. The Agent Foundry crowns the mountain —
+ creating an agent walks it out of the forge.
+- **Agent chat and tool calls.** Each agent gets its own chat surface, a
+ contained shell, file hands, and its own browser driven by browser-use out of
+ process.
+- **Agent capabilities.** Agents learn active skills from finished tasks, run
+ routines whose results arrive in chat, propose self-changes the person
+ confirms, and obey per-agent approval rules.
+- **Quest Board.** A posted job routes to one agent, forges a new one when
+ nobody fits, and reads back off the board monument in the market square.
+- **World Kit buildings.** Plugin Docks, Skill Forge, Relay Tower, Terminal
+ Cantina, and the Memory House — each built by script in Blender and wired
+ into the island with their own drawers.
+- **Shared memory.** One memory for every agent, visible on the island as the
+ Memory House building.
+- **Society composer completions.** The composer completes teammates,
+ capabilities, skills, plugins, MCP servers and tools with `@`.
+- **Agent MCP surface.** Drive the whole agent ecosystem from any MCP client.
+- **Per-client MCP credentials, quests and portable ecosystems.**
+- **Dictation on-device pass.** The final recognition pass runs on-device, out
+ of process, in front of the cloud chain.
+- **Profile rebuild.** Profile becomes the file the assistant keeps on you,
+ with a two-tab layout.
+- **Recording strip in every composer.** One visible microphone across all
+ input surfaces.
+
+### Changed
+
+- **Neutral design tokens.** The UI drops brand hue for an ink-on-paper system
+ with Inter type scale, shell redesign, visible rims, and brighter ink.
+- **App icon.** Redrawn as paper Gigi on an ink squircle.
+- **Settings cards span full width.** No more capped containers.
+- **Orbit camera.** The island can be looked at from any side, with
+ deep-linkable camera parameters.
+- **Agent subscriptions.** Agents run on CLI seats with pinned accounts and
+ model switching.
+
+### Fixed
+
+- **Socket pool exhaustion on wake (BUG-215, AP-33).** Reconnects are jittered
+ and pay a shared connect budget so N panes × M windows cannot empty the OS
+ ephemeral-port pool.
+- **Agent-chat shell calls dying on the first call.**
+- **Boot-budget guard was blind, not passing.**
+- **Agent card description editor wiping focus and approval rules.**
+
## [2.0.0] — 2026-08-29
The release that stops being one voice channel with a settings screen behind it.
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.md
index d381426860..ce46d6db2b 100644
--- a/docs/adr/0011-router-pure-dispatcher.md
+++ b/docs/adr/0011-router-pure-dispatcher.md
@@ -1324,3 +1324,36 @@ and the last board events without a model call.
- `tests/unit/plugins/tool/test_delegate_to_agent.py` (ack, unknown agent,
veto read-back, status answers, not-ready path)
- `tests/unit/society/test_scheduler.py` (the wall the tool relies on)
+
+
+## Amendment 2026-09-07 — Internal agent messages (RUB-14)
+
+`message-agent` joins `ROUTER_TOOLS` as `message_agent`. It is an internal
+communication action with risk `safe`, executed through `ToolExecutor`.
+It shares `MessageAgentTool` and the scheduler's durable delivery queue with
+`society_message_agent`; it never invokes an external mail connector or starts
+a worker directly. `delegate_to_agent` remains the assignment path.
+
+The lead tool binds its sender to the runtime's lead. Society tools bind their
+sender to their owning session. Neither schema accepts an author. Both respect
+explicit tool denial, inactive roster rows and the master kill switch.
+Delivery does not authorize the recipient's subsequent external actions.
+
+The board atomically queues new envelopes using an SQLite insertion trigger.
+The scheduler serializes draining, preserves FIFO per recipient and retries busy
+chats. Existing board history is not replayed by this migration. Chat receipts
+use `agent_message` and `agent_message_status`, preserving sender identity and
+queued/delivered/failed status through storage, API, WebSocket and both chat UIs.
+A persisted delivery receipt prevents another turn when the same event is
+replayed. Delivery means accepted by the chat, not successful task completion.
+
+Receiving turns inherit conversation provenance through task-local context;
+new conversations receive fresh traces. Replies retain the trace and parent
+event, so the scheduler's conversation cap remains effective. Lead replies go
+to the front-page Jarvis chat. Legacy `user_message` events are not relabeled.
+
+Guards: `tests/contract/test_internal_messages.py`, the router membership test,
+`tests/unit/realtime/test_internal_message_regression.py`, and the shared
+`InternalMessageBubble` tests. Voice confirmation retries share one result;
+a real microphone response captured after playback is not discarded solely
+because its transcript resembles the confirmation question.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 4c1fdc0e3d..57e63a815a 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -322,3 +322,20 @@ search. Existing native-tool OS limitations remain unchanged.
TypeScript contract, read-only plan filtering and isolated one-key fake-provider
turns. Tests run locally on Windows; physical macOS/Linux and live-provider fresh
install verification are not claimed. See [the inventory and design](chat-tool-picker.md).
+
+
+## Internal agent messaging — RUB-14 (2026-09-07)
+
+The message tool, durable SQLite queue, task-local sender provenance, and chat
+receipts use the same Python/React implementation on Windows, macOS and Linux.
+There are no native imports, GPU requirements, or provider-name gates. The
+capability boundary is an available society runtime and receiving chat service;
+unavailable services retain queued messages, while an unavailable agent model
+reports delivery failure. Initialization remains lazy and serialized.
+
+`tests/contract/test_internal_messages.py` covers receipt replay, busy-recipient
+FIFO, restart recovery, sender identity, failure projection and SQL/Python/TS
+status parity. Realtime confirmation/echo cases use fakes with no microphone
+or provider account. Native macOS execution and a fresh single-key live-provider
+run remain release validation requirements; running this portable contract on
+one operating system does not establish those results.
diff --git a/jarvis/__init__.py b/jarvis/__init__.py
index 99c2bd9ab2..90727b2f16 100644
--- a/jarvis/__init__.py
+++ b/jarvis/__init__.py
@@ -1,3 +1,3 @@
"""Personal Jarvis — a voice-driven, cross-platform meta-orchestrator."""
-__version__ = "2.0.0"
+__version__ = "2.1.0"
diff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.py
index b4f410e803..c45548a064 100644
--- a/jarvis/agent_chat/events.py
+++ b/jarvis/agent_chat/events.py
@@ -8,6 +8,8 @@ it did while it ran (``src/components/agentchat/reduce.ts``).
Kinds (``payload`` keys in brackets):
+``agent_message`` [IncomingMessage fields] — trusted internal sender, initially queued
+``agent_message_status`` [message_id, status, turn_id, error] — durable delivery receipt
``user_message`` [text] — the person's turn
``turn_started`` [turn_id, provider, model, effort, runner]
``text_delta`` [turn_id, message_id, text] — live only, never stored
diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.py
index cccf1e8d98..1fd643cb79 100644
--- a/jarvis/agent_chat/runner_api.py
+++ b/jarvis/agent_chat/runner_api.py
@@ -180,9 +180,19 @@ def messages_from_events(events: list[dict[str, Any]]) -> list[BrainMessage]:
out.append(BrainMessage(role="assistant", content=list(pending_blocks)))
pending_blocks = []
+ internal: dict[str, dict[str, Any]] = {}
for ev in events[-_HISTORY_MAX_EVENTS:]:
kind = ev.get("kind")
payload = ev.get("payload") or {}
+ if kind == "agent_message":
+ internal[str(payload.get("message_id"))] = payload
+ continue
+ if kind == "agent_message_status":
+ original = internal.pop(str(payload.get("message_id")), None)
+ if payload.get("status") == "delivered" and original is not None:
+ flush()
+ out.append(BrainMessage(role="user", content=str(original["prompt"])))
+ continue
if kind == "user_message":
flush()
text = str(payload.get("text") or "")
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 16c02603e5..9df13a95a0 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -43,6 +43,7 @@ from jarvis.agent_chat.store import (
AgentChatStore,
)
from jarvis.agent_chat.surface_kits import kit_for
+from jarvis.society.delivery import IncomingMessage
log = logging.getLogger(__name__)
@@ -293,6 +294,23 @@ class AgentChatService:
# ---------------------------------------------------------------- turns
+ async def receive_message(self, session_id: str, incoming: IncomingMessage) -> dict[str, Any]:
+ """Persist a trusted internal message even while its receiving chat is busy."""
+ if self.store.get_session(session_id) is None:
+ raise NoSuchSession(session_id)
+ existing = self.store.incoming_message(session_id, incoming.message_id)
+ if existing is not None:
+ return existing
+ await self._emit(session_id, make_event("agent_message", incoming.model_dump()))
+ return incoming.model_dump()
+
+ async def message_status(
+ self, session_id: str, message_id: str, status: str, *, turn_id: str = "", error: str = ""
+ ) -> None:
+ await self._emit(session_id, make_event("agent_message_status", {
+ "message_id": message_id, "status": status, "turn_id": turn_id, "error": error,
+ }))
+
async def send(
self,
session_id: str,
@@ -300,6 +318,7 @@ class AgentChatService:
attachments: list[dict[str, Any]] | None = None,
*,
tool_choices: list[str] | None = None,
+ incoming: IncomingMessage | None = None,
) -> str:
"""Persist the person's message and start the turn. Returns turn_id.
@@ -316,6 +335,12 @@ class AgentChatService:
session = self.store.get_session(session_id)
if session is None:
raise NoSuchSession(session_id)
+ if incoming is not None:
+ receipt = await self.receive_message(session_id, incoming)
+ if receipt["status"] == "delivered":
+ return str(receipt.get("turn_id") or "")
+ if receipt["status"] == "failed":
+ raise ValueError("This internal message already failed")
if self.is_running(session_id):
raise SessionBusy(session_id)
kit = kit_for(session.surface)
@@ -347,42 +372,47 @@ class AgentChatService:
self._running[session_id] = run
history = self.store.list_events(session_id)
- await self._emit(
- session_id,
- make_event(
- "user_message",
- {
- # The full prompt: this is what was actually sent, and the
- # API runner rebuilds the conversation from these events —
- # storing only the sentence would lose the picture on the
- # NEXT turn (runner_api.messages_from_events).
- "text": prompt,
- **(
- {"tool_choices": [row.model_dump(mode="json") for row in selected]}
- if selected
- else {}
- ),
- # What the person typed, when it differs from the prompt.
- # Absent on an ordinary message, so nothing changes there.
- **({"typed": text} if attached else {}),
- **(
- {
- "attachments": [
- {
- "name": item.name,
- "kind": item.kind,
- "described_by": item.described_by,
- "note": item.note,
- }
- for item in attached
- ]
- }
- if attached
- else {}
- ),
- },
- ),
- )
+ if incoming is not None:
+ await self.message_status(
+ session_id, incoming.message_id, "delivered", turn_id=turn_id
+ )
+ else:
+ await self._emit(
+ session_id,
+ make_event(
+ "user_message",
+ {
+ # The full prompt: this is what was actually sent, and the
+ # API runner rebuilds the conversation from these events —
+ # storing only the sentence would lose the picture on the
+ # NEXT turn (runner_api.messages_from_events).
+ "text": prompt,
+ **(
+ {"tool_choices": [row.model_dump(mode="json") for row in selected]}
+ if selected
+ else {}
+ ),
+ # What the person typed, when it differs from the prompt.
+ # Absent on an ordinary message, so nothing changes there.
+ **({"typed": text} if attached else {}),
+ **(
+ {
+ "attachments": [
+ {
+ "name": item.name,
+ "kind": item.kind,
+ "described_by": item.described_by,
+ "note": item.note,
+ }
+ for item in attached
+ ]
+ }
+ if attached
+ else {}
+ ),
+ },
+ ),
+ )
runner = resolve_runner(session.provider, surface=session.surface)
await self._emit(
session_id,
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index 362dea9f12..0a60d72908 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -322,7 +322,7 @@ class AgentChatStore:
"VALUES (?, ?, ?, ?, ?)",
(session_id, seq, ts_ms, kind, json.dumps(payload, ensure_ascii=False)),
)
- if kind == "user_message":
+ if kind in {"user_message", "agent_message"}:
text = str(payload.get("text") or "")
self._conn.execute(
"UPDATE agent_chat_sessions SET message_count = message_count + 1, "
@@ -350,6 +350,19 @@ class AgentChatStore:
out["ts_ms"] = ts_ms
return out
+ def incoming_message(self, session_id: str, message_id: str) -> dict[str, Any] | None:
+ """Fold a receipt and its status updates; old user messages stay untouched."""
+ receipt = None
+ for event in self.list_events(session_id):
+ payload = event["payload"]
+ if payload.get("message_id") != message_id:
+ continue
+ if event["kind"] == "agent_message":
+ receipt = dict(payload)
+ elif event["kind"] == "agent_message_status" and receipt is not None:
+ receipt.update(payload)
+ return receipt
+
def list_events(self, session_id: str, *, after_seq: int = 0) -> list[dict[str, Any]]:
with self._lock:
rows = self._conn.execute(
diff --git a/jarvis/agent_screen/__init__.py b/jarvis/agent_screen/__init__.py
new file mode 100644
index 0000000000..476cee0655
--- /dev/null
+++ b/jarvis/agent_screen/__init__.py
@@ -0,0 +1,50 @@
+"""Agent screens — a screen the agent owns, isolated from the user's desktop.
+
+Computer-Use drives ONE physical pointer, so a background agent using it takes
+the machine away from the user. An agent screen removes that trade: the agent
+gets its own session (a Windows Sandbox, a virtual X display) with its own
+framebuffer and its own input stream, and works there while the user keeps
+typing on theirs.
+
+Public surface:
+
+* :mod:`~jarvis.agent_screen.manager` — leases screens, one per owner.
+* :mod:`~jarvis.agent_screen.port` — the seam the Computer-Use engine
+ perceives through; ``RealScreenPort`` preserves today's behaviour exactly.
+* :mod:`~jarvis.agent_screen.tools` — action tools with the SAME names as the
+ desktop tools, so swapping the tool map redirects a whole mission.
+"""
+
+from jarvis.agent_screen.manager import (
+ AgentScreenManager,
+ ScreenSettings,
+ get_agent_screen_manager,
+ peek_agent_screen_manager,
+ set_agent_screen_manager,
+)
+from jarvis.agent_screen.port import RealScreenPort, RemoteScreenPort, resolve_port
+from jarvis.agent_screen.protocol import (
+ AgentScreenUnavailable,
+ ProbeResult,
+ ScreenLease,
+ ScreenSession,
+ ScreenSpec,
+)
+from jarvis.agent_screen.tools import screen_bound_tools
+
+__all__ = [
+ "AgentScreenManager",
+ "AgentScreenUnavailable",
+ "ProbeResult",
+ "RealScreenPort",
+ "RemoteScreenPort",
+ "ScreenLease",
+ "ScreenSession",
+ "ScreenSettings",
+ "ScreenSpec",
+ "get_agent_screen_manager",
+ "peek_agent_screen_manager",
+ "resolve_port",
+ "screen_bound_tools",
+ "set_agent_screen_manager",
+]
diff --git a/jarvis/agent_screen/manager.py b/jarvis/agent_screen/manager.py
new file mode 100644
index 0000000000..ac42029460
--- /dev/null
+++ b/jarvis/agent_screen/manager.py
@@ -0,0 +1,372 @@
+"""Allocates, reuses and reaps agent screens.
+
+The manager is the only place that decides WHICH provider runs on this host
+and HOW MANY screens may exist. Two rules shape it:
+
+* **One screen per owner, refcounted.** An errand doing ten desktop steps must
+ pay one sandbox boot, not ten. The screen dies when the last lease for that
+ owner is released, never earlier.
+* **Never silently fall back to the user's screen.** When no isolated provider
+ is available the acquisition FAILS with the provider's own reason and
+ remedy. Quietly handing back the physical desktop is the exact behaviour
+ this subsystem exists to prevent, and it is the failure mode a future
+ refactor is most likely to reintroduce.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+from dataclasses import dataclass
+from typing import Any
+
+from jarvis.agent_screen.protocol import (
+ AgentScreenUnavailable,
+ ProbeResult,
+ ScreenLease,
+ ScreenProvider,
+ ScreenSession,
+ ScreenSpec,
+)
+from jarvis.agent_screen.providers import (
+ AttachedProvider,
+ WindowsSandboxProvider,
+ XvfbProvider,
+)
+
+logger = logging.getLogger(__name__)
+
+#: Providers ``auto`` may pick, best first. ``attached`` is deliberately
+#: absent: it drives the user's real screen and must always be chosen by name.
+_AUTO_ORDER: tuple[str, ...] = ("windows-sandbox", "xvfb")
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenSettings:
+ """The knobs :mod:`jarvis.core.config` feeds in, with safe defaults."""
+
+ enabled: bool = True
+ provider: str = "auto"
+ max_screens: int = 2
+ width: int = 1280
+ height: int = 800
+ memory_mb: int = 4096
+ networking: bool = True
+ vgpu: bool = False
+
+ @classmethod
+ def from_config(cls, config: Any) -> ScreenSettings:
+ block = getattr(config, "agent_screen", None)
+ if block is None:
+ return cls()
+ return cls(
+ enabled=bool(getattr(block, "enabled", True)),
+ provider=str(getattr(block, "provider", "auto") or "auto"),
+ max_screens=max(1, int(getattr(block, "max_screens", 2) or 2)),
+ width=max(320, int(getattr(block, "width", 1280) or 1280)),
+ height=max(240, int(getattr(block, "height", 800) or 800)),
+ memory_mb=max(1024, int(getattr(block, "memory_mb", 4096) or 4096)),
+ networking=bool(getattr(block, "networking", True)),
+ vgpu=bool(getattr(block, "vgpu", False)),
+ )
+
+
+class AgentScreenManager:
+ """Process-wide owner of every live agent screen."""
+
+ def __init__(
+ self,
+ *,
+ settings: ScreenSettings | None = None,
+ bus: Any = None,
+ providers: dict[str, ScreenProvider] | None = None,
+ ) -> None:
+ self._settings = settings or ScreenSettings()
+ self._bus = bus
+ self._providers: dict[str, ScreenProvider] = providers or self._build_providers()
+ self._sessions: dict[str, ScreenSession] = {} # owner -> session
+ self._refcounts: dict[str, int] = {} # owner -> live leases
+ self._by_id: dict[str, ScreenSession] = {}
+ # Guards the maps AND serialises boots: two concurrent acquisitions
+ # for one owner must share a screen, not race two sandboxes up.
+ self._lock = asyncio.Lock()
+ self._sync_lock = threading.Lock()
+
+ def _build_providers(self) -> dict[str, ScreenProvider]:
+ return {
+ "windows-sandbox": WindowsSandboxProvider(
+ memory_mb=self._settings.memory_mb,
+ networking=self._settings.networking,
+ vgpu=self._settings.vgpu,
+ ),
+ "xvfb": XvfbProvider(),
+ "attached": AttachedProvider(),
+ }
+
+ # -- capability --------------------------------------------------------
+
+ def probe(self) -> list[ProbeResult]:
+ """Probe every provider. Never raises; used by the REST/CLI surface."""
+ results: list[ProbeResult] = []
+ for name in ("windows-sandbox", "xvfb", "attached"):
+ provider = self._providers.get(name)
+ if provider is None:
+ continue
+ try:
+ results.append(provider.probe())
+ except Exception as exc: # noqa: BLE001 — a broken probe is a "no"
+ logger.debug("[agent-screen] probe of %s failed", name, exc_info=True)
+ results.append(
+ ProbeResult(
+ kind=provider.kind,
+ available=False,
+ reason=f"probe failed: {exc}",
+ ),
+ )
+ return results
+
+ def select_provider(self) -> tuple[ScreenProvider | None, str]:
+ """``(provider, reason_when_none)`` for this host and configuration."""
+ if not self._settings.enabled:
+ return (None, "agent screens are disabled ([agent_screen].enabled = false)")
+ configured = self._settings.provider.strip().lower()
+ if configured not in ("", "auto"):
+ provider = self._providers.get(configured)
+ if provider is None:
+ return (
+ None,
+ f"[agent_screen].provider = {configured!r} is not a known "
+ f"provider (known: {', '.join(sorted(self._providers))})",
+ )
+ result = provider.probe()
+ if not result.available:
+ return (None, f"{result.reason}. {result.remedy}".strip())
+ return (provider, "")
+ reasons: list[str] = []
+ for name in _AUTO_ORDER:
+ provider = self._providers.get(name)
+ if provider is None:
+ continue
+ result = provider.probe()
+ if result.available:
+ return (provider, "")
+ if result.reason:
+ reasons.append(
+ f"{name}: {result.reason}"
+ + (f" — {result.remedy}" if result.remedy else ""),
+ )
+ return (
+ None,
+ "no isolated screen is available on this host. "
+ + " | ".join(reasons),
+ )
+
+ def available(self) -> bool:
+ provider, _reason = self.select_provider()
+ return provider is not None
+
+ def unavailable_reason(self) -> str:
+ _provider, reason = self.select_provider()
+ return reason
+
+ # -- leasing -----------------------------------------------------------
+
+ async def acquire(
+ self,
+ owner: str,
+ *,
+ purpose: str = "",
+ require_isolated: bool = True,
+ ) -> ScreenLease:
+ """Lease a screen for ``owner``, booting one only when needed."""
+ owner_key = str(owner or "").strip() or "anonymous"
+ async with self._lock:
+ existing = self._sessions.get(owner_key)
+ if existing is not None:
+ alive = await asyncio.to_thread(existing.alive)
+ if alive:
+ self._refcounts[owner_key] = self._refcounts.get(owner_key, 0) + 1
+ return ScreenLease(session=existing, owner=owner_key)
+ logger.warning(
+ "[agent-screen] %s died under owner %s — booting a fresh one",
+ existing.screen_id,
+ owner_key,
+ )
+ await self._drop_locked(owner_key, reason="died")
+
+ provider, reason = self.select_provider()
+ if provider is None:
+ raise AgentScreenUnavailable(reason)
+
+ cap = min(
+ self._settings.max_screens,
+ int(getattr(provider, "max_screens", self._settings.max_screens)),
+ )
+ if len(self._sessions) >= cap:
+ raise AgentScreenUnavailable(
+ f"all {cap} agent screens are in use on this host "
+ f"(owners: {', '.join(sorted(self._sessions))}). Wait for one "
+ "to finish, or raise [agent_screen].max_screens.",
+ )
+
+ spec = ScreenSpec(
+ owner=owner_key,
+ purpose=purpose,
+ width=self._settings.width,
+ height=self._settings.height,
+ )
+ # Booting a session is seconds of blocking work (a sandbox boots a
+ # whole Windows); it must never run on the event loop.
+ session = await asyncio.to_thread(provider.start, spec)
+ if require_isolated and not session.isolated:
+ await asyncio.to_thread(session.close)
+ raise AgentScreenUnavailable(
+ f"the {session.kind!r} screen is not isolated from the "
+ "user's session, so it must not be handed to a background "
+ "agent. Configure an isolated provider instead.",
+ )
+ self._sessions[owner_key] = session
+ self._by_id[session.screen_id] = session
+ self._refcounts[owner_key] = 1
+ await self._publish_started(session)
+ logger.info(
+ "[agent-screen] %s (%s) leased to %s%s",
+ session.screen_id,
+ session.kind,
+ owner_key,
+ "" if session.hidden else " — VISIBLE on this host",
+ )
+ return ScreenLease(session=session, owner=owner_key)
+
+ async def release(self, lease: ScreenLease) -> None:
+ """Give a lease back; the screen dies with the last one."""
+ if lease is None or lease._released: # noqa: SLF001 — the flag is the lease's own
+ return
+ lease._released = True # noqa: SLF001
+ async with self._lock:
+ remaining = self._refcounts.get(lease.owner, 0) - 1
+ if remaining > 0:
+ self._refcounts[lease.owner] = remaining
+ return
+ await self._drop_locked(lease.owner, reason="finished")
+
+ async def _drop_locked(self, owner: str, *, reason: str) -> None:
+ session = self._sessions.pop(owner, None)
+ self._refcounts.pop(owner, None)
+ if session is None:
+ return
+ self._by_id.pop(session.screen_id, None)
+ await asyncio.to_thread(session.close)
+ await self._publish_ended(session, reason)
+ logger.info("[agent-screen] %s closed (%s)", session.screen_id, reason)
+
+ async def shutdown(self) -> None:
+ """Close every screen. Safe to call more than once."""
+ async with self._lock:
+ for owner in list(self._sessions):
+ await self._drop_locked(owner, reason="shutdown")
+
+ # -- inspection --------------------------------------------------------
+
+ def get(self, screen_id: str) -> ScreenSession | None:
+ with self._sync_lock:
+ return self._by_id.get(str(screen_id))
+
+ def list_screens(self) -> list[dict[str, Any]]:
+ with self._sync_lock:
+ sessions = list(self._by_id.values())
+ refcounts = dict(self._refcounts)
+ return [
+ {
+ "screen_id": session.screen_id,
+ "kind": session.kind,
+ "owner": session.owner,
+ "purpose": session.purpose,
+ "isolated": session.isolated,
+ "hidden": session.hidden,
+ "leases": refcounts.get(session.owner, 0),
+ }
+ for session in sessions
+ ]
+
+ # -- events ------------------------------------------------------------
+
+ async def _publish_started(self, session: ScreenSession) -> None:
+ if self._bus is None:
+ return
+ try:
+ from jarvis.core.events import AgentScreenStarted # noqa: PLC0415
+
+ await self._bus.publish(
+ AgentScreenStarted(
+ screen_id=session.screen_id,
+ kind=str(session.kind),
+ owner=session.owner,
+ purpose=session.purpose,
+ hidden=session.hidden,
+ ),
+ )
+ except Exception: # noqa: BLE001 — telemetry never breaks a mission
+ logger.debug("AgentScreenStarted publish failed", exc_info=True)
+
+ async def _publish_ended(self, session: ScreenSession, reason: str) -> None:
+ if self._bus is None:
+ return
+ try:
+ from jarvis.core.events import AgentScreenEnded # noqa: PLC0415
+
+ await self._bus.publish(
+ AgentScreenEnded(screen_id=session.screen_id, reason=reason),
+ )
+ except Exception: # noqa: BLE001
+ logger.debug("AgentScreenEnded publish failed", exc_info=True)
+
+
+# ---------------------------------------------------------------------------
+# Process-wide handle
+# ---------------------------------------------------------------------------
+
+_MANAGER: AgentScreenManager | None = None
+_MANAGER_LOCK = threading.Lock()
+
+
+def set_agent_screen_manager(manager: AgentScreenManager | None) -> None:
+ """Install (or clear) the process-wide manager. Called once at boot."""
+ global _MANAGER
+ with _MANAGER_LOCK:
+ _MANAGER = manager
+
+
+def peek_agent_screen_manager() -> AgentScreenManager | None:
+ """Non-raising read — ``None`` before boot wired one."""
+ return _MANAGER
+
+
+def get_agent_screen_manager() -> AgentScreenManager:
+ """The manager, building a config-backed default if boot did not wire one.
+
+ The lazy default keeps the CLI and tests usable without a full app boot,
+ and mirrors how the Computer-Use context degrades elsewhere in the tree.
+ """
+ global _MANAGER
+ with _MANAGER_LOCK:
+ if _MANAGER is None:
+ settings = ScreenSettings()
+ try:
+ from jarvis.core.config import load_config # noqa: PLC0415
+
+ settings = ScreenSettings.from_config(load_config())
+ except Exception: # noqa: BLE001 — defaults are a valid answer
+ logger.debug("agent-screen config read failed", exc_info=True)
+ _MANAGER = AgentScreenManager(settings=settings)
+ return _MANAGER
+
+
+__all__ = [
+ "AgentScreenManager",
+ "ScreenSettings",
+ "get_agent_screen_manager",
+ "peek_agent_screen_manager",
+ "set_agent_screen_manager",
+]
diff --git a/jarvis/agent_screen/port.py b/jarvis/agent_screen/port.py
new file mode 100644
index 0000000000..348aba436d
--- /dev/null
+++ b/jarvis/agent_screen/port.py
@@ -0,0 +1,424 @@
+"""The seam the Computer-Use engine perceives and verifies through.
+
+The engine's value is its loop — stable frames, one mapper per frame, the
+idempotency ledger, effect verification, the zoom-refine rescue, the handoff
+detector, the prompt-injection defence. None of that is screen-specific, and
+none of it is duplicated here. What IS screen-specific is a short list of
+primitives: where to capture, how to capture, who is in the foreground, and
+what the accessibility layer says. Those are the port.
+
+:class:`RealScreenPort` forwards every one of them to the functions the
+engine called before this seam existed, so the physical-screen behaviour is
+unchanged by construction rather than by careful re-implementation.
+:class:`RemoteScreenPort` answers the same questions for an isolated screen.
+
+The rule this file exists to enforce: on an agent screen, NOTHING may read or
+write the user's session. Two verification paths make that easy to get wrong
+— the typed-text read-back and the click-focus hit-test both walk the local
+accessibility tree — so both are routed here explicitly. A port that forgot
+them would verify the agent's typing against the user's screen and quietly
+report nonsense.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import sys
+from pathlib import Path
+from typing import Any, Protocol
+
+from jarvis.cu.capture import (
+ Frame,
+ Grabber,
+ RawCapture,
+ VisualProbe,
+ capture_stable_frame,
+ grab_region,
+ grab_visual_probe,
+ raw_pixels,
+ select_capture_target,
+)
+from jarvis.cu.geometry import MonitorInfo
+from jarvis.cu.target_guard import ForegroundTarget
+
+logger = logging.getLogger(__name__)
+
+
+class ScreenPort(Protocol):
+ """What the Computer-Use engine needs from whatever screen it drives."""
+
+ kind: str
+ is_real: bool
+
+ def wayland_refusal(self) -> str | None: ...
+
+ def select_all_keys(self) -> list[str]: ...
+
+ def list_monitors(self) -> list[MonitorInfo]: ...
+
+ def select_capture_target(
+ self,
+ policy: str,
+ *,
+ main_monitor: str,
+ scope: str,
+ ) -> MonitorInfo: ...
+
+ def capture_stable_frame(
+ self,
+ monitor: MonitorInfo,
+ *,
+ max_dimension: int,
+ blob_dir: Path | None,
+ capture_guard: Any = None,
+ ) -> Frame: ...
+
+ def read_foreground_target(self) -> ForegroundTarget: ...
+
+ def foreground_matches_or_same_app(self, expected: tuple[Any, ...]) -> bool: ...
+
+ def foreground_title(self) -> str: ...
+
+ def normalize_foreground_window(self) -> tuple[bool, str]: ...
+
+ def grab_visual_probe(
+ self,
+ bbox: dict[str, int],
+ *,
+ point: tuple[int, int] | None = None,
+ radius: int = 110,
+ local_only: bool = False,
+ ) -> VisualProbe | None: ...
+
+ def grab_region(self, bbox: dict[str, int]) -> RawCapture | None: ...
+
+ async def ui_snapshot(
+ self,
+ *,
+ observation_guard: Any = None,
+ ) -> tuple[list[str], str, str | None, list[Any]]: ...
+
+ async def verify_typed_text(self, text: str) -> bool | None: ...
+
+ async def verify_click_focus_point(
+ self,
+ x: int,
+ y: int,
+ *,
+ capture_area: int | None = None,
+ ) -> bool | None: ...
+
+
+class RealScreenPort:
+ """The user's physical desktop — the pre-existing behaviour, verbatim."""
+
+ kind = "real"
+ is_real = True
+
+ def wayland_refusal(self) -> str | None:
+ try:
+ from jarvis.platform.probes import is_wayland # noqa: PLC0415
+
+ if is_wayland():
+ return (
+ "cannot run on a Wayland session: Wayland blocks global "
+ "screen capture and synthetic input by design. Log into an "
+ "X11 session instead (running single apps under XWayland "
+ "is not enough — the desktop session itself must be X11)."
+ )
+ except Exception: # noqa: BLE001 — an unreadable probe is not a refusal
+ logger.debug("[cu] wayland probe failed", exc_info=True)
+ return None
+ return None
+
+ def select_all_keys(self) -> list[str]:
+ return ["cmd", "a"] if sys.platform == "darwin" else ["ctrl", "a"]
+
+ def list_monitors(self) -> list[MonitorInfo]:
+ from jarvis.cu.geometry import list_monitors # noqa: PLC0415
+
+ return list_monitors()
+
+ def select_capture_target(
+ self,
+ policy: str,
+ *,
+ main_monitor: str,
+ scope: str,
+ ) -> MonitorInfo:
+ return select_capture_target(policy, main_monitor=main_monitor, scope=scope)
+
+ def capture_stable_frame(
+ self,
+ monitor: MonitorInfo,
+ *,
+ max_dimension: int,
+ blob_dir: Path | None,
+ capture_guard: Any = None,
+ ) -> Frame:
+ return capture_stable_frame(
+ monitor,
+ max_dimension=max_dimension,
+ blob_dir=blob_dir,
+ capture_guard=capture_guard,
+ )
+
+ def read_foreground_target(self) -> ForegroundTarget:
+ from jarvis.cu.target_guard import read_foreground_target # noqa: PLC0415
+
+ return read_foreground_target()
+
+ def foreground_matches_or_same_app(self, expected: tuple[Any, ...]) -> bool:
+ from jarvis.cu.target_guard import ( # noqa: PLC0415
+ foreground_matches_or_same_app,
+ )
+
+ return foreground_matches_or_same_app(expected)
+
+ def foreground_title(self) -> str:
+ try:
+ from jarvis.platform import window_state # noqa: PLC0415
+
+ return str(window_state.get_foreground_title() or "")
+ except Exception: # noqa: BLE001 — a title is decoration, never a gate
+ logger.debug("[cu] foreground title read failed", exc_info=True)
+ return ""
+
+ def normalize_foreground_window(self) -> tuple[bool, str]:
+ from jarvis.platform import window_state # noqa: PLC0415
+
+ return window_state.normalize_foreground_window()
+
+ def grab_visual_probe(
+ self,
+ bbox: dict[str, int],
+ *,
+ point: tuple[int, int] | None = None,
+ radius: int = 110,
+ local_only: bool = False,
+ ) -> VisualProbe | None:
+ return grab_visual_probe(
+ bbox,
+ point=point,
+ radius=radius,
+ local_only=local_only,
+ )
+
+ def grab_region(self, bbox: dict[str, int]) -> RawCapture | None:
+ return grab_region(bbox)
+
+ async def ui_snapshot(
+ self,
+ *,
+ observation_guard: Any = None,
+ ) -> tuple[list[str], str, str | None, list[Any]]:
+ from jarvis.cu.verify import foreground_ui_snapshot # noqa: PLC0415
+
+ return await foreground_ui_snapshot(observation_guard=observation_guard)
+
+ async def verify_typed_text(self, text: str) -> bool | None:
+ from jarvis.cu.verify import verify_typed_text # noqa: PLC0415
+
+ return await verify_typed_text(text)
+
+ async def verify_click_focus_point(
+ self,
+ x: int,
+ y: int,
+ *,
+ capture_area: int | None = None,
+ ) -> bool | None:
+ from jarvis.cu.verify import verify_click_focus_point # noqa: PLC0415
+
+ return await verify_click_focus_point(x, y, capture_area=capture_area)
+
+
+class RemoteScreenPort:
+ """An isolated agent screen, reached through its in-session runner."""
+
+ is_real = False
+
+ def __init__(self, session: Any) -> None:
+ self._session = session
+ self.kind = str(session.kind)
+
+ # -- capability --------------------------------------------------------
+
+ def wayland_refusal(self) -> str | None:
+ """Never: the screen's own session decided this before it booted.
+
+ The host may well be a Wayland desktop while the agent screen is an
+ Xvfb display or a Windows sandbox. Refusing here would block exactly
+ the configuration that solves the problem.
+ """
+ return None
+
+ def select_all_keys(self) -> list[str]:
+ """Select-all inside the SCREEN, not on the host.
+
+ A Windows sandbox is Windows and a virtual X display is Linux, whoever
+ the host happens to be — sending ``cmd+a`` from a Mac host into a
+ sandbox would simply do nothing, and the mission would blame the app.
+ """
+ return ["ctrl", "a"]
+
+ # -- geometry ----------------------------------------------------------
+
+ def _screen_monitor(self) -> MonitorInfo:
+ left, top, width, height = self._session.geometry()
+ return MonitorInfo(
+ left=left,
+ top=top,
+ width=width,
+ height=height,
+ is_primary=True,
+ name=f"agent-screen:{self._session.screen_id}",
+ )
+
+ def list_monitors(self) -> list[MonitorInfo]:
+ return [self._screen_monitor()]
+
+ def select_capture_target(
+ self,
+ policy: str,
+ *,
+ main_monitor: str,
+ scope: str,
+ ) -> MonitorInfo:
+ """Always the whole screen.
+
+ Window-scoped framing exists because a small window floating on a big
+ physical desktop shrinks to stamp size in the downscaled frame. An
+ agent screen is sized for the job (1280x800 by default), so its whole
+ framebuffer already IS the tight frame — and cropping to a window
+ would need per-window geometry the guest reports only for the
+ foreground, adding a failure mode for no grounding gain.
+ """
+ return self._screen_monitor()
+
+ # -- perception --------------------------------------------------------
+
+ def _grabber(self, *, rgb: bool = False) -> Grabber:
+ session = self._session
+
+ def grab(bbox: dict[str, int]) -> RawCapture:
+ frame = session.grab(bbox, rgb=rgb)
+ return raw_pixels(
+ frame.size,
+ frame.data,
+ pixel_format=frame.pixel_format,
+ )
+
+ return grab
+
+ def capture_stable_frame(
+ self,
+ monitor: MonitorInfo,
+ *,
+ max_dimension: int,
+ blob_dir: Path | None,
+ capture_guard: Any = None,
+ ) -> Frame:
+ return capture_stable_frame(
+ monitor,
+ max_dimension=max_dimension,
+ blob_dir=blob_dir,
+ capture_guard=capture_guard,
+ grab=self._grabber(),
+ )
+
+ def read_foreground_target(self) -> ForegroundTarget:
+ info = self._session.foreground()
+ rect = info.rect
+ return ForegroundTarget(
+ window=None,
+ rect=rect,
+ signature=info.signature(),
+ )
+
+ def foreground_matches_or_same_app(self, expected: tuple[Any, ...]) -> bool:
+ if not expected or expected[0] == "none":
+ return False
+ return self.read_foreground_target().signature == expected
+
+ def foreground_title(self) -> str:
+ return str(self._session.foreground().title or "")
+
+ def normalize_foreground_window(self) -> tuple[bool, str]:
+ """Nothing to normalise: the screen is exactly the size of the job."""
+ return (False, "agent screens are not resized")
+
+ def grab_visual_probe(
+ self,
+ bbox: dict[str, int],
+ *,
+ point: tuple[int, int] | None = None,
+ radius: int = 110,
+ local_only: bool = False,
+ ) -> VisualProbe | None:
+ # Packed RGB for the probe path: the local crop is compared BYTE for
+ # byte, and a backend's unused fourth byte must never masquerade as a
+ # visual effect.
+ return grab_visual_probe(
+ bbox,
+ point=point,
+ radius=radius,
+ local_only=local_only,
+ grab=self._grabber(rgb=True),
+ )
+
+ def grab_region(self, bbox: dict[str, int]) -> RawCapture | None:
+ # The zoom-refine crop is JPEG-encoded from a packed RGB tuple by the
+ # engine, so hand it that shape directly.
+ return grab_region(bbox, grab=self._grabber(rgb=True))
+
+ async def ui_snapshot(
+ self,
+ *,
+ observation_guard: Any = None,
+ ) -> tuple[list[str], str, str | None, list[Any]]:
+ if observation_guard is not None and not observation_guard():
+ raise RuntimeError("foreground window changed before UI-tree observation")
+ snapshot = await asyncio.to_thread(self._session.ui_snapshot)
+ if observation_guard is not None and not observation_guard():
+ raise RuntimeError("foreground window changed during UI-tree observation")
+ return snapshot
+
+ async def verify_typed_text(self, text: str) -> bool | None:
+ return await asyncio.to_thread(self._session.typed_text_landed, text)
+
+ async def verify_click_focus_point(
+ self,
+ x: int,
+ y: int,
+ *,
+ capture_area: int | None = None,
+ ) -> bool | None:
+ return await asyncio.to_thread(
+ lambda: self._session.click_landed_in_focus(
+ x,
+ y,
+ capture_area=capture_area,
+ ),
+ )
+
+
+def resolve_port(ctx: Any) -> ScreenPort:
+ """The port a Computer-Use context should drive.
+
+ Defaults to the physical screen so every existing caller, test and rig
+ keeps its exact behaviour without knowing this seam exists.
+ """
+ port = getattr(ctx, "screen_port", None)
+ if port is not None:
+ return port # type: ignore[no-any-return]
+ return RealScreenPort()
+
+
+__all__ = [
+ "RealScreenPort",
+ "RemoteScreenPort",
+ "ScreenPort",
+ "resolve_port",
+]
diff --git a/jarvis/agent_screen/protocol.py b/jarvis/agent_screen/protocol.py
new file mode 100644
index 0000000000..07866cd646
--- /dev/null
+++ b/jarvis/agent_screen/protocol.py
@@ -0,0 +1,301 @@
+"""Vocabulary for agent screens — a screen the AGENT owns, not the user's.
+
+The load-bearing insight of this whole subsystem, stated once so no later
+change can quietly violate it:
+
+ One login session has ONE visible desktop, ONE pointer and ONE input
+ stream. Synthetic input (``SendInput`` / XTest / Quartz) is injected into
+ the input stream of ITS OWN session — it cannot be aimed at a background
+ window of the SAME session. Therefore "the agent gets its own screen" can
+ only mean "the agent gets its own SESSION": a Windows Sandbox, a virtual
+ X display, a VM. It can never mean "a hidden window on this desktop".
+
+Everything here follows from that. A :class:`ScreenSession` is a session with
+a framebuffer and an input stream that Jarvis may drive without touching the
+user's desktop; a :class:`ScreenProvider` knows how to create one on this host
+and — just as importantly — how to say honestly that it cannot.
+
+Cross-platform contract (repo baseline rule): every provider is selected by a
+runtime capability probe, never by an OS allowlist in a caller. A host that
+cannot provide an invisible screen must degrade to a NAMED reason plus an
+actionable remedy, never to a silent fallback onto the user's real screen —
+silently borrowing the physical pointer is exactly the failure this subsystem
+exists to prevent.
+"""
+
+from __future__ import annotations
+
+import abc
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+#: Wire-level pixel layouts a screen may hand back. ``BGRX`` is the native
+#: layout of both mss (Windows/Linux) and GDI ``LockBits``, so it travels
+#: without a conversion pass; ``RGB`` is the packed 3-byte form the public
+#: :class:`jarvis.cu.capture.Grabber` contract uses.
+PixelFormat = Literal["RGB", "BGRX"]
+
+#: What kind of session a screen lives in. ``real`` is the user's physical
+#: desktop; every other value is an isolated session the user never sees.
+ScreenKind = Literal["real", "windows-sandbox", "xvfb", "attached"]
+
+
+class AgentScreenUnavailable(RuntimeError):
+ """No isolated screen can be created on this host.
+
+ The message is user-actionable and English (artifact rule); spoken
+ readbacks localize separately. Raised instead of falling back to the
+ user's real screen: a subagent that cannot get its own screen must stop
+ honestly, not take over the desktop the user is working on.
+ """
+
+
+@dataclass(frozen=True, slots=True)
+class ProbeResult:
+ """Whether one provider can run here, and what to do when it cannot.
+
+ ``remedy`` is deliberately a concrete instruction (a command to run, a
+ feature to enable), because "not available" without a next step is the
+ honesty failure this repo keeps fixing elsewhere.
+ """
+
+ kind: ScreenKind
+ available: bool
+ reason: str = ""
+ remedy: str = ""
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "kind": self.kind,
+ "available": self.available,
+ "reason": self.reason,
+ "remedy": self.remedy,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ScreenSpec:
+ """What a caller wants from a screen.
+
+ ``owner`` identifies the errand/mission/worker the screen belongs to, so
+ a second request from the SAME owner reuses its screen instead of booting
+ a second session (an errand that runs ten desktop steps must not pay ten
+ sandbox boots).
+ """
+
+ owner: str
+ purpose: str = ""
+ width: int = 1280
+ height: int = 800
+
+
+@dataclass(frozen=True, slots=True)
+class ForegroundInfo:
+ """The foreground window INSIDE a screen, in that screen's input units.
+
+ ``available=False`` means the screen cannot currently name its foreground
+ window. The Computer-Use engine treats that as "refuse unbound input",
+ which is the correct fail-closed behaviour on every screen kind: without a
+ window identity there is no way to prove the click lands where the model
+ looked.
+ """
+
+ available: bool
+ title: str = ""
+ app: str = ""
+ handle: int | None = None
+ rect: tuple[int, int, int, int] | None = None
+
+ def signature(self) -> tuple[Any, ...]:
+ """Identity tuple in the shape :mod:`jarvis.cu.target_guard` produces.
+
+ Keeping the SHAPE identical (``("handle", id, rect)`` /
+ ``("none",)``) means the engine's capture-to-action race checks work
+ unchanged on an agent screen — same comparison, same same-app
+ tolerance helper, no parallel implementation to drift.
+ """
+ if not self.available:
+ return ("none",)
+ if self.handle:
+ return ("handle", int(self.handle), self.rect)
+ return ("title", str(self.title or "").casefold(), self.rect)
+
+
+@dataclass(frozen=True, slots=True)
+class ActOutcome:
+ """Result of one input primitive dispatched into a screen."""
+
+ ok: bool
+ detail: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class RawFrame:
+ """Raw pixels straight out of a screen, before any downscale/encode.
+
+ Deliberately NOT a Pillow image: the Computer-Use capture pipeline
+ (stability loop, thumbnail identity, one-mapper-per-frame downscale) is
+ the valuable part and stays shared. A screen only supplies pixels.
+ """
+
+ width: int
+ height: int
+ pixel_format: PixelFormat
+ data: bytes
+
+ @property
+ def size(self) -> tuple[int, int]:
+ return (self.width, self.height)
+
+
+class ScreenSession(abc.ABC):
+ """One live isolated screen: a framebuffer plus an input stream.
+
+ Implementations must be safe to call from worker threads (the CU engine
+ reaches them through ``asyncio.to_thread``) and must never raise on a
+ merely-degraded capability — an absent accessibility tree returns empty,
+ an unreadable foreground returns ``ForegroundInfo(available=False)``.
+ Only a genuinely dead screen raises :class:`AgentScreenUnavailable`.
+ """
+
+ #: Stable id, unique per process. Used by the REST surface, the events,
+ #: and the per-screen actuation lock.
+ screen_id: str
+ kind: ScreenKind
+ #: The owner that acquired it (errand id, mission id, "user", ...).
+ owner: str = ""
+ purpose: str = ""
+ #: Whether the screen draws NOTHING on the user's display. Isolation and
+ #: invisibility are two different promises: a sandbox started through the
+ #: classic launcher is fully isolated (its input never reaches the user's
+ #: session) yet still shows a viewer window. Callers that promised the
+ #: user "you won't see it" must check this, not :attr:`isolated`.
+ hidden: bool = True
+
+ @property
+ def is_real(self) -> bool:
+ """Whether driving this screen moves the USER's physical pointer."""
+ return self.kind == "real"
+
+ @property
+ def isolated(self) -> bool:
+ """Whether the user can neither see nor feel work done here.
+
+ The gate a subagent must pass. ``attached`` is deliberately excluded
+ even though it speaks the same wire protocol: it runs a runner in the
+ user's OWN session, which makes it a faithful end-to-end test of the
+ transport and an honest local fallback, but never an invisible one.
+ """
+ return self.kind not in ("real", "attached")
+
+ @abc.abstractmethod
+ def geometry(self) -> tuple[int, int, int, int]:
+ """Screen rect ``(left, top, width, height)`` in its input units."""
+
+ @abc.abstractmethod
+ def grab(self, bbox: dict[str, int], *, rgb: bool = False) -> RawFrame:
+ """Grab a rect. ``rgb=True`` forces the packed 3-byte layout.
+
+ Callers that only compare bytes (the pre/post visual probes) ask for
+ ``rgb`` so the comparison never sees a backend's padding byte;
+ callers that feed the downscale pipeline accept the native layout and
+ save a full-desktop conversion per stability re-grab.
+ """
+
+ @abc.abstractmethod
+ def foreground(self) -> ForegroundInfo:
+ """The screen's current foreground window."""
+
+ @abc.abstractmethod
+ def act(self, action: str, params: dict[str, Any]) -> ActOutcome:
+ """Dispatch one input primitive into this screen.
+
+ The action vocabulary mirrors the Computer-Use tool names exactly
+ (``click``, ``type_text``, ``hotkey``, ``scroll``, ``drag``,
+ ``open_app``, ``switch_window``) so a screen-bound tool is a thin
+ adapter and no second grammar exists.
+ """
+
+ def typed_text_landed(self, typed: str) -> bool | None:
+ """Did ``typed`` land in a focused field? ``None`` = cannot tell.
+
+ Default ``None``: a screen without an accessibility channel must NOT
+ pretend a read-back succeeded (that would turn strict verification
+ into a rubber stamp) and must not report failure either (that would
+ fail healthy typing on a canvas app).
+ """
+ return None
+
+ def click_landed_in_focus(
+ self,
+ x: int,
+ y: int,
+ *,
+ capture_area: int | None = None,
+ ) -> bool | None:
+ """Is ``(x, y)`` inside the focused control? ``None`` = cannot tell."""
+ return None
+
+ def ui_snapshot(self) -> tuple[list[str], str, str | None, list[Any]]:
+ """``(clickable labels, field hint, handoff reason, clickable rects)``.
+
+ The empty tuple is a first-class answer: the engine self-gates back to
+ pure pixel grounding when a screen exposes no tree, which is exactly
+ what a fresh sandbox without an accessibility bridge should do.
+ """
+ return ([], "", None, [])
+
+ def alive(self) -> bool:
+ """Cheap liveness check; ``False`` once the session died."""
+ return True
+
+ @abc.abstractmethod
+ def close(self) -> None:
+ """Tear the screen down. Must be idempotent and never raise."""
+
+
+class ScreenProvider(abc.ABC):
+ """Knows how to create one kind of isolated screen on this host."""
+
+ kind: ScreenKind
+
+ @abc.abstractmethod
+ def probe(self) -> ProbeResult:
+ """Can this provider run here right now? Never raises."""
+
+ @abc.abstractmethod
+ def start(self, spec: ScreenSpec) -> ScreenSession:
+ """Boot a screen. Raises :class:`AgentScreenUnavailable` on failure."""
+
+
+@dataclass(slots=True)
+class ScreenLease:
+ """A borrowed screen plus the release handle.
+
+ Leases are refcounted per owner by :class:`~jarvis.agent_screen.manager`
+ so overlapping desktop steps of one errand share one session and the
+ screen dies exactly once, when the last lease is released.
+ """
+
+ session: ScreenSession
+ owner: str
+ _released: bool = field(default=False, repr=False)
+
+ @property
+ def screen_id(self) -> str:
+ return self.session.screen_id
+
+
+__all__ = [
+ "ActOutcome",
+ "AgentScreenUnavailable",
+ "ForegroundInfo",
+ "PixelFormat",
+ "ProbeResult",
+ "RawFrame",
+ "ScreenKind",
+ "ScreenLease",
+ "ScreenProvider",
+ "ScreenSession",
+ "ScreenSpec",
+]
diff --git a/jarvis/agent_screen/providers/__init__.py b/jarvis/agent_screen/providers/__init__.py
new file mode 100644
index 0000000000..2d96d82a8f
--- /dev/null
+++ b/jarvis/agent_screen/providers/__init__.py
@@ -0,0 +1,7 @@
+"""Screen providers, one per way of getting an isolated session on a host."""
+
+from jarvis.agent_screen.providers.attached import AttachedProvider
+from jarvis.agent_screen.providers.windows_sandbox import WindowsSandboxProvider
+from jarvis.agent_screen.providers.xvfb import XvfbProvider
+
+__all__ = ["AttachedProvider", "WindowsSandboxProvider", "XvfbProvider"]
diff --git a/jarvis/agent_screen/providers/attached.py b/jarvis/agent_screen/providers/attached.py
new file mode 100644
index 0000000000..e544106adb
--- /dev/null
+++ b/jarvis/agent_screen/providers/attached.py
@@ -0,0 +1,161 @@
+"""A runner attached to the USER's own display — the honesty provider.
+
+This one is not isolated and never pretends to be: it starts the same runner
+in the user's session and drives the same wire protocol against the real
+screen. Two jobs justify it:
+
+1. **Proof.** It exercises the entire chain — transport, framing, capture,
+ coordinate handling, verified input — on any machine, including one where
+ no isolated provider can run. A green self-test here means the only thing
+ an isolated provider still has to get right is booting its session.
+2. **Attended fallback.** Where a host genuinely cannot offer isolation
+ (macOS today, a Windows Home edition, a Linux box without Xvfb), a
+ maintainer may still want desktop automation. Making that an explicitly
+ named, explicitly non-hidden screen is more honest than silently routing a
+ subagent onto the physical pointer.
+
+``auto`` never selects it, and :attr:`ScreenSession.isolated` is ``False``, so
+a subagent cannot reach it by accident.
+"""
+
+from __future__ import annotations
+
+import logging
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+from jarvis.agent_screen.protocol import (
+ AgentScreenUnavailable,
+ ProbeResult,
+ ScreenProvider,
+ ScreenSession,
+ ScreenSpec,
+)
+from jarvis.agent_screen.providers.base import (
+ mint_token,
+ popen_detached,
+ screen_dir,
+ terminate_quietly,
+ write_token_file,
+)
+from jarvis.agent_screen.session import RemoteScreenSession
+from jarvis.agent_screen.wire import HttpTransport
+
+logger = logging.getLogger(__name__)
+
+_BOOT_TIMEOUT_S = 30.0
+_BOOT_POLL_S = 0.2
+
+
+class AttachedProvider(ScreenProvider):
+ """Runs the in-session runner against the display this process already has."""
+
+ kind = "attached"
+
+ def probe(self) -> ProbeResult:
+ try:
+ from jarvis.platform.probes import display_present, is_wayland # noqa: PLC0415
+
+ if sys.platform not in ("win32", "darwin"):
+ if is_wayland():
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason=(
+ "Wayland blocks global capture and synthetic input "
+ "by design"
+ ),
+ remedy="Log into an X11 session instead.",
+ )
+ if not display_present():
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason="this host has no display session",
+ )
+ except Exception as exc: # noqa: BLE001 — probe failure is a "no"
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason=f"display capability probe failed: {exc}",
+ )
+ return ProbeResult(kind=self.kind, available=True)
+
+ @property
+ def max_screens(self) -> int:
+ """One: there is only one physical pointer to attach to."""
+ return 1
+
+ def start(self, spec: ScreenSpec) -> ScreenSession:
+ probe = self.probe()
+ if not probe.available:
+ raise AgentScreenUnavailable(f"{probe.reason}. {probe.remedy}".strip())
+
+ screen_id = f"attached-{uuid.uuid4().hex[:8]}"
+ root = screen_dir(screen_id)
+ token = mint_token()
+ token_file = root / "token"
+ port_file = root / "port"
+ port_file.unlink(missing_ok=True)
+ write_token_file(token_file, token)
+
+ runner = popen_detached(
+ [
+ sys.executable,
+ "-m",
+ "jarvis.agent_screen.runner",
+ "--transport",
+ "http",
+ "--kind",
+ "attached",
+ "--token-file",
+ str(token_file),
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "0",
+ "--port-file",
+ str(port_file),
+ ],
+ )
+ try:
+ port = _await_port(port_file, runner)
+ session = RemoteScreenSession(
+ screen_id=screen_id,
+ kind="attached",
+ transport=HttpTransport("127.0.0.1", port, token),
+ owner=spec.owner,
+ purpose=spec.purpose,
+ # The user's own screen: never claim it is hidden.
+ hidden=False,
+ on_close=lambda: terminate_quietly(runner),
+ )
+ session.handshake(timeout_s=_BOOT_TIMEOUT_S)
+ except Exception:
+ terminate_quietly(runner)
+ raise
+ logger.info("[agent-screen] %s: attached runner on port %s", screen_id, port)
+ return session
+
+
+def _await_port(port_file: Path, runner: subprocess.Popen[bytes]) -> int:
+ deadline = time.monotonic() + _BOOT_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if runner.poll() is not None:
+ raise AgentScreenUnavailable(
+ f"the screen runner exited with code {runner.returncode} before "
+ "it was listening",
+ )
+ if port_file.exists():
+ try:
+ return int(port_file.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ logger.debug("port file not readable yet", exc_info=True)
+ time.sleep(_BOOT_POLL_S)
+ raise AgentScreenUnavailable("the screen runner never reported a listening port")
+
+
+__all__ = ["AttachedProvider"]
diff --git a/jarvis/agent_screen/providers/base.py b/jarvis/agent_screen/providers/base.py
new file mode 100644
index 0000000000..3b31e7cb0f
--- /dev/null
+++ b/jarvis/agent_screen/providers/base.py
@@ -0,0 +1,146 @@
+"""Shared plumbing for screen providers: state dirs, tokens, runner staging."""
+
+from __future__ import annotations
+
+import logging
+import os
+import secrets
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+#: Where a screen keeps its mailbox, staged runner and persistent profile.
+#: Under the user data dir (never the repo) so a packaged install and a source
+#: checkout behave identically, and never a hardcoded absolute path.
+_SCREEN_DIR_NAME = "agent_screens"
+
+
+def screens_root() -> Path:
+ from jarvis.core.paths import user_data_dir # noqa: PLC0415
+
+ return Path(user_data_dir()) / _SCREEN_DIR_NAME
+
+
+def screen_dir(screen_id: str) -> Path:
+ path = screens_root() / screen_id
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def profile_root() -> Path:
+ """The persistent slice an isolated screen keeps between boots.
+
+ A Windows Sandbox is discarded on every stop, which would log the agent
+ out of everything on every job. Mapping ONE folder back in gives the agent
+ a durable browser profile — the "digital life" half of the clone — without
+ weakening the isolation of the rest of the session.
+ """
+ path = screens_root() / "_profile"
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def mint_token() -> str:
+ """A per-boot bearer token for the runner.
+
+ ``secrets`` rather than ``uuid``: this authorises input injection into a
+ session, and a predictable value would let any local process drive the
+ agent's screen.
+ """
+ return secrets.token_urlsafe(32)
+
+
+def write_token_file(path: Path, token: str) -> None:
+ """Persist the token where only the runner will read it.
+
+ Passed as a file, never as an argv element: process listings are readable
+ by every local user on all three supported systems.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(token, encoding="utf-8")
+ if os.name != "nt":
+ try:
+ path.chmod(0o600)
+ except OSError:
+ logger.debug("could not tighten screen token permissions", exc_info=True)
+
+
+def stage_sandbox_runner(target_dir: Path) -> Path:
+ """Copy the PowerShell runner next to the screen that will use it.
+
+ Copied rather than mapped from the source tree because the guest gets a
+ read-only view of exactly this folder — mapping the whole repository into
+ a sandbox would hand an isolated session the user's entire codebase.
+ """
+ source = Path(__file__).resolve().parent.parent / "runner" / "sandbox_runner.ps1"
+ if not source.is_file():
+ raise FileNotFoundError(f"the sandbox runner is missing at {source}")
+ target_dir.mkdir(parents=True, exist_ok=True)
+ target = target_dir / source.name
+ shutil.copyfile(source, target)
+ return target
+
+
+def popen_detached(
+ argv: list[str],
+ *,
+ env: dict[str, str] | None = None,
+ cwd: Path | None = None,
+) -> subprocess.Popen[bytes]:
+ """Start a helper process without flashing a console window.
+
+ ``NO_WINDOW_CREATIONFLAGS`` on Windows and a new session on POSIX, so a
+ screen's helpers never inherit the app's terminal and never die with it in
+ a way the provider cannot control.
+ """
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415
+
+ merged = dict(os.environ)
+ if env:
+ merged.update(env)
+ merged.setdefault("PYTHONIOENCODING", "utf-8")
+ merged.setdefault("PYTHONUTF8", "1")
+ kwargs: dict[str, object] = {
+ "env": merged,
+ "stdin": subprocess.DEVNULL,
+ "stdout": subprocess.DEVNULL,
+ "stderr": subprocess.DEVNULL,
+ "close_fds": True,
+ }
+ if cwd is not None:
+ kwargs["cwd"] = str(cwd)
+ if sys.platform == "win32":
+ kwargs["creationflags"] = NO_WINDOW_CREATIONFLAGS
+ else:
+ kwargs["start_new_session"] = True
+ return subprocess.Popen(argv, **kwargs) # type: ignore[arg-type] # noqa: S603
+
+
+def terminate_quietly(process: subprocess.Popen[bytes] | None, *, timeout_s: float = 5.0) -> None:
+ """Stop a helper process, escalating once, never raising."""
+ if process is None or process.poll() is not None:
+ return
+ try:
+ process.terminate()
+ process.wait(timeout=timeout_s)
+ except Exception: # noqa: BLE001 — escalate below
+ try:
+ process.kill()
+ process.wait(timeout=timeout_s)
+ except Exception: # noqa: BLE001 — teardown must never raise
+ logger.warning("could not stop a screen helper process", exc_info=True)
+
+
+__all__ = [
+ "mint_token",
+ "popen_detached",
+ "profile_root",
+ "screen_dir",
+ "screens_root",
+ "stage_sandbox_runner",
+ "terminate_quietly",
+ "write_token_file",
+]
diff --git a/jarvis/agent_screen/providers/windows_sandbox.py b/jarvis/agent_screen/providers/windows_sandbox.py
new file mode 100644
index 0000000000..38d776bbba
--- /dev/null
+++ b/jarvis/agent_screen/providers/windows_sandbox.py
@@ -0,0 +1,331 @@
+"""Windows Sandbox as an agent screen.
+
+Windows Sandbox is a throwaway Windows session with its own desktop, its own
+input stream and its own filesystem, booted from the host image in seconds and
+discarded on stop. That makes it the right first provider on Windows: the
+agent gets a real Windows it can click, install into and browse from, while
+the user's desktop is untouched — and nothing the agent does survives unless
+we explicitly mapped a folder for it.
+
+Two things are deliberate and worth stating, because a later change will be
+tempted to undo both:
+
+* **Networking is configurable and defaults to enabled**, but the transport is
+ files in a mapped folder, so the sandbox still works with networking off.
+ The host cannot dial into the guest anyway (it is NAT'd), which is why a
+ loopback socket was never an option here.
+* **Exactly one folder is mapped writable** — the RPC mailbox and the
+ persistent browser profile. Mapping the repository or the user's home in
+ would hand a disposable session the very data the isolation exists to
+ protect.
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+from xml.sax.saxutils import escape as xml_escape
+
+from jarvis.agent_screen.protocol import (
+ AgentScreenUnavailable,
+ ProbeResult,
+ ScreenProvider,
+ ScreenSession,
+ ScreenSpec,
+)
+from jarvis.agent_screen.providers.base import (
+ mint_token,
+ popen_detached,
+ profile_root,
+ screen_dir,
+ stage_sandbox_runner,
+ terminate_quietly,
+)
+from jarvis.agent_screen.session import RemoteScreenSession
+from jarvis.agent_screen.wire import MailboxTransport
+
+logger = logging.getLogger(__name__)
+
+#: Guest-side mount points. Fixed because the LogonCommand has to name them
+#: literally and the guest is always Windows.
+_GUEST_RUNNER_DIR = r"C:\jarvis\runner"
+_GUEST_RPC_DIR = r"C:\jarvis\rpc"
+_GUEST_PROFILE_DIR = r"C:\jarvis\profile"
+
+#: A cold sandbox boots the whole Windows session before our LogonCommand
+#: runs. Measured elsewhere at 20-40 s on warm hosts; the ceiling is generous
+#: because failing a real boot as "unavailable" would be the worse error.
+_BOOT_TIMEOUT_S = 180.0
+_BOOT_POLL_S = 1.0
+
+
+def _sandbox_binaries() -> tuple[str | None, str | None]:
+ """``(wsb.exe, WindowsSandbox.exe)`` — whichever exist on this host.
+
+ ``wsb.exe`` is the newer CLI (Windows 11 24H2 era). Where it exists it is
+ preferred: it can start a sandbox by config and stop it by name, which
+ gives the provider a real lifecycle instead of "kill the window".
+ """
+ if sys.platform != "win32":
+ return (None, None)
+ system32 = Path(r"C:\Windows\System32")
+ wsb = shutil.which("wsb") or shutil.which("wsb.exe")
+ if wsb is None and (system32 / "wsb.exe").is_file():
+ wsb = str(system32 / "wsb.exe")
+ classic = shutil.which("WindowsSandbox") or shutil.which("WindowsSandbox.exe")
+ if classic is None and (system32 / "WindowsSandbox.exe").is_file():
+ classic = str(system32 / "WindowsSandbox.exe")
+ return (wsb, classic)
+
+
+class WindowsSandboxProvider(ScreenProvider):
+ """Boots a Windows Sandbox and drives it through a mapped mailbox."""
+
+ kind = "windows-sandbox"
+
+ def __init__(
+ self,
+ *,
+ memory_mb: int = 4096,
+ networking: bool = True,
+ vgpu: bool = False,
+ ) -> None:
+ self._memory_mb = max(1024, int(memory_mb))
+ self._networking = bool(networking)
+ self._vgpu = bool(vgpu)
+
+ # -- probe -------------------------------------------------------------
+
+ def probe(self) -> ProbeResult:
+ if sys.platform != "win32":
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason="Windows Sandbox exists only on Windows",
+ remedy="",
+ )
+ wsb, classic = _sandbox_binaries()
+ if wsb is None and classic is None:
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason=(
+ "the Windows Sandbox feature is not enabled on this machine "
+ "(neither wsb.exe nor WindowsSandbox.exe is present)"
+ ),
+ remedy=(
+ "Enable it once, as administrator: "
+ "Enable-WindowsOptionalFeature -Online -FeatureName "
+ "Containers-DisposableClientVM -All — then restart Windows. "
+ "It needs Windows Pro/Enterprise/Education and virtualization "
+ "enabled in the firmware."
+ ),
+ )
+ return ProbeResult(kind=self.kind, available=True)
+
+ @property
+ def max_screens(self) -> int:
+ """How many sandboxes may run at once on this host.
+
+ The classic launcher supports a single sandbox; the newer ``wsb.exe``
+ manages named instances. Reporting the truth keeps the manager from
+ promising a second screen that the host will refuse to boot.
+ """
+ wsb, _classic = _sandbox_binaries()
+ return 4 if wsb is not None else 1
+
+ # -- start -------------------------------------------------------------
+
+ def start(self, spec: ScreenSpec) -> ScreenSession:
+ probe = self.probe()
+ if not probe.available:
+ raise AgentScreenUnavailable(f"{probe.reason}. {probe.remedy}".strip())
+
+ screen_id = f"wsb-{uuid.uuid4().hex[:8]}"
+ root = screen_dir(screen_id)
+ runner_dir = root / "runner"
+ rpc_dir = root / "rpc"
+ rpc_dir.mkdir(parents=True, exist_ok=True)
+ stage_sandbox_runner(runner_dir)
+
+ token = mint_token()
+ # The guest reads its config from the mapped mailbox. The token has to
+ # be reachable from inside, so it rides the same folder — its secrecy
+ # comes from the folder being mapped into exactly one sandbox.
+ import json # noqa: PLC0415
+
+ (rpc_dir / "config.json").write_text(
+ json.dumps({"token": token, "mailbox": _GUEST_RPC_DIR}, ensure_ascii=False),
+ encoding="utf-8",
+ )
+
+ wsb_path = root / f"{screen_id}.wsb"
+ wsb_path.write_text(
+ self._render_config(runner_dir, rpc_dir, profile_root()),
+ encoding="utf-8",
+ )
+
+ managed_by_cli, process = self._launch(screen_id, wsb_path)
+
+ transport = MailboxTransport(rpc_dir, token)
+ session = RemoteScreenSession(
+ screen_id=screen_id,
+ kind="windows-sandbox",
+ transport=transport,
+ owner=spec.owner,
+ purpose=spec.purpose,
+ # The classic launcher always paints its viewer window; only the
+ # id-managed CLI path is genuinely invisible.
+ hidden=managed_by_cli,
+ on_close=lambda: self._stop(screen_id, managed_by_cli, process),
+ )
+ try:
+ self._await_boot(session, screen_id)
+ except Exception:
+ self._stop(screen_id, managed_by_cli, process)
+ raise
+ self._sweep(rpc_dir)
+ return session
+
+ def _launch(
+ self,
+ screen_id: str,
+ wsb_path: Path,
+ ) -> tuple[bool, subprocess.Popen[bytes] | None]:
+ """Start the sandbox, preferring a lifecycle we can address by id.
+
+ Only ONE ``wsb.exe`` invocation shape is used, and only when it also
+ accepts ``--id``: without an id there is no way to stop this specific
+ sandbox later, and stopping "all" of them would kill sandboxes the
+ user started for their own reasons. When that shape is unavailable the
+ provider falls back to the classic launcher, where owning the process
+ handle gives an equally precise teardown.
+
+ Returns ``(managed_by_cli, process)``.
+ """
+ wsb, classic = _sandbox_binaries()
+ if wsb is not None:
+ argv = [wsb, "start", "--config", str(wsb_path), "--id", screen_id]
+ try:
+ completed = subprocess.run( # noqa: S603 — fixed system binary
+ argv,
+ capture_output=True,
+ timeout=90,
+ check=False,
+ )
+ if completed.returncode == 0:
+ return (True, None)
+ logger.info(
+ "[agent-screen] wsb start --id rejected (rc=%s); using the "
+ "classic launcher instead: %s",
+ completed.returncode,
+ completed.stderr[:200].decode("utf-8", "replace"),
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ logger.info("[agent-screen] wsb start unusable (%s)", exc)
+ if classic is None:
+ raise AgentScreenUnavailable(
+ "Windows Sandbox is present but could not be started: the "
+ "wsb CLI rejected the start and no WindowsSandbox.exe was "
+ "found. Check that Windows Sandbox starts manually.",
+ )
+ # The classic launcher always shows its viewer window — the sandbox is
+ # isolated but not invisible on this path. Reported honestly by the
+ # manager rather than papered over.
+ return (False, popen_detached([classic, str(wsb_path)]))
+
+ @staticmethod
+ def _sweep(rpc_dir: Path) -> None:
+ """Drop answers to boot probes the host had already given up on."""
+ for stale in rpc_dir.glob("*.res.*"):
+ try:
+ stale.unlink(missing_ok=True)
+ except OSError: # noqa: PERF203 — hygiene only
+ logger.debug("could not clear a stale mailbox file", exc_info=True)
+
+ def _render_config(self, runner_dir: Path, rpc_dir: Path, profile_dir: Path) -> str:
+ """Render the .wsb XML. Host paths are escaped — they contain user text."""
+ mapped = [
+ (runner_dir, _GUEST_RUNNER_DIR, True),
+ (rpc_dir, _GUEST_RPC_DIR, False),
+ (profile_dir, _GUEST_PROFILE_DIR, False),
+ ]
+ folders = "\n".join(
+ " <MappedFolder>\n"
+ f" <HostFolder>{xml_escape(str(host))}</HostFolder>\n"
+ f" <SandboxFolder>{xml_escape(guest)}</SandboxFolder>\n"
+ f" <ReadOnly>{'true' if read_only else 'false'}</ReadOnly>\n"
+ " </MappedFolder>"
+ for host, guest, read_only in mapped
+ )
+ command = (
+ "powershell.exe -NoProfile -ExecutionPolicy Bypass -File "
+ rf"{_GUEST_RUNNER_DIR}\sandbox_runner.ps1 "
+ rf"-ConfigPath {_GUEST_RPC_DIR}\config.json"
+ )
+ return (
+ "<Configuration>\n"
+ f" <VGpu>{'Enable' if self._vgpu else 'Disable'}</VGpu>\n"
+ f" <Networking>{'Enable' if self._networking else 'Disable'}</Networking>\n"
+ f" <MemoryInMB>{self._memory_mb}</MemoryInMB>\n"
+ " <MappedFolders>\n"
+ f"{folders}\n"
+ " </MappedFolders>\n"
+ " <LogonCommand>\n"
+ f" <Command>{xml_escape(command)}</Command>\n"
+ " </LogonCommand>\n"
+ "</Configuration>\n"
+ )
+
+ def _await_boot(self, session: RemoteScreenSession, screen_id: str) -> None:
+ """Poll until the guest runner answers, or fail with a named reason."""
+ deadline = time.monotonic() + _BOOT_TIMEOUT_S
+ last_error = ""
+ while time.monotonic() < deadline:
+ try:
+ session.handshake(timeout_s=_BOOT_POLL_S)
+ except AgentScreenUnavailable:
+ raise
+ except Exception as exc: # noqa: BLE001 — the guest is still booting
+ last_error = str(exc)
+ time.sleep(_BOOT_POLL_S)
+ continue
+ logger.info("[agent-screen] %s: sandbox runner is up", screen_id)
+ return
+ raise AgentScreenUnavailable(
+ f"the Windows Sandbox screen did not come up within "
+ f"{_BOOT_TIMEOUT_S:.0f}s ({last_error or 'no answer from the runner'}). "
+ "Check that Windows Sandbox starts manually on this machine.",
+ )
+
+ def _stop(
+ self,
+ screen_id: str,
+ managed_by_cli: bool,
+ process: subprocess.Popen[bytes] | None,
+ ) -> None:
+ """Tear down exactly THIS sandbox, never any other."""
+ if managed_by_cli:
+ wsb, _classic = _sandbox_binaries()
+ if wsb is not None:
+ try:
+ subprocess.run( # noqa: S603 — fixed system binary
+ [wsb, "stop", "--id", screen_id],
+ capture_output=True,
+ timeout=60,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ logger.warning(
+ "[agent-screen] could not stop sandbox %s", screen_id,
+ exc_info=True,
+ )
+ terminate_quietly(process)
+
+
+__all__ = ["WindowsSandboxProvider"]
diff --git a/jarvis/agent_screen/providers/xvfb.py b/jarvis/agent_screen/providers/xvfb.py
new file mode 100644
index 0000000000..fb718c1c3c
--- /dev/null
+++ b/jarvis/agent_screen/providers/xvfb.py
@@ -0,0 +1,241 @@
+"""A virtual X display as an agent screen (Linux).
+
+The cheapest real isolation of the three supported systems: ``Xvfb`` is an X
+server that renders into memory instead of a monitor, so a process started
+against it has its own display, its own focus and — crucially — its own XTest
+input stream. Synthetic input there never reaches the user's session, and the
+user never sees a window.
+
+A window manager matters more here than it looks. Without one, X11 has no
+concept of a focused top-level window, so "click the button in that dialog"
+degrades badly and ``switch_window`` cannot work at all. The provider starts
+one when the host has it and says so honestly when it does not, rather than
+pretending the screen is fully featured.
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+from jarvis.agent_screen.protocol import (
+ AgentScreenUnavailable,
+ ProbeResult,
+ ScreenProvider,
+ ScreenSession,
+ ScreenSpec,
+)
+from jarvis.agent_screen.providers.base import (
+ mint_token,
+ popen_detached,
+ screen_dir,
+ terminate_quietly,
+ write_token_file,
+)
+from jarvis.agent_screen.session import RemoteScreenSession
+from jarvis.agent_screen.wire import HttpTransport
+
+logger = logging.getLogger(__name__)
+
+#: Window managers tried in order. All are tiny, none needs a session bus.
+_WINDOW_MANAGERS = ("openbox", "fluxbox", "i3", "matchbox-window-manager", "twm")
+
+_DISPLAY_RANGE = range(90, 130)
+_BOOT_TIMEOUT_S = 45.0
+_BOOT_POLL_S = 0.25
+
+#: X11's own well-known locations, fixed by the protocol — not scratch files
+#: of ours, so the usual "put temporary files somewhere private" rule does not
+#: apply. ``Xvfb :N`` refuses to start while the lock file exists, which is
+#: exactly what makes them the right liveness markers.
+_X_LOCK_TEMPLATE = "/tmp/.X{n}-lock" # noqa: S108 — X11 protocol location
+_X_SOCKET_TEMPLATE = "/tmp/.X11-unix/X{n}" # noqa: S108 — X11 protocol location
+
+
+def _free_display() -> int:
+ """Pick a display number no X server is currently using."""
+ for number in _DISPLAY_RANGE:
+ lock = Path(_X_LOCK_TEMPLATE.format(n=number))
+ socket = Path(_X_SOCKET_TEMPLATE.format(n=number))
+ if not lock.exists() and not socket.exists():
+ return number
+ raise AgentScreenUnavailable(
+ "no free X display number is available for an agent screen",
+ )
+
+
+class XvfbProvider(ScreenProvider):
+ """Runs a virtual X display plus an in-session runner."""
+
+ kind = "xvfb"
+
+ def probe(self) -> ProbeResult:
+ if not sys.platform.startswith("linux"):
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason="virtual X displays are a Linux capability",
+ )
+ if shutil.which("Xvfb") is None:
+ return ProbeResult(
+ kind=self.kind,
+ available=False,
+ reason="Xvfb is not installed",
+ remedy=(
+ "Install it: sudo apt install xvfb (Debian/Ubuntu) or "
+ "sudo dnf install xorg-x11-server-Xvfb (Fedora). For window "
+ "focus and switch_window also install a small window "
+ "manager, e.g. sudo apt install openbox."
+ ),
+ )
+ return ProbeResult(kind=self.kind, available=True)
+
+ @property
+ def max_screens(self) -> int:
+ """Virtual displays are cheap; the manager's own cap is the real limit."""
+ return len(_DISPLAY_RANGE)
+
+ def start(self, spec: ScreenSpec) -> ScreenSession:
+ probe = self.probe()
+ if not probe.available:
+ raise AgentScreenUnavailable(f"{probe.reason}. {probe.remedy}".strip())
+
+ screen_id = f"xvfb-{uuid.uuid4().hex[:8]}"
+ root = screen_dir(screen_id)
+ display_number = _free_display()
+ display = f":{display_number}"
+
+ xvfb = popen_detached(
+ [
+ "Xvfb",
+ display,
+ "-screen",
+ "0",
+ f"{max(320, spec.width)}x{max(240, spec.height)}x24",
+ "-nolisten",
+ "tcp",
+ ],
+ )
+ helpers: list[subprocess.Popen[bytes]] = []
+ runner: subprocess.Popen[bytes] | None = None
+
+ def teardown() -> None:
+ terminate_quietly(runner)
+ for helper in helpers:
+ terminate_quietly(helper)
+ terminate_quietly(xvfb)
+
+ try:
+ self._await_display(display_number, xvfb)
+ window_manager = next(
+ (name for name in _WINDOW_MANAGERS if shutil.which(name)),
+ None,
+ )
+ if window_manager is not None:
+ helpers.append(popen_detached([window_manager], env={"DISPLAY": display}))
+ else:
+ logger.warning(
+ "[agent-screen] %s has no window manager — window focus and "
+ "switch_window will be limited. Install openbox to fix.",
+ screen_id,
+ )
+
+ token = mint_token()
+ token_file = root / "token"
+ port_file = root / "port"
+ port_file.unlink(missing_ok=True)
+ write_token_file(token_file, token)
+ runner = popen_detached(
+ [
+ sys.executable,
+ "-m",
+ "jarvis.agent_screen.runner",
+ "--transport",
+ "http",
+ "--kind",
+ "xvfb",
+ "--token-file",
+ str(token_file),
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "0",
+ "--port-file",
+ str(port_file),
+ ],
+ env={"DISPLAY": display},
+ )
+ port = self._await_port(port_file, runner)
+ session = RemoteScreenSession(
+ screen_id=screen_id,
+ kind="xvfb",
+ transport=HttpTransport("127.0.0.1", port, token),
+ owner=spec.owner,
+ purpose=spec.purpose,
+ hidden=True,
+ on_close=teardown,
+ )
+ session.handshake(timeout_s=_BOOT_TIMEOUT_S)
+ except Exception:
+ teardown()
+ raise
+ logger.info(
+ "[agent-screen] %s: virtual display %s up on port %s",
+ screen_id,
+ display,
+ port,
+ )
+ return session
+
+ @staticmethod
+ def _await_display(number: int, xvfb: subprocess.Popen[bytes]) -> None:
+ socket_path = Path(_X_SOCKET_TEMPLATE.format(n=number))
+ deadline = time.monotonic() + _BOOT_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if xvfb.poll() is not None:
+ raise AgentScreenUnavailable(
+ f"Xvfb exited with code {xvfb.returncode} before the display "
+ "was ready",
+ )
+ if socket_path.exists():
+ return
+ time.sleep(_BOOT_POLL_S)
+ raise AgentScreenUnavailable(
+ f"the virtual display :{number} did not come up within "
+ f"{_BOOT_TIMEOUT_S:.0f}s",
+ )
+
+ @staticmethod
+ def _await_port(port_file: Path, runner: subprocess.Popen[bytes]) -> int:
+ """Wait for the runner to publish the port it actually bound.
+
+ The runner binds port 0 and writes back what the OS gave it. Picking a
+ port on the host instead would race any other process on the machine —
+ a class of flake worth designing out rather than retrying.
+ """
+ deadline = time.monotonic() + _BOOT_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if runner.poll() is not None:
+ raise AgentScreenUnavailable(
+ f"the screen runner exited with code {runner.returncode} "
+ "before it was listening",
+ )
+ if port_file.exists():
+ try:
+ return int(port_file.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ # The runner writes atomically, so this is a read racing
+ # the rename; the next poll sees the settled file.
+ logger.debug("port file not readable yet", exc_info=True)
+ time.sleep(_BOOT_POLL_S)
+ raise AgentScreenUnavailable(
+ "the screen runner never reported a listening port",
+ )
+
+
+__all__ = ["XvfbProvider"]
diff --git a/jarvis/agent_screen/runner/__init__.py b/jarvis/agent_screen/runner/__init__.py
new file mode 100644
index 0000000000..4989731ef4
--- /dev/null
+++ b/jarvis/agent_screen/runner/__init__.py
@@ -0,0 +1,13 @@
+"""The in-session runner: the half of an agent screen that lives INSIDE it.
+
+Capture and synthetic input only ever reach the session the calling process
+belongs to. So the host cannot drive an isolated screen directly — it starts
+a small runner in that session and speaks :mod:`jarvis.agent_screen.wire` to
+it. This package holds the Python runner (used for virtual X displays and for
+the diagnostic attached screen); the Windows Sandbox guest has no Python and
+uses the PowerShell runner shipped alongside it.
+"""
+
+from jarvis.agent_screen.runner.server import ScreenServer, serve
+
+__all__ = ["ScreenServer", "serve"]
diff --git a/jarvis/agent_screen/runner/__main__.py b/jarvis/agent_screen/runner/__main__.py
new file mode 100644
index 0000000000..d41a363c7b
--- /dev/null
+++ b/jarvis/agent_screen/runner/__main__.py
@@ -0,0 +1,10 @@
+"""``python -m jarvis.agent_screen.runner`` — start an in-session runner."""
+
+from __future__ import annotations
+
+import sys
+
+from jarvis.agent_screen.runner.server import main
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/jarvis/agent_screen/runner/sandbox_runner.ps1 b/jarvis/agent_screen/runner/sandbox_runner.ps1
new file mode 100644
index 0000000000..359f5585ab
--- /dev/null
+++ b/jarvis/agent_screen/runner/sandbox_runner.ps1
@@ -0,0 +1,514 @@
+# Personal Jarvis — in-sandbox screen runner (zero dependencies).
+#
+# A fresh Windows Sandbox guest has no Python and no package manager, and it is
+# thrown away on every stop, so anything we install would have to be installed
+# again on the next boot. This runner therefore uses only what every Windows
+# image already ships: PowerShell plus the .NET Framework that comes with it.
+#
+# It is the guest half of jarvis/agent_screen/wire.py and speaks the MAILBOX
+# transport: request/response files in a folder the host mapped in. The guest
+# sits behind the sandbox NAT, so the host cannot dial into it — and using
+# files instead means the sandbox can run with networking switched off
+# entirely, which makes an agent screen a smaller attack surface than the
+# user's own desktop rather than a larger one.
+#
+# The one ordering rule shared with the Python runner: write the binary
+# payload FIRST and the response JSON LAST, so the JSON's existence proves the
+# whole answer is on disk.
+
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory = $true)][string]$ConfigPath
+)
+
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+
+Add-Type -AssemblyName System.Drawing
+Add-Type -AssemblyName System.Windows.Forms
+
+$Native = @"
+using System;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Runtime.InteropServices;
+using System.Text;
+
+public static class JarvisScreen
+{
+ // --- input ------------------------------------------------------------
+ // The struct layout below is load-bearing. On x64 an INPUT is 40 bytes
+ // ONLY when the union declares MOUSEINPUT (the largest member); a smaller
+ // declaration makes SendInput reject every event silently, which on the
+ // host side once produced a mission that "typed" without a single
+ // character appearing. Same trap, same fix, restated here because this is
+ // a separate implementation.
+ [StructLayout(LayoutKind.Sequential)]
+ public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
+ [StructLayout(LayoutKind.Sequential)]
+ public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
+ [StructLayout(LayoutKind.Sequential)]
+ public struct HARDWAREINPUT { public uint uMsg; public ushort wParamL; public ushort wParamH; }
+ [StructLayout(LayoutKind.Explicit)]
+ public struct InputUnion
+ {
+ [FieldOffset(0)] public MOUSEINPUT mi;
+ [FieldOffset(0)] public KEYBDINPUT ki;
+ [FieldOffset(0)] public HARDWAREINPUT hi;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ public struct INPUT { public uint type; public InputUnion U; }
+
+ const uint INPUT_MOUSE = 0;
+ const uint INPUT_KEYBOARD = 1;
+ const uint MOUSEEVENTF_MOVE = 0x0001;
+ const uint MOUSEEVENTF_ABSOLUTE = 0x8000;
+ const uint MOUSEEVENTF_VIRTUALDESK = 0x4000;
+ const uint MOUSEEVENTF_WHEEL = 0x0800;
+ const uint MOUSEEVENTF_HWHEEL = 0x01000;
+ const uint KEYEVENTF_KEYUP = 0x0002;
+ const uint KEYEVENTF_UNICODE = 0x0004;
+ const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
+
+ [DllImport("user32.dll", SetLastError = true)]
+ static extern uint SendInput(uint nInputs, [In] INPUT[] pInputs, int cbSize);
+ [DllImport("user32.dll")] static extern bool GetCursorPos(out POINT p);
+ [DllImport("user32.dll")] static extern int GetSystemMetrics(int n);
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r);
+ [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
+ [DllImport("user32.dll")] static extern bool SetProcessDpiAwarenessContext(IntPtr v);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowW(string c, string w);
+ [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
+ [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd);
+ [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr lp);
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
+
+ public delegate bool EnumProc(IntPtr hWnd, IntPtr lParam);
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
+
+ const int SM_XVIRTUALSCREEN = 76, SM_YVIRTUALSCREEN = 77;
+ const int SM_CXVIRTUALSCREEN = 78, SM_CYVIRTUALSCREEN = 79;
+
+ public static void DeclareDpiAware()
+ {
+ try { if (SetProcessDpiAwarenessContext(new IntPtr(-4))) return; } catch { }
+ try { SetProcessDPIAware(); } catch { }
+ }
+
+ public static int[] VirtualScreen()
+ {
+ return new int[] {
+ GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN),
+ GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN)
+ };
+ }
+
+ public static int[] CursorPos()
+ {
+ POINT p; if (!GetCursorPos(out p)) return null;
+ return new int[] { p.X, p.Y };
+ }
+
+ static void Send(INPUT[] inputs)
+ {
+ uint sent = SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
+ if (sent != (uint)inputs.Length)
+ throw new Exception("SendInput accepted " + sent + " of " + inputs.Length + " events (error " + Marshal.GetLastWin32Error() + ")");
+ }
+
+ // Absolute positioning over the whole virtual desktop, never SetCursorPos:
+ // SetCursorPos misplaces onto monitors with a negative origin.
+ public static void MoveAbsolute(int x, int y)
+ {
+ int[] v = VirtualScreen();
+ int w = Math.Max(1, v[2] - 1), h = Math.Max(1, v[3] - 1);
+ int nx = (int)Math.Round((double)(x - v[0]) * 65535.0 / w);
+ int ny = (int)Math.Round((double)(y - v[1]) * 65535.0 / h);
+ INPUT[] input = new INPUT[1];
+ input[0].type = INPUT_MOUSE;
+ input[0].U.mi.dx = nx; input[0].U.mi.dy = ny;
+ input[0].U.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
+ Send(input);
+ }
+
+ static void ButtonFlags(string button, out uint down, out uint up)
+ {
+ switch (button)
+ {
+ case "right": down = 0x0008; up = 0x0010; break;
+ case "middle": down = 0x0020; up = 0x0040; break;
+ default: down = 0x0002; up = 0x0004; break;
+ }
+ }
+
+ public static void ClickAtCursor(string button, bool doubleClick)
+ {
+ uint d, u; ButtonFlags(button, out d, out u);
+ int n = doubleClick ? 4 : 2;
+ INPUT[] input = new INPUT[n];
+ for (int i = 0; i < n; i++)
+ {
+ input[i].type = INPUT_MOUSE;
+ input[i].U.mi.dwFlags = (i % 2 == 0) ? d : u;
+ }
+ Send(input);
+ }
+
+ public static void ButtonDown(string button) { uint d, u; ButtonFlags(button, out d, out u); INPUT[] i = new INPUT[1]; i[0].type = INPUT_MOUSE; i[0].U.mi.dwFlags = d; Send(i); }
+ public static void ButtonUp(string button) { uint d, u; ButtonFlags(button, out d, out u); INPUT[] i = new INPUT[1]; i[0].type = INPUT_MOUSE; i[0].U.mi.dwFlags = u; Send(i); }
+
+ public static void Wheel(int notches, bool horizontal)
+ {
+ INPUT[] input = new INPUT[1];
+ input[0].type = INPUT_MOUSE;
+ input[0].U.mi.mouseData = unchecked((uint)(notches * 120));
+ input[0].U.mi.dwFlags = horizontal ? MOUSEEVENTF_HWHEEL : MOUSEEVENTF_WHEEL;
+ Send(input);
+ }
+
+ // Unicode typing. A synthetic U+000A types nothing in a Windows edit
+ // control, so newline/tab/return fall back to their virtual keys.
+ public static void TypeText(string text)
+ {
+ foreach (char ch in text)
+ {
+ if (ch == '\n' || ch == '\r') { TapVk(0x0D, false); continue; }
+ if (ch == '\t') { TapVk(0x09, false); continue; }
+ INPUT[] input = new INPUT[2];
+ for (int i = 0; i < 2; i++)
+ {
+ input[i].type = INPUT_KEYBOARD;
+ input[i].U.ki.wScan = ch;
+ input[i].U.ki.dwFlags = KEYEVENTF_UNICODE | (i == 1 ? KEYEVENTF_KEYUP : 0);
+ }
+ Send(input);
+ }
+ }
+
+ public static void TapVk(ushort vk, bool extended)
+ {
+ INPUT[] input = new INPUT[2];
+ for (int i = 0; i < 2; i++)
+ {
+ input[i].type = INPUT_KEYBOARD;
+ input[i].U.ki.wVk = vk;
+ input[i].U.ki.dwFlags = (extended ? KEYEVENTF_EXTENDEDKEY : 0) | (i == 1 ? KEYEVENTF_KEYUP : 0);
+ }
+ Send(input);
+ }
+
+ public static void KeyDown(ushort vk, bool extended)
+ {
+ INPUT[] input = new INPUT[1];
+ input[0].type = INPUT_KEYBOARD; input[0].U.ki.wVk = vk;
+ input[0].U.ki.dwFlags = extended ? KEYEVENTF_EXTENDEDKEY : 0;
+ Send(input);
+ }
+
+ public static void KeyUp(ushort vk, bool extended)
+ {
+ INPUT[] input = new INPUT[1];
+ input[0].type = INPUT_KEYBOARD; input[0].U.ki.wVk = vk;
+ input[0].U.ki.dwFlags = (extended ? KEYEVENTF_EXTENDEDKEY : 0) | KEYEVENTF_KEYUP;
+ Send(input);
+ }
+
+ // --- perception -------------------------------------------------------
+
+ public static object[] Foreground()
+ {
+ IntPtr h = GetForegroundWindow();
+ if (h == IntPtr.Zero) return null;
+ StringBuilder sb = new StringBuilder(512);
+ GetWindowTextW(h, sb, sb.Capacity);
+ RECT r;
+ if (!GetWindowRect(h, out r)) return null;
+ return new object[] { h.ToInt64(), sb.ToString(), r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top };
+ }
+
+ public static bool FocusWindowByTitle(string needle)
+ {
+ IntPtr found = IntPtr.Zero;
+ string lower = needle.ToLowerInvariant();
+ EnumWindows(delegate (IntPtr hWnd, IntPtr lp)
+ {
+ if (!IsWindowVisible(hWnd)) return true;
+ StringBuilder sb = new StringBuilder(512);
+ GetWindowTextW(hWnd, sb, sb.Capacity);
+ string title = sb.ToString();
+ if (title.Length > 0 && title.ToLowerInvariant().Contains(lower)) { found = hWnd; return false; }
+ return true;
+ }, IntPtr.Zero);
+ if (found == IntPtr.Zero) return false;
+ ShowWindow(found, 9); // SW_RESTORE
+ return SetForegroundWindow(found);
+ }
+
+ // Capture straight into the BGRX layout the host's decoder expects, so no
+ // conversion pass happens anywhere in the chain.
+ public static byte[] Grab(int left, int top, int width, int height, bool asRgb, out int outW, out int outH)
+ {
+ outW = width; outH = height;
+ using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppRgb))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.CopyFromScreen(left, top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
+ }
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
+ try
+ {
+ int rowBytes = width * 4;
+ byte[] raw = new byte[rowBytes * height];
+ for (int y = 0; y < height; y++)
+ {
+ IntPtr rowStart = new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride);
+ Marshal.Copy(rowStart, raw, y * rowBytes, rowBytes);
+ }
+ if (!asRgb) return raw;
+ byte[] rgb = new byte[width * height * 3];
+ for (int i = 0, j = 0; i < raw.Length; i += 4, j += 3)
+ {
+ rgb[j] = raw[i + 2]; rgb[j + 1] = raw[i + 1]; rgb[j + 2] = raw[i];
+ }
+ return rgb;
+ }
+ finally { bmp.UnlockBits(data); }
+ }
+ }
+}
+"@
+
+Add-Type -TypeDefinition $Native -ReferencedAssemblies System.Drawing, System.Windows.Forms
+
+[JarvisScreen]::DeclareDpiAware()
+
+$config = Get-Content -LiteralPath $ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
+$token = [string]$config.token
+$mailbox = [string]$config.mailbox
+$protocolVersion = 1
+$landingTolerance = 2
+
+if (-not (Test-Path -LiteralPath $mailbox)) { New-Item -ItemType Directory -Path $mailbox -Force | Out-Null }
+
+# Virtual-key names shared with the host vocabulary (jarvis/cu/actuate/base.py).
+$VkMap = @{
+ 'ctrl' = 0x11; 'control' = 0x11; 'shift' = 0x10; 'alt' = 0x12; 'menu' = 0x12; 'option' = 0x12
+ 'win' = 0x5B; 'windows' = 0x5B; 'lwin' = 0x5B; 'rwin' = 0x5C; 'cmd' = 0x5B; 'command' = 0x5B
+ 'meta' = 0x5B; 'super' = 0x5B
+ 'esc' = 0x1B; 'escape' = 0x1B; 'enter' = 0x0D; 'return' = 0x0D; 'tab' = 0x09
+ 'space' = 0x20; 'spacebar' = 0x20; 'backspace' = 0x08; 'back' = 0x08
+ 'delete' = 0x2E; 'del' = 0x2E; 'insert' = 0x2D; 'ins' = 0x2D
+ 'home' = 0x24; 'end' = 0x23; 'pageup' = 0x21; 'pgup' = 0x21; 'pagedown' = 0x22; 'pgdn' = 0x22
+ 'left' = 0x25; 'up' = 0x26; 'right' = 0x27; 'down' = 0x28; 'capslock' = 0x14
+ 'multiply' = 0x6A; 'add' = 0x6B; 'subtract' = 0x6D; 'decimal' = 0x6E; 'divide' = 0x6F
+}
+1..12 | ForEach-Object { $VkMap["f$_"] = 0x6F + $_ }
+0..9 | ForEach-Object { $VkMap["numpad$_"] = 0x60 + $_ }
+# Keys the OS only routes correctly with the extended-key flag set.
+$ExtendedKeys = @('insert', 'ins', 'delete', 'del', 'home', 'end', 'pageup', 'pgup',
+ 'pagedown', 'pgdn', 'left', 'up', 'right', 'down', 'divide', 'rwin')
+
+function Resolve-Vk {
+ param([string]$Name)
+ $key = $Name.ToLowerInvariant()
+ if ($VkMap.ContainsKey($key)) { return [int]$VkMap[$key] }
+ if ($key.Length -eq 1) {
+ $ch = [char]::ToUpperInvariant($key[0])
+ if (($ch -ge 'A' -and $ch -le 'Z') -or ($ch -ge '0' -and $ch -le '9')) { return [int][byte][char]$ch }
+ }
+ throw "unknown key name '$Name'"
+}
+
+function Test-Extended { param([string]$Name) return $ExtendedKeys -contains $Name.ToLowerInvariant() }
+
+# Position, read back, and refuse to press when the cursor did not land:
+# the host contract is that a silent miss is worse than a loud failure.
+function Invoke-VerifiedMove {
+ param([int]$X, [int]$Y)
+ for ($attempt = 0; $attempt -lt 2; $attempt++) {
+ [JarvisScreen]::MoveAbsolute($X, $Y)
+ Start-Sleep -Milliseconds 20
+ $pos = [JarvisScreen]::CursorPos()
+ if ($null -eq $pos) { continue }
+ if ([Math]::Abs($pos[0] - $X) -le $landingTolerance -and [Math]::Abs($pos[1] - $Y) -le $landingTolerance) { return }
+ }
+ throw "cursor did not land on ($X,$Y) — refusing to press a button"
+}
+
+function Invoke-ScreenAction {
+ param([string]$Action, $Params)
+ switch ($Action) {
+ 'click' {
+ Invoke-VerifiedMove -X ([int]$Params.x) -Y ([int]$Params.y)
+ $button = 'left'; if ($Params.PSObject.Properties.Name -contains 'button' -and $Params.button) { $button = [string]$Params.button }
+ $double = $false; if ($Params.PSObject.Properties.Name -contains 'double') { $double = [bool]$Params.double }
+ [JarvisScreen]::ClickAtCursor($button, $double)
+ return "click at ($($Params.x),$($Params.y))"
+ }
+ 'drag' {
+ Invoke-VerifiedMove -X ([int]$Params.x1) -Y ([int]$Params.y1)
+ [JarvisScreen]::ButtonDown('left')
+ $steps = 12
+ for ($i = 1; $i -le $steps; $i++) {
+ $ix = [int]([int]$Params.x1 + (([int]$Params.x2 - [int]$Params.x1) * $i / $steps))
+ $iy = [int]([int]$Params.y1 + (([int]$Params.y2 - [int]$Params.y1) * $i / $steps))
+ [JarvisScreen]::MoveAbsolute($ix, $iy)
+ Start-Sleep -Milliseconds 15
+ }
+ [JarvisScreen]::ButtonUp('left')
+ return 'drag'
+ }
+ 'type_text' {
+ [JarvisScreen]::TypeText([string]$Params.text)
+ return "typed"
+ }
+ 'hotkey' {
+ $names = @($Params.keys | ForEach-Object { [string]$_ })
+ if ($names.Count -eq 0) { throw 'hotkey needs at least one key' }
+ $vks = @(); $ext = @()
+ foreach ($n in $names) { $vks += (Resolve-Vk -Name $n); $ext += (Test-Extended -Name $n) }
+ for ($i = 0; $i -lt $vks.Count; $i++) { [JarvisScreen]::KeyDown([uint16]$vks[$i], [bool]$ext[$i]) }
+ for ($i = $vks.Count - 1; $i -ge 0; $i--) { [JarvisScreen]::KeyUp([uint16]$vks[$i], [bool]$ext[$i]) }
+ return "key $($names -join '+')"
+ }
+ 'scroll' {
+ if ($Params.PSObject.Properties.Name -contains 'x' -and $null -ne $Params.x) {
+ Invoke-VerifiedMove -X ([int]$Params.x) -Y ([int]$Params.y)
+ }
+ $direction = [string]$Params.direction
+ $amount = 3; if ($Params.PSObject.Properties.Name -contains 'amount') { $amount = [int]$Params.amount }
+ switch ($direction) {
+ 'up' { [JarvisScreen]::Wheel($amount, $false) }
+ 'down' { [JarvisScreen]::Wheel(-$amount, $false) }
+ 'right' { [JarvisScreen]::Wheel($amount, $true) }
+ 'left' { [JarvisScreen]::Wheel(-$amount, $true) }
+ default { throw "unknown scroll direction '$direction'" }
+ }
+ return "scroll $direction x$amount"
+ }
+ 'switch_window' {
+ $needle = [string]$Params.title_contains
+ if (-not [JarvisScreen]::FocusWindowByTitle($needle)) { throw "no window matching '$needle'" }
+ return "focused '$needle'"
+ }
+ 'open_app' {
+ $name = [string]$Params.app_name
+ if ([string]::IsNullOrWhiteSpace($name)) { throw 'open_app needs an app name' }
+ if ([JarvisScreen]::FocusWindowByTitle($name)) { return "focused $name" }
+ Start-Process -FilePath $name -ErrorAction Stop | Out-Null
+ $deadline = (Get-Date).AddSeconds(8)
+ while ((Get-Date) -lt $deadline) {
+ if ([JarvisScreen]::FocusWindowByTitle($name)) { return "launched $name" }
+ Start-Sleep -Milliseconds 150
+ }
+ return "launched $name (no window yet)"
+ }
+ default { throw "unknown screen action '$Action'" }
+ }
+}
+
+function Write-Atomic {
+ param([string]$Path, [byte[]]$Bytes)
+ $tmp = "$Path.part"
+ [System.IO.File]::WriteAllBytes($tmp, $Bytes)
+ if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force }
+ [System.IO.File]::Move($tmp, $Path)
+}
+
+function Write-Response {
+ param([string]$Seq, $Envelope, [byte[]]$Blob)
+ if ($null -ne $Blob -and $Blob.Length -gt 0) {
+ Write-Atomic -Path (Join-Path $mailbox "$Seq.res.bin") -Bytes $Blob
+ }
+ $json = ($Envelope | ConvertTo-Json -Depth 6 -Compress)
+ Write-Atomic -Path (Join-Path $mailbox "$Seq.res.json") -Bytes ([System.Text.Encoding]::UTF8.GetBytes($json))
+}
+
+$running = $true
+Write-Host "[jarvis-screen] runner up, mailbox $mailbox"
+
+while ($running) {
+ $requests = @(Get-ChildItem -LiteralPath $mailbox -Filter '*.req.json' -ErrorAction SilentlyContinue | Sort-Object Name)
+ if ($requests.Count -eq 0) { Start-Sleep -Milliseconds 15; continue }
+
+ foreach ($file in $requests) {
+ $seq = $file.Name.Substring(0, $file.Name.Length - '.req.json'.Length)
+ $envelope = $null
+ $blob = $null
+ try {
+ $request = Get-Content -LiteralPath $file.FullName -Raw -Encoding UTF8 | ConvertFrom-Json
+ }
+ catch {
+ # A torn read of a file the host is still replacing — the next poll
+ # sees the settled version.
+ continue
+ }
+ try {
+ if ([string]$request.token -ne $token) {
+ $envelope = @{ ok = $false; error = 'bad token' }
+ }
+ else {
+ $method = [string]$request.method
+ $p = $request.params
+ switch ($method) {
+ 'health' { $envelope = @{ ok = $true; v = $protocolVersion; kind = 'windows-sandbox' } }
+ 'geometry' {
+ $v = [JarvisScreen]::VirtualScreen()
+ $envelope = @{ ok = $true; left = $v[0]; top = $v[1]; width = $v[2]; height = $v[3] }
+ }
+ 'grab' {
+ $w = 0; $h = 0
+ $asRgb = $false
+ if ($p.PSObject.Properties.Name -contains 'rgb') { $asRgb = [bool]$p.rgb }
+ $blob = [JarvisScreen]::Grab([int]$p.left, [int]$p.top, [int]$p.width, [int]$p.height, $asRgb, [ref]$w, [ref]$h)
+ $envelope = @{ ok = $true; binary = $true; width = $w; height = $h; format = $(if ($asRgb) { 'RGB' } else { 'BGRX' }) }
+ }
+ 'foreground' {
+ $fg = [JarvisScreen]::Foreground()
+ if ($null -eq $fg) { $envelope = @{ ok = $true; available = $false } }
+ else {
+ $envelope = @{ ok = $true; available = $true; handle = $fg[0]; title = $fg[1]; app = ''
+ rect = @($fg[2], $fg[3], $fg[4], $fg[5])
+ }
+ }
+ }
+ # A fresh sandbox exposes no accessibility bridge we can
+ # trust, and claiming otherwise would turn the host's
+ # strict verification into a rubber stamp. Answering
+ # "unsupported" makes the host ground on pixels, which is
+ # both honest and correct here.
+ 'ui_snapshot' { $envelope = @{ ok = $true; supported = $false } }
+ 'typed_text_landed' { $envelope = @{ ok = $true; landed = $null } }
+ 'click_landed_in_focus' { $envelope = @{ ok = $true; focused = $null } }
+ 'act' {
+ try {
+ $detail = Invoke-ScreenAction -Action ([string]$p.action) -Params $p.params
+ $envelope = @{ ok = $true; detail = $detail }
+ }
+ catch {
+ $envelope = @{ ok = $false; error = $_.Exception.Message }
+ }
+ }
+ 'quit' { $envelope = @{ ok = $true }; $running = $false }
+ default { $envelope = @{ ok = $false; error = "unknown method '$method'" } }
+ }
+ }
+ }
+ catch {
+ $envelope = @{ ok = $false; error = $_.Exception.Message }
+ }
+ try {
+ Write-Response -Seq $seq -Envelope $envelope -Blob $blob
+ Remove-Item -LiteralPath $file.FullName -Force -ErrorAction SilentlyContinue
+ }
+ catch {
+ Write-Host "[jarvis-screen] could not answer ${seq}: $($_.Exception.Message)"
+ }
+ }
+}
+
+Write-Host '[jarvis-screen] runner stopped'
diff --git a/jarvis/agent_screen/runner/server.py b/jarvis/agent_screen/runner/server.py
new file mode 100644
index 0000000000..7b50211502
--- /dev/null
+++ b/jarvis/agent_screen/runner/server.py
@@ -0,0 +1,600 @@
+"""Verb handling for the in-session runner, plus both server loops.
+
+The runner deliberately reuses the production actuation and window layers
+(``jarvis.cu.actuate``, ``jarvis.platform.window_state``) rather than
+re-implementing input. Those backends inject into the input stream of the
+process's OWN session — which is precisely why running them here, inside the
+isolated session, produces invisible-to-the-user control while the identical
+code on the host would grab the user's pointer. The isolation comes from
+WHERE the code runs, not from a different code path.
+
+Security posture: the runner answers only on loopback (HTTP transport) or
+through a directory the host explicitly mapped (mailbox transport), and every
+request must carry the token minted by the host at boot. The token lives in a
+file rather than argv so it never appears in a process listing.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+from jarvis.agent_screen.wire import (
+ BIN_SUFFIX,
+ HEADER_FORMAT,
+ HEADER_HEIGHT,
+ HEADER_TOKEN,
+ HEADER_WIDTH,
+ MAILBOX_POLL_S,
+ PROTOCOL_VERSION,
+ REQ_SUFFIX,
+ RES_SUFFIX,
+ write_atomic,
+)
+
+logger = logging.getLogger(__name__)
+
+#: Wheel notches per scroll unit, matching the host tools' vocabulary.
+_SCROLL_UNIT = 1
+
+
+class ScreenServer:
+ """Executes the wire verbs against the session this process runs in."""
+
+ def __init__(self, *, kind: str = "xvfb") -> None:
+ self.kind = kind
+ self._stop = threading.Event()
+ self._geometry: tuple[int, int, int, int] | None = None
+ # One actuator for the process: building it constructs keycode tables,
+ # and the host-side backends already treat it as process-wide state.
+ self._actuator: Any = None
+ self._actuator_error: str = ""
+
+ # -- helpers -----------------------------------------------------------
+
+ @property
+ def stopped(self) -> threading.Event:
+ return self._stop
+
+ def _get_actuator(self) -> Any:
+ if self._actuator is None and not self._actuator_error:
+ try:
+ from jarvis.cu.actuate import get_actuator # noqa: PLC0415
+
+ self._actuator = get_actuator()
+ except Exception as exc: # noqa: BLE001 — reported per action
+ self._actuator_error = str(exc)
+ if self._actuator is None:
+ raise RuntimeError(
+ self._actuator_error or "no input backend is available in this screen",
+ )
+ return self._actuator
+
+ def _screen_rect(self) -> tuple[int, int, int, int]:
+ if self._geometry is not None:
+ return self._geometry
+ import mss # noqa: PLC0415
+
+ with mss.mss() as sct:
+ monitors = sct.monitors
+ if not monitors:
+ raise RuntimeError("this screen has no framebuffer")
+ # ``monitors[0]`` is the union of all displays; an isolated screen
+ # has exactly one, so the union IS the screen and stays correct
+ # even for an X display configured with several virtual heads.
+ box = monitors[0]
+ self._geometry = (
+ int(box["left"]),
+ int(box["top"]),
+ int(box["width"]),
+ int(box["height"]),
+ )
+ return self._geometry
+
+ # -- verbs -------------------------------------------------------------
+
+ def health(self, _params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ return ({"ok": True, "v": PROTOCOL_VERSION, "kind": self.kind}, b"")
+
+ def geometry(self, _params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ left, top, width, height = self._screen_rect()
+ return (
+ {"ok": True, "left": left, "top": top, "width": width, "height": height},
+ b"",
+ )
+
+ def grab(self, params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ import mss # noqa: PLC0415
+
+ bbox = {
+ "left": int(params.get("left", 0)),
+ "top": int(params.get("top", 0)),
+ "width": max(1, int(params.get("width", 1))),
+ "height": max(1, int(params.get("height", 1))),
+ }
+ want_rgb = bool(params.get("rgb", False))
+ with mss.mss() as sct:
+ shot = sct.grab(bbox)
+ if want_rgb:
+ data = bytes(shot.rgb)
+ pixel_format = "RGB"
+ else:
+ # ``shot.raw`` is the backend's native BGRX buffer. Handing it over
+ # untouched saves a full-desktop conversion on every stability
+ # re-grab; the host's Pillow decode understands the layout.
+ data = bytes(shot.raw)
+ pixel_format = "BGRX"
+ return (
+ {
+ "ok": True,
+ "binary": True,
+ "width": int(shot.size[0]),
+ "height": int(shot.size[1]),
+ "format": pixel_format,
+ },
+ data,
+ )
+
+ def foreground(self, _params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ try:
+ from jarvis.platform import window_state # noqa: PLC0415
+
+ window = window_state.foreground_window()
+ if window is None:
+ return ({"ok": True, "available": False}, b"")
+ rect = window_state.window_frame_rect(window)
+ except Exception: # noqa: BLE001 — an unreadable foreground is a
+ # first-class answer, not a crash: the host fails closed on it.
+ logger.debug("[screen-runner] foreground read failed", exc_info=True)
+ return ({"ok": True, "available": False}, b"")
+ handle = getattr(window, "handle", None)
+ return (
+ {
+ "ok": True,
+ "available": True,
+ "title": str(getattr(window, "title", "") or ""),
+ "app": str(getattr(window, "process_name", "") or ""),
+ "handle": int(handle) if handle else None,
+ "rect": list(rect) if rect else None,
+ },
+ b"",
+ )
+
+ def ui_snapshot(self, _params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ """Accessibility labels from inside the screen, when it has a bridge.
+
+ A fresh Windows Sandbox or a bare X display usually has none, and the
+ honest ``supported: false`` makes the host ground on pixels alone
+ instead of pretending the screen has no buttons.
+ """
+ try:
+ from jarvis.vision.tree_factory import make_ui_tree_source # noqa: PLC0415
+
+ source = make_ui_tree_source()
+ if type(source).__name__ == "NullUITreeSource":
+ return ({"ok": True, "supported": False}, b"")
+ import asyncio # noqa: PLC0415
+
+ from jarvis.cu.verify import ( # noqa: PLC0415
+ clickable_labels,
+ clickable_rects,
+ field_values_hint,
+ human_handoff_reason,
+ )
+
+ observation = asyncio.run(source.observe())
+ nodes = tuple(getattr(observation, "nodes", ()) or ())
+ except Exception: # noqa: BLE001 — best-effort enumeration
+ logger.debug("[screen-runner] ui snapshot failed", exc_info=True)
+ return ({"ok": True, "supported": False}, b"")
+ return (
+ {
+ "ok": True,
+ "supported": True,
+ "labels": clickable_labels(nodes),
+ "field_hint": field_values_hint(nodes),
+ "handoff": human_handoff_reason(nodes),
+ "clickables": [
+ [name, role, list(bounds)] for name, role, bounds in clickable_rects(nodes)
+ ],
+ },
+ b"",
+ )
+
+ def typed_text_landed(self, params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ try:
+ import asyncio # noqa: PLC0415
+
+ from jarvis.cu.verify import typed_text_landed # noqa: PLC0415
+ from jarvis.vision.tree_factory import make_ui_tree_source # noqa: PLC0415
+
+ source = make_ui_tree_source()
+ if type(source).__name__ == "NullUITreeSource":
+ return ({"ok": True, "landed": None}, b"")
+ observation = asyncio.run(source.observe())
+ nodes = tuple(getattr(observation, "nodes", ()) or ())
+ verdict = typed_text_landed(nodes, str(params.get("text", "")))
+ except Exception: # noqa: BLE001
+ logger.debug("[screen-runner] type read-back failed", exc_info=True)
+ return ({"ok": True, "landed": None}, b"")
+ return ({"ok": True, "landed": verdict}, b"")
+
+ def click_landed_in_focus(
+ self,
+ params: dict[str, Any],
+ ) -> tuple[dict[str, Any], bytes]:
+ try:
+ import asyncio # noqa: PLC0415
+
+ from jarvis.cu.verify import verify_click_focus_point # noqa: PLC0415
+
+ area = int(params.get("capture_area", 0) or 0)
+ verdict = asyncio.run(
+ verify_click_focus_point(
+ int(params.get("x", 0)),
+ int(params.get("y", 0)),
+ capture_area=area or None,
+ ),
+ )
+ except Exception: # noqa: BLE001
+ logger.debug("[screen-runner] focus hit-test failed", exc_info=True)
+ return ({"ok": True, "focused": None}, b"")
+ return ({"ok": True, "focused": verdict}, b"")
+
+ def act(self, params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ action = str(params.get("action", ""))
+ args = dict(params.get("params") or {})
+ try:
+ detail = self._dispatch_action(action, args)
+ except Exception as exc: # noqa: BLE001 — every failure is reported to
+ # the host as a failed ACTION, never as a transport error: the
+ # engine's verify/retry ladder is built to consume exactly that.
+ logger.debug("[screen-runner] action %s failed", action, exc_info=True)
+ return ({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, b"")
+ return ({"ok": True, "detail": detail}, b"")
+
+ def _dispatch_action(self, action: str, args: dict[str, Any]) -> str:
+ from jarvis.cu.actuate import ( # noqa: PLC0415
+ verified_click,
+ verified_drag,
+ )
+
+ if action == "click":
+ actuator = self._get_actuator()
+ x, y = int(args["x"]), int(args["y"])
+ outcome = verified_click(
+ actuator,
+ x,
+ y,
+ button=str(args.get("button", "left")),
+ double=bool(args.get("double", False)),
+ )
+ if not outcome.ok:
+ raise RuntimeError(outcome.detail)
+ return f"click at ({x},{y})"
+
+ if action == "drag":
+ actuator = self._get_actuator()
+ outcome = verified_drag(
+ actuator,
+ int(args["x1"]),
+ int(args["y1"]),
+ int(args["x2"]),
+ int(args["y2"]),
+ duration_s=max(0.0, float(args.get("duration_ms", 400)) / 1000.0),
+ )
+ if not outcome.ok:
+ raise RuntimeError(outcome.detail)
+ return "drag"
+
+ if action == "type_text":
+ actuator = self._get_actuator()
+ text = str(args.get("text", ""))
+ actuator.type_text(text)
+ return f"typed {text[:40]!r}"
+
+ if action == "hotkey":
+ actuator = self._get_actuator()
+ keys = [str(k) for k in (args.get("keys") or [])]
+ if not keys:
+ raise ValueError("hotkey needs at least one key")
+ actuator.key_combo(keys)
+ return f"key {'+'.join(keys)}"
+
+ if action == "scroll":
+ actuator = self._get_actuator()
+ direction = str(args.get("direction", "down"))
+ amount = max(1, int(args.get("amount", 3)))
+ x = args.get("x")
+ y = args.get("y")
+ actuator.scroll(
+ direction,
+ amount * _SCROLL_UNIT,
+ x=int(x) if x is not None else None,
+ y=int(y) if y is not None else None,
+ )
+ return f"scroll {direction} x{amount}"
+
+ if action == "switch_window":
+ from jarvis.platform import window_state # noqa: PLC0415
+
+ ok, message = window_state.focus_window(str(args.get("title_contains", "")))
+ if not ok:
+ raise RuntimeError(message)
+ return message
+
+ if action == "open_app":
+ return self._open_app(str(args.get("app_name", "")))
+
+ raise ValueError(f"unknown screen action {action!r}")
+
+ def _open_app(self, app_name: str) -> str:
+ """Launch (or focus) an application inside this screen.
+
+ Deliberately modest compared with the host's app-inventory tool: a
+ fresh isolated session has no learned inventory, so the honest
+ contract is "run what I was told to run, then wait for its window".
+ Focusing an already-open window first keeps a second launch from
+ piling up duplicate processes.
+ """
+ name = app_name.strip()
+ if not name:
+ raise ValueError("open_app needs an app name")
+
+ from jarvis.platform import window_state # noqa: PLC0415
+
+ existing = window_state.is_app_running(name)
+ if existing is not None:
+ ok, message = window_state.raise_window(existing)
+ if ok:
+ return message
+
+ import shutil # noqa: PLC0415
+ import subprocess # noqa: PLC0415
+
+ resolved = shutil.which(name)
+ launch: list[str]
+ if resolved:
+ launch = [resolved]
+ elif sys.platform == "win32":
+ launch = ["cmd", "/c", "start", "", name]
+ elif sys.platform == "darwin":
+ launch = ["open", "-a", name]
+ else:
+ launch = ["xdg-open", name]
+ creationflags = 0
+ if sys.platform == "win32":
+ from jarvis.core.process_utils import ( # noqa: PLC0415
+ NO_WINDOW_CREATIONFLAGS,
+ )
+
+ creationflags = NO_WINDOW_CREATIONFLAGS
+ subprocess.Popen( # noqa: S603 — the name comes from the CU action grammar
+ launch,
+ creationflags=creationflags,
+ close_fds=True,
+ )
+ # Give the window a bounded chance to appear so the next perception
+ # frame sees the app rather than an empty desktop.
+ deadline = time.monotonic() + 8.0
+ while time.monotonic() < deadline:
+ if window_state.is_app_running(name) is not None:
+ return f"launched {name}"
+ time.sleep(0.15)
+ return f"launched {name} (no window yet)"
+
+ def quit(self, _params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ self._stop.set()
+ return ({"ok": True}, b"")
+
+ # -- dispatch ----------------------------------------------------------
+
+ def handle(self, method: str, params: dict[str, Any]) -> tuple[dict[str, Any], bytes]:
+ handler = {
+ "health": self.health,
+ "geometry": self.geometry,
+ "grab": self.grab,
+ "foreground": self.foreground,
+ "ui_snapshot": self.ui_snapshot,
+ "typed_text_landed": self.typed_text_landed,
+ "click_landed_in_focus": self.click_landed_in_focus,
+ "act": self.act,
+ "quit": self.quit,
+ }.get(method)
+ if handler is None:
+ return ({"ok": False, "error": f"unknown method {method!r}"}, b"")
+ try:
+ return handler(params)
+ except Exception as exc: # noqa: BLE001 — one bad verb must not kill
+ # the runner: the host is mid-mission and can retry or fail the
+ # step, but it cannot restart a sandbox cheaply.
+ logger.warning("[screen-runner] %s failed", method, exc_info=True)
+ return ({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, b"")
+
+
+# ---------------------------------------------------------------------------
+# Server loops
+# ---------------------------------------------------------------------------
+
+
+def _serve_http(
+ server: ScreenServer,
+ token: str,
+ host: str,
+ port: int,
+ port_file: Path | None,
+) -> None:
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer # noqa: PLC0415
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args: Any) -> None: # noqa: D102 — silence stderr spam
+ return
+
+ def do_POST(self) -> None: # noqa: N802 — BaseHTTPRequestHandler API
+ if self.headers.get(HEADER_TOKEN, "") != token:
+ self.send_response(401)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
+ length = int(self.headers.get("Content-Length", "0") or 0)
+ raw = self.rfile.read(length) if length else b"{}"
+ try:
+ request = json.loads(raw.decode("utf-8"))
+ method = str(request.get("method", ""))
+ params = dict(request.get("params") or {})
+ except Exception: # noqa: BLE001
+ self.send_response(400)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
+ envelope, blob = server.handle(method, params)
+ if blob:
+ self.send_response(200)
+ self.send_header("Content-Type", "application/octet-stream")
+ self.send_header(HEADER_WIDTH, str(envelope.get("width", 0)))
+ self.send_header(HEADER_HEIGHT, str(envelope.get("height", 0)))
+ self.send_header(HEADER_FORMAT, str(envelope.get("format", "RGB")))
+ self.send_header("Content-Length", str(len(blob)))
+ self.end_headers()
+ self.wfile.write(blob)
+ else:
+ body = json.dumps(envelope, ensure_ascii=False).encode("utf-8")
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ if method == "quit":
+ threading.Thread(target=httpd.shutdown, daemon=True).start()
+
+ httpd = ThreadingHTTPServer((host, port), Handler)
+ bound_port = httpd.server_address[1]
+ if port_file is not None:
+ # Written only once the socket is actually listening, so the host
+ # never dials a port that is not up yet.
+ write_atomic(Path(port_file), str(bound_port).encode("utf-8"))
+ logger.info("[screen-runner] http transport on %s:%s", host, bound_port)
+ try:
+ httpd.serve_forever(poll_interval=0.2)
+ finally:
+ httpd.server_close()
+
+
+def _serve_mailbox(server: ScreenServer, token: str, mailbox: Path) -> None:
+ mailbox.mkdir(parents=True, exist_ok=True)
+ logger.info("[screen-runner] mailbox transport in %s", mailbox)
+ while not server.stopped.is_set():
+ requests = sorted(mailbox.glob(f"*{REQ_SUFFIX}"))
+ if not requests:
+ time.sleep(MAILBOX_POLL_S)
+ continue
+ for req_path in requests:
+ seq = req_path.name[: -len(REQ_SUFFIX)]
+ try:
+ request = json.loads(req_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
+ # A half-written or vanished request: the host writes
+ # atomically, so this is a torn read of a file being replaced.
+ # Skipping lets the next poll see the settled file.
+ continue
+ if str(request.get("token", "")) != token:
+ envelope, blob = {"ok": False, "error": "bad token"}, b""
+ else:
+ envelope, blob = server.handle(
+ str(request.get("method", "")),
+ dict(request.get("params") or {}),
+ )
+ try:
+ if blob:
+ write_atomic(mailbox / f"{seq}{BIN_SUFFIX}", blob)
+ # The JSON is written LAST: its existence is the host's proof
+ # that the whole answer (payload included) is on disk.
+ write_atomic(
+ mailbox / f"{seq}{RES_SUFFIX}",
+ json.dumps(envelope, ensure_ascii=False).encode("utf-8"),
+ )
+ req_path.unlink(missing_ok=True)
+ except OSError:
+ logger.warning(
+ "[screen-runner] could not answer %s", seq, exc_info=True,
+ )
+
+
+def serve(
+ *,
+ transport: str,
+ token: str,
+ kind: str = "xvfb",
+ host: str = "127.0.0.1",
+ port: int = 0,
+ port_file: Path | None = None,
+ mailbox: Path | None = None,
+) -> None:
+ """Run one runner until it is told to quit."""
+ server = ScreenServer(kind=kind)
+ if transport == "http":
+ _serve_http(server, token, host, port, port_file)
+ elif transport == "mailbox":
+ if mailbox is None:
+ raise ValueError("the mailbox transport needs a directory")
+ _serve_mailbox(server, token, Path(mailbox))
+ else:
+ raise ValueError(f"unknown transport {transport!r}")
+
+
+def _read_token(token_file: Path) -> str:
+ """Read the boot token, then remove the file.
+
+ The token never travels in argv (a process listing is world-readable on
+ every supported OS). Deleting it after the read keeps a later process on
+ the same screen from picking it up.
+ """
+ token = Path(token_file).read_text(encoding="utf-8").strip()
+ try:
+ Path(token_file).unlink(missing_ok=True)
+ except OSError:
+ logger.debug("[screen-runner] token file cleanup failed", exc_info=True)
+ if not token:
+ raise ValueError("the screen token file is empty")
+ return token
+
+
+def main(argv: list[str] | None = None) -> int:
+ import argparse # noqa: PLC0415
+
+ parser = argparse.ArgumentParser(prog="jarvis-agent-screen-runner")
+ parser.add_argument("--transport", choices=("http", "mailbox"), required=True)
+ parser.add_argument("--kind", default="xvfb")
+ parser.add_argument("--token-file", required=True)
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=0)
+ parser.add_argument("--port-file", default="")
+ parser.add_argument("--mailbox", default="")
+ args = parser.parse_args(argv)
+
+ logging.basicConfig(
+ level=os.environ.get("JARVIS_SCREEN_RUNNER_LOG", "INFO"),
+ format="%(asctime)s %(levelname)s %(message)s",
+ )
+ token = _read_token(Path(args.token_file))
+ serve(
+ transport=args.transport,
+ token=token,
+ kind=args.kind,
+ host=args.host,
+ port=args.port,
+ port_file=Path(args.port_file) if args.port_file else None,
+ mailbox=Path(args.mailbox) if args.mailbox else None,
+ )
+ return 0
+
+
+__all__ = ["ScreenServer", "main", "serve"]
diff --git a/jarvis/agent_screen/session.py b/jarvis/agent_screen/session.py
new file mode 100644
index 0000000000..508d3d4c0f
--- /dev/null
+++ b/jarvis/agent_screen/session.py
@@ -0,0 +1,307 @@
+"""A screen driven through a runner living inside the isolated session."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jarvis.agent_screen.protocol import (
+ ActOutcome,
+ AgentScreenUnavailable,
+ ForegroundInfo,
+ RawFrame,
+ ScreenKind,
+ ScreenSession,
+)
+from jarvis.agent_screen.wire import PROTOCOL_VERSION, Transport, TransportError
+
+logger = logging.getLogger(__name__)
+
+#: Per-verb ceilings. A grab of a full desktop over the mailbox transport is
+#: the slowest verb, and an ``act`` may legitimately wait on an app; both stay
+#: below the engine's own ``_ACT_TIMEOUT_S`` so a stuck screen surfaces as a
+#: named screen failure rather than an opaque tool timeout.
+_TIMEOUT_FAST_S = 8.0
+_TIMEOUT_GRAB_S = 15.0
+_TIMEOUT_ACT_S = 12.0
+
+
+class RemoteScreenSession(ScreenSession):
+ """Talks to an in-session runner over one :class:`Transport`.
+
+ Every degraded capability answers honestly rather than raising: a screen
+ whose foreground is unreadable returns ``available=False`` (the engine
+ then refuses unbound input, which is correct), and an absent
+ accessibility channel returns the empty snapshot (the engine falls back to
+ pixel grounding). Only a dead transport raises — that is a real outage
+ and must not be mistaken for "the app has no buttons".
+ """
+
+ def __init__(
+ self,
+ *,
+ screen_id: str,
+ kind: ScreenKind,
+ transport: Transport,
+ owner: str = "",
+ purpose: str = "",
+ hidden: bool = True,
+ on_close: Any = None,
+ ) -> None:
+ self.screen_id = screen_id
+ self.kind = kind
+ self.owner = owner
+ self.purpose = purpose
+ self.hidden = hidden
+ self._transport = transport
+ self._on_close = on_close
+ self._closed = False
+ self._geometry: tuple[int, int, int, int] | None = None
+
+ # -- lifecycle ---------------------------------------------------------
+
+ def handshake(self, *, timeout_s: float = 30.0) -> None:
+ """Verify the runner is up and speaks our protocol version.
+
+ Called once by the provider after boot. A version mismatch fails
+ loudly here instead of producing subtly wrong pixels later — the
+ Windows Sandbox runner is a separate implementation in another
+ language, so drift between the two is a real risk, not a theoretical
+ one.
+ """
+ envelope, _ = self._transport.call("health", timeout_s=timeout_s)
+ version = int(envelope.get("v", 0) or 0)
+ if version != PROTOCOL_VERSION:
+ raise AgentScreenUnavailable(
+ f"the screen runner speaks protocol v{version}, this build "
+ f"needs v{PROTOCOL_VERSION}. Restart Personal Jarvis so the "
+ "runner is re-deployed into the screen.",
+ )
+ if envelope.get("ok") is not True:
+ raise AgentScreenUnavailable(
+ "the screen runner reported itself unhealthy: "
+ + str(envelope.get("error", "no reason given")),
+ )
+
+ def alive(self) -> bool:
+ if self._closed:
+ return False
+ try:
+ envelope, _ = self._transport.call("health", timeout_s=_TIMEOUT_FAST_S)
+ except TransportError:
+ return False
+ return envelope.get("ok") is True
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ try:
+ self._transport.call("quit", timeout_s=3.0)
+ except TransportError:
+ logger.debug(
+ "[agent-screen] %s: quit verb unanswered (already gone)",
+ self.screen_id,
+ )
+ except Exception: # noqa: BLE001 — teardown must never raise
+ logger.debug("[agent-screen] %s: quit failed", self.screen_id, exc_info=True)
+ try:
+ self._transport.close()
+ except Exception: # noqa: BLE001
+ logger.debug("[agent-screen] transport close failed", exc_info=True)
+ if callable(self._on_close):
+ try:
+ self._on_close()
+ except Exception: # noqa: BLE001 — provider teardown is its own concern
+ logger.warning(
+ "[agent-screen] %s: provider teardown failed",
+ self.screen_id,
+ exc_info=True,
+ )
+
+ # -- perception --------------------------------------------------------
+
+ def geometry(self) -> tuple[int, int, int, int]:
+ """Screen rect, cached: an isolated screen cannot be re-plugged.
+
+ The user's physical desktop can gain or lose a monitor mid-mission,
+ which is why the engine re-reads its topology; an agent screen has
+ exactly one fixed framebuffer for its lifetime, so re-asking every
+ step would only add round-trips.
+ """
+ if self._geometry is None:
+ envelope, _ = self._transport.call("geometry", timeout_s=_TIMEOUT_FAST_S)
+ self._geometry = (
+ int(envelope.get("left", 0) or 0),
+ int(envelope.get("top", 0) or 0),
+ int(envelope.get("width", 0) or 0),
+ int(envelope.get("height", 0) or 0),
+ )
+ if self._geometry[2] <= 0 or self._geometry[3] <= 0:
+ raise AgentScreenUnavailable(
+ f"screen {self.screen_id} reported an empty framebuffer "
+ f"({self._geometry[2]}x{self._geometry[3]})",
+ )
+ return self._geometry
+
+ def grab(self, bbox: dict[str, int], *, rgb: bool = False) -> RawFrame:
+ envelope, blob = self._transport.call(
+ "grab",
+ {
+ "left": int(bbox["left"]),
+ "top": int(bbox["top"]),
+ "width": int(bbox["width"]),
+ "height": int(bbox["height"]),
+ "rgb": bool(rgb),
+ },
+ timeout_s=_TIMEOUT_GRAB_S,
+ )
+ width = int(envelope.get("width", 0) or 0)
+ height = int(envelope.get("height", 0) or 0)
+ pixel_format = str(envelope.get("format", "RGB") or "RGB").upper()
+ if pixel_format not in ("RGB", "BGRX"):
+ raise AgentScreenUnavailable(
+ f"screen {self.screen_id} sent an unknown pixel format "
+ f"{pixel_format!r}",
+ )
+ expected = width * height * (3 if pixel_format == "RGB" else 4)
+ if width <= 0 or height <= 0 or len(blob) != expected:
+ raise AgentScreenUnavailable(
+ f"screen {self.screen_id} sent a truncated frame: "
+ f"{len(blob)} bytes for {width}x{height} {pixel_format} "
+ f"(expected {expected})",
+ )
+ return RawFrame(
+ width=width,
+ height=height,
+ pixel_format=pixel_format, # type: ignore[arg-type]
+ data=blob,
+ )
+
+ def foreground(self) -> ForegroundInfo:
+ try:
+ envelope, _ = self._transport.call(
+ "foreground",
+ timeout_s=_TIMEOUT_FAST_S,
+ )
+ except TransportError:
+ # A dead transport is a dead screen; the caller's next verb will
+ # raise. Reporting "no foreground" keeps the fail-closed contract
+ # (the engine refuses unbound input) without masking the outage.
+ logger.debug(
+ "[agent-screen] %s: foreground read failed",
+ self.screen_id,
+ exc_info=True,
+ )
+ return ForegroundInfo(available=False)
+ if envelope.get("available") is not True:
+ return ForegroundInfo(available=False)
+ raw_rect = envelope.get("rect")
+ rect: tuple[int, int, int, int] | None = None
+ if isinstance(raw_rect, (list, tuple)) and len(raw_rect) == 4:
+ rect = (
+ int(raw_rect[0]),
+ int(raw_rect[1]),
+ int(raw_rect[2]),
+ int(raw_rect[3]),
+ )
+ handle_raw = envelope.get("handle")
+ return ForegroundInfo(
+ available=True,
+ title=str(envelope.get("title", "") or ""),
+ app=str(envelope.get("app", "") or ""),
+ handle=int(handle_raw) if handle_raw else None,
+ rect=rect,
+ )
+
+ def ui_snapshot(self) -> tuple[list[str], str, str | None, list[Any]]:
+ """Accessibility snapshot from inside the screen, empty when absent.
+
+ The runner answers ``supported: false`` on a session without an
+ accessibility bridge. That empty answer is a feature: the engine then
+ grounds purely on pixels, which is exactly right for a fresh sandbox,
+ and no code has to special-case the screen kind.
+ """
+ try:
+ envelope, _ = self._transport.call("ui_snapshot", timeout_s=_TIMEOUT_FAST_S)
+ except TransportError:
+ return ([], "", None, [])
+ if envelope.get("supported") is not True:
+ return ([], "", None, [])
+ labels = [str(x) for x in (envelope.get("labels") or []) if str(x)]
+ hint = str(envelope.get("field_hint", "") or "")
+ handoff_raw = envelope.get("handoff")
+ handoff = str(handoff_raw) if handoff_raw else None
+ rects: list[Any] = []
+ for entry in envelope.get("clickables") or []:
+ if not isinstance(entry, (list, tuple)) or len(entry) != 3:
+ continue
+ bounds = entry[2]
+ if not isinstance(bounds, (list, tuple)) or len(bounds) != 4:
+ continue
+ rects.append(
+ (
+ str(entry[0]),
+ str(entry[1]),
+ (
+ int(bounds[0]),
+ int(bounds[1]),
+ int(bounds[2]),
+ int(bounds[3]),
+ ),
+ ),
+ )
+ return (labels, hint, handoff, rects)
+
+ def typed_text_landed(self, typed: str) -> bool | None:
+ try:
+ envelope, _ = self._transport.call(
+ "typed_text_landed",
+ {"text": str(typed)},
+ timeout_s=_TIMEOUT_FAST_S,
+ )
+ except TransportError:
+ return None
+ verdict = envelope.get("landed")
+ return verdict if isinstance(verdict, bool) else None
+
+ def click_landed_in_focus(
+ self,
+ x: int,
+ y: int,
+ *,
+ capture_area: int | None = None,
+ ) -> bool | None:
+ try:
+ envelope, _ = self._transport.call(
+ "click_landed_in_focus",
+ {
+ "x": int(x),
+ "y": int(y),
+ "capture_area": int(capture_area or 0),
+ },
+ timeout_s=_TIMEOUT_FAST_S,
+ )
+ except TransportError:
+ return None
+ verdict = envelope.get("focused")
+ return verdict if isinstance(verdict, bool) else None
+
+ # -- actuation ---------------------------------------------------------
+
+ def act(self, action: str, params: dict[str, Any]) -> ActOutcome:
+ try:
+ envelope, _ = self._transport.call(
+ "act",
+ {"action": str(action), "params": dict(params)},
+ timeout_s=_TIMEOUT_ACT_S,
+ )
+ except TransportError as exc:
+ return ActOutcome(ok=False, detail=str(exc))
+ return ActOutcome(
+ ok=envelope.get("ok") is True,
+ detail=str(envelope.get("detail", "") or envelope.get("error", "") or ""),
+ )
+
+
+__all__ = ["RemoteScreenSession"]
diff --git a/jarvis/agent_screen/tools.py b/jarvis/agent_screen/tools.py
new file mode 100644
index 0000000000..727a9e63bf
--- /dev/null
+++ b/jarvis/agent_screen/tools.py
@@ -0,0 +1,358 @@
+"""Action tools bound to one agent screen.
+
+These carry the SAME tool names as the physical-desktop tools (``click``,
+``type_text``, ``hotkey``, ``scroll``, ``drag``, ``click_element``,
+``open_app``, ``switch_window``). That is the whole trick: the Computer-Use
+engine dispatches by name through the ToolExecutor, so swapping the tool map
+redirects every action into the isolated session without touching a line of
+the engine's action code — and without leaving the ToolExecutor choke point
+that gates and records every action (AP-3).
+
+Each tool re-checks the captured foreground identity immediately before it
+acts, exactly like its physical counterpart. On a screen nobody is watching
+that check matters MORE, not less: there is no user to notice that a dialog
+stole focus between the screenshot and the click.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from jarvis.core.protocols import ExecutionContext, ToolResult
+
+#: Every action name an agent screen answers. Kept in one place so the broker
+#: allowlist, the tool map and the tests cannot drift apart.
+SCREEN_TOOL_NAMES: tuple[str, ...] = (
+ "click",
+ "type_text",
+ "hotkey",
+ "scroll",
+ "drag",
+ "click_element",
+ "open_app",
+ "switch_window",
+)
+
+
+class _ScreenBoundTool:
+ """Shared body: validate, re-check the foreground, dispatch, report."""
+
+ name: str = ""
+ risk_tier: str = "monitor"
+ description: str = ""
+ schema: dict[str, Any] = {"type": "object", "properties": {}}
+ #: Actions that move the pointer or the keyboard focus and therefore must
+ #: honour the captured-window guard. ``open_app`` is excluded because it
+ #: is expected to CHANGE the foreground.
+ guarded: bool = True
+
+ def __init__(self, session: Any) -> None:
+ self._session = session
+
+ @property
+ def screen_id(self) -> str:
+ return str(getattr(self._session, "screen_id", ""))
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ raise NotImplementedError
+
+ def _guard_ok(self, expected: tuple[Any, ...] | None) -> bool:
+ if not self.guarded or expected is None:
+ return True
+ if not expected or expected[0] == "none":
+ return False
+ return self._session.foreground().signature() == tuple(expected)
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ try:
+ params = self._action_params(args)
+ except (KeyError, TypeError, ValueError) as exc:
+ return ToolResult(success=False, output=None, error=str(exc))
+
+ expected_raw = args.get("_expected_window_signature")
+ if expected_raw is not None and not isinstance(expected_raw, (list, tuple)):
+ return ToolResult(
+ success=False,
+ output=None,
+ error=f"Refusing {self.name}: invalid captured-window identity.",
+ )
+ expected = tuple(expected_raw) if expected_raw is not None else None
+ if not await asyncio.to_thread(self._guard_ok, expected):
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ f"Refusing {self.name} on screen {self.screen_id}: the "
+ "foreground window identity is unavailable or changed "
+ "after the screenshot."
+ ),
+ )
+ outcome = await asyncio.to_thread(
+ self._session.act,
+ self._screen_action,
+ params,
+ )
+ if not outcome.ok:
+ return ToolResult(success=False, output=None, error=outcome.detail)
+ return ToolResult(
+ success=True,
+ output=f"{outcome.detail} [screen {self.screen_id}]",
+ )
+
+ #: Wire verb this tool maps to; equals ``name`` unless the screen has a
+ #: coarser primitive (``click_element`` resolves to a plain click).
+ _screen_action: str = ""
+
+
+class ScreenClickTool(_ScreenBoundTool):
+ name = "click"
+ _screen_action = "click"
+ description = "Click at a coordinate on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {
+ "x": {"type": "integer"},
+ "y": {"type": "integer"},
+ "button": {"type": "string", "enum": ["left", "right", "middle"]},
+ "double": {"type": "boolean"},
+ },
+ "required": ["x", "y"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ button = str(args.get("button", "left")).lower()
+ if button not in ("left", "right", "middle"):
+ raise ValueError(f"Unknown button={button!r}. Allowed: left/right/middle")
+ return {
+ "x": int(args["x"]),
+ "y": int(args["y"]),
+ "button": button,
+ "double": bool(args.get("double", False)),
+ }
+
+
+class ScreenTypeTextTool(_ScreenBoundTool):
+ name = "type_text"
+ _screen_action = "type_text"
+ description = "Type text into the focused control on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {"text": {"type": "string"}},
+ "required": ["text"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ text = args.get("text")
+ if not isinstance(text, str):
+ raise ValueError("text must be a string")
+ return {"text": text}
+
+
+class ScreenHotkeyTool(_ScreenBoundTool):
+ name = "hotkey"
+ _screen_action = "hotkey"
+ description = "Press a key combination on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {"keys": {"type": "array", "items": {"type": "string"}}},
+ "required": ["keys"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.cu.actuate.base import is_known_key_name # noqa: PLC0415
+
+ keys = [str(k) for k in (args.get("keys") or [])]
+ if not keys:
+ raise ValueError("keys must contain at least one key name")
+ unknown = [k for k in keys if not is_known_key_name(k)]
+ if unknown:
+ raise ValueError(f"unknown key name(s): {', '.join(unknown)}")
+ return {"keys": keys}
+
+
+class ScreenScrollTool(_ScreenBoundTool):
+ name = "scroll"
+ _screen_action = "scroll"
+ description = "Scroll on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {
+ "direction": {"type": "string", "enum": ["up", "down", "left", "right"]},
+ "amount": {"type": "integer"},
+ "x": {"type": "integer"},
+ "y": {"type": "integer"},
+ },
+ "required": ["direction"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ direction = str(args.get("direction", "down")).lower()
+ if direction not in ("up", "down", "left", "right"):
+ raise ValueError(f"unknown scroll direction {direction!r}")
+ params: dict[str, Any] = {
+ "direction": direction,
+ "amount": max(1, int(args.get("amount", 3))),
+ }
+ if args.get("x") is not None and args.get("y") is not None:
+ params["x"] = int(args["x"])
+ params["y"] = int(args["y"])
+ return params
+
+
+class ScreenDragTool(_ScreenBoundTool):
+ name = "drag"
+ _screen_action = "drag"
+ description = "Drag from one point to another on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {
+ "x1": {"type": "integer"},
+ "y1": {"type": "integer"},
+ "x2": {"type": "integer"},
+ "y2": {"type": "integer"},
+ "duration_ms": {"type": "integer"},
+ },
+ "required": ["x1", "y1", "x2", "y2"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "x1": int(args["x1"]),
+ "y1": int(args["y1"]),
+ "x2": int(args["x2"]),
+ "y2": int(args["y2"]),
+ "duration_ms": max(0, int(args.get("duration_ms", 400))),
+ }
+
+
+class ScreenClickElementTool(_ScreenBoundTool):
+ """Click a named control — honestly refused where no tree exists.
+
+ The physical-screen tool resolves a label through the accessibility tree
+ and clicks its centre. A screen whose runner reports no tree cannot do
+ that, and guessing a coordinate from a label would be exactly the
+ hallucinated click this engine's guards were built to stop. Refusing with
+ a reason sends the model back to pixel coordinates, which DO work.
+ """
+
+ name = "click_element"
+ _screen_action = "click"
+ description = "Click a named control on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ "required": ["name"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ return {"name": str(args.get("name", ""))}
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ label = str(args.get("name", "")).strip()
+ if not label:
+ return ToolResult(success=False, output=None, error="name is required")
+ labels, _hint, _handoff, rects = await asyncio.to_thread(
+ self._session.ui_snapshot,
+ )
+ match = next(
+ (
+ bounds
+ for name, _role, bounds in rects
+ if name.strip().casefold() == label.casefold()
+ ),
+ None,
+ )
+ if match is None:
+ available = ", ".join(labels[:12]) if labels else "none reported"
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ f"screen {self.screen_id} exposes no control named "
+ f"{label!r} (available: {available}). Use click with pixel "
+ "coordinates from the screenshot instead."
+ ),
+ )
+ left, top, width, height = match
+ outcome = await asyncio.to_thread(
+ self._session.act,
+ "click",
+ {
+ "x": int(left + width // 2),
+ "y": int(top + height // 2),
+ "button": "left",
+ "double": False,
+ },
+ )
+ if not outcome.ok:
+ return ToolResult(success=False, output=None, error=outcome.detail)
+ return ToolResult(
+ success=True,
+ output=f"clicked {label!r} [screen {self.screen_id}]",
+ )
+
+
+class ScreenOpenAppTool(_ScreenBoundTool):
+ name = "open_app"
+ _screen_action = "open_app"
+ guarded = False # launching an app is meant to change the foreground
+ description = "Launch or focus an application on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {"app_name": {"type": "string"}},
+ "required": ["app_name"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ name = str(args.get("app_name", "")).strip()
+ if not name:
+ raise ValueError("app_name is required")
+ return {"app_name": name}
+
+
+class ScreenSwitchWindowTool(_ScreenBoundTool):
+ name = "switch_window"
+ _screen_action = "switch_window"
+ guarded = False # switching windows is meant to change the foreground
+ description = "Focus an open window on the agent's own screen."
+ schema = {
+ "type": "object",
+ "properties": {"title_contains": {"type": "string"}},
+ "required": ["title_contains"],
+ }
+
+ def _action_params(self, args: dict[str, Any]) -> dict[str, Any]:
+ needle = str(args.get("title_contains", "")).strip()
+ if not needle:
+ raise ValueError("title_contains is required")
+ return {"title_contains": needle}
+
+
+def screen_bound_tools(session: Any) -> dict[str, Any]:
+ """The action tool map for one screen, keyed exactly as the engine asks."""
+ tools = (
+ ScreenClickTool(session),
+ ScreenTypeTextTool(session),
+ ScreenHotkeyTool(session),
+ ScreenScrollTool(session),
+ ScreenDragTool(session),
+ ScreenClickElementTool(session),
+ ScreenOpenAppTool(session),
+ ScreenSwitchWindowTool(session),
+ )
+ return {tool.name: tool for tool in tools}
+
+
+__all__ = [
+ "SCREEN_TOOL_NAMES",
+ "ScreenClickElementTool",
+ "ScreenClickTool",
+ "ScreenDragTool",
+ "ScreenHotkeyTool",
+ "ScreenOpenAppTool",
+ "ScreenScrollTool",
+ "ScreenSwitchWindowTool",
+ "ScreenTypeTextTool",
+ "screen_bound_tools",
+]
diff --git a/jarvis/agent_screen/wire.py b/jarvis/agent_screen/wire.py
new file mode 100644
index 0000000000..f2e340b922
--- /dev/null
+++ b/jarvis/agent_screen/wire.py
@@ -0,0 +1,302 @@
+"""The host↔screen wire protocol, and the two transports that carry it.
+
+A screen runs an in-session *runner* — a small program living INSIDE the
+isolated session — because that is the only place from which capture and
+synthetic input reach that session's own input stream. The host drives it
+with five verbs (``health``, ``geometry``, ``foreground``, ``grab``, ``act``,
+plus ``quit``), each a JSON request answered by a JSON envelope and, for
+``grab``, a raw pixel payload.
+
+Two transports carry the same verbs:
+
+* :class:`HttpTransport` — loopback HTTP. Used where the runner shares the
+ host's network namespace (a virtual X display, the diagnostic attached
+ runner).
+* :class:`MailboxTransport` — request/response FILES in a folder both sides
+ can see. Used for Windows Sandbox, where the guest sits behind NAT and the
+ host cannot dial into it. It is not a workaround but the better default
+ there: it works with the sandbox's networking switched OFF entirely, so an
+ agent screen needs no network attack surface at all.
+
+The framing is deliberately primitive (JSON + one raw blob, fixed file
+names). The Windows Sandbox guest has no Python — its runner is PowerShell
+with inline C# — so every rule here must be re-implementable in a page of
+another language without a parser.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+#: Bumped when the verbs or framing change incompatibly. The host refuses a
+#: runner whose major differs rather than mis-parsing its answers.
+PROTOCOL_VERSION = 1
+
+#: Header/field names shared by both transports.
+HEADER_TOKEN = "X-Agent-Screen-Token" # noqa: S105 — a header NAME, not a secret
+HEADER_WIDTH = "X-Agent-Screen-Width"
+HEADER_HEIGHT = "X-Agent-Screen-Height"
+HEADER_FORMAT = "X-Agent-Screen-Format"
+
+#: Mailbox file suffixes. The response JSON is always written LAST, after any
+#: binary payload, so its mere existence proves the whole answer is on disk —
+#: the one ordering rule the PowerShell runner must also honour.
+REQ_SUFFIX = ".req.json"
+RES_SUFFIX = ".res.json"
+BIN_SUFFIX = ".res.bin"
+PART_SUFFIX = ".part"
+
+#: How often the mailbox host polls for a response. 15 ms is well under one
+#: display frame, so it never dominates a capture that already costs
+#: milliseconds, while keeping the guest's own poll loop cheap.
+MAILBOX_POLL_S = 0.015
+
+
+class TransportError(RuntimeError):
+ """The runner could not be reached, or answered unusably."""
+
+
+def write_atomic(path: Path, data: bytes) -> None:
+ """Write ``data`` to ``path`` so a reader never sees a partial file.
+
+ ``os.replace`` is atomic within one directory on NTFS and POSIX alike,
+ which is what makes the mailbox safe without any locking: a reader either
+ sees the previous state or the complete new file, never a half-written
+ one. Mapped Windows Sandbox folders are ordinary filesystem redirects, so
+ the guarantee survives the guest boundary.
+ """
+ tmp = path.with_name(path.name + PART_SUFFIX)
+ tmp.write_bytes(data)
+ os.replace(tmp, path)
+
+
+def encode_request(method: str, payload: dict[str, Any] | None = None) -> bytes:
+ return json.dumps(
+ {"v": PROTOCOL_VERSION, "method": method, "params": payload or {}},
+ ensure_ascii=False,
+ ).encode("utf-8")
+
+
+def decode_envelope(raw: bytes) -> dict[str, Any]:
+ try:
+ obj = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise TransportError(f"screen runner sent unparseable JSON: {exc}") from exc
+ if not isinstance(obj, dict):
+ raise TransportError("screen runner sent a non-object envelope")
+ return obj
+
+
+class Transport:
+ """Host-side channel to one runner."""
+
+ def call(
+ self,
+ method: str,
+ params: dict[str, Any] | None = None,
+ *,
+ timeout_s: float = 20.0,
+ ) -> tuple[dict[str, Any], bytes]:
+ """Send one verb; return ``(json envelope, binary payload)``."""
+ raise NotImplementedError
+
+ def close(self) -> None:
+ """Release transport resources. Idempotent, never raises."""
+
+
+class HttpTransport(Transport):
+ """Loopback HTTP with a bearer token and a kept-alive connection.
+
+ Keep-alive is not a micro-optimisation here: one perception frame issues
+ at least two grabs plus foreground reads, and a fresh TCP handshake per
+ grab measurably lengthened the stability loop in the local rig. The
+ connection is guarded by a lock because the CU engine reaches a screen
+ from ``asyncio.to_thread`` workers, i.e. from more than one thread.
+ """
+
+ def __init__(self, host: str, port: int, token: str) -> None:
+ self._host = host
+ self._port = int(port)
+ self._token = token
+ self._conn: Any = None
+ import threading
+
+ self._lock = threading.Lock()
+
+ def _connection(self, timeout_s: float) -> Any:
+ import http.client # noqa: PLC0415
+
+ if self._conn is None:
+ self._conn = http.client.HTTPConnection(
+ self._host,
+ self._port,
+ timeout=timeout_s,
+ )
+ return self._conn
+
+ def _drop(self) -> None:
+ conn, self._conn = self._conn, None
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception: # noqa: BLE001 — teardown is best-effort
+ logger.debug("agent-screen transport close failed", exc_info=True)
+
+ def call(
+ self,
+ method: str,
+ params: dict[str, Any] | None = None,
+ *,
+ timeout_s: float = 20.0,
+ ) -> tuple[dict[str, Any], bytes]:
+ body = encode_request(method, params)
+ headers = {
+ "Content-Type": "application/json; charset=utf-8",
+ HEADER_TOKEN: self._token,
+ "Connection": "keep-alive",
+ }
+ with self._lock:
+ for attempt in (1, 2):
+ try:
+ conn = self._connection(timeout_s)
+ conn.request("POST", f"/{method}", body=body, headers=headers)
+ response = conn.getresponse()
+ raw = response.read()
+ if response.status == 401:
+ raise TransportError("screen runner rejected the token")
+ if response.status != 200:
+ raise TransportError(
+ f"screen runner returned HTTP {response.status} for {method}",
+ )
+ content_type = response.getheader("Content-Type", "")
+ if "application/octet-stream" in content_type:
+ envelope = {
+ "ok": True,
+ "width": int(response.getheader(HEADER_WIDTH, "0") or 0),
+ "height": int(response.getheader(HEADER_HEIGHT, "0") or 0),
+ "format": response.getheader(HEADER_FORMAT, "RGB"),
+ }
+ return envelope, raw
+ return decode_envelope(raw), b""
+ except TransportError:
+ raise
+ except Exception as exc: # noqa: BLE001 — a stale keep-alive
+ # socket surfaces as an arbitrary OSError/http exception on
+ # the FIRST use after the peer recycled it. Retry once on a
+ # fresh connection; a second failure is a real outage.
+ self._drop()
+ if attempt == 2:
+ raise TransportError(
+ f"screen runner unreachable at "
+ f"{self._host}:{self._port} ({exc})",
+ ) from exc
+ raise TransportError("unreachable") # pragma: no cover — loop always returns
+
+ def close(self) -> None:
+ with self._lock:
+ self._drop()
+
+
+class MailboxTransport(Transport):
+ """Request/response files in a directory both sides can see.
+
+ Chosen for Windows Sandbox: the guest is NAT'd, so the host cannot dial
+ it, and a mapped folder is the one channel the sandbox configuration
+ guarantees. Because it needs no network at all, the sandbox can be booted
+ with networking disabled — the agent screen then has a strictly smaller
+ attack surface than the user's own desktop.
+ """
+
+ def __init__(self, mailbox_dir: Path, token: str) -> None:
+ self._dir = Path(mailbox_dir)
+ self._token = token
+ self._dir.mkdir(parents=True, exist_ok=True)
+ import threading
+
+ self._lock = threading.Lock()
+
+ def call(
+ self,
+ method: str,
+ params: dict[str, Any] | None = None,
+ *,
+ timeout_s: float = 20.0,
+ ) -> tuple[dict[str, Any], bytes]:
+ seq = uuid.uuid4().hex[:16]
+ req_path = self._dir / f"{seq}{REQ_SUFFIX}"
+ res_path = self._dir / f"{seq}{RES_SUFFIX}"
+ bin_path = self._dir / f"{seq}{BIN_SUFFIX}"
+ request = {
+ "v": PROTOCOL_VERSION,
+ "token": self._token,
+ "method": method,
+ "params": params or {},
+ }
+ with self._lock:
+ try:
+ write_atomic(
+ req_path,
+ json.dumps(request, ensure_ascii=False).encode("utf-8"),
+ )
+ except OSError as exc:
+ raise TransportError(
+ f"cannot write to the screen mailbox {self._dir}: {exc}",
+ ) from exc
+ deadline = time.monotonic() + max(0.1, timeout_s)
+ try:
+ while True:
+ if res_path.exists():
+ break
+ if time.monotonic() >= deadline:
+ raise TransportError(
+ f"the screen runner did not answer {method!r} within "
+ f"{timeout_s:.0f}s — the session may have died",
+ )
+ time.sleep(MAILBOX_POLL_S)
+ envelope = decode_envelope(res_path.read_bytes())
+ blob = b""
+ if envelope.get("binary"):
+ blob = bin_path.read_bytes()
+ finally:
+ for stale in (req_path, res_path, bin_path):
+ try:
+ stale.unlink(missing_ok=True)
+ except OSError: # noqa: PERF203 — cleanup is best-effort
+ pass
+ if envelope.get("ok") is False and method != "act":
+ raise TransportError(
+ f"screen runner failed {method!r}: {envelope.get('error', '')}",
+ )
+ return envelope, blob
+
+ def close(self) -> None:
+ """Nothing to release — the files are removed per call."""
+
+
+__all__ = [
+ "BIN_SUFFIX",
+ "HEADER_FORMAT",
+ "HEADER_HEIGHT",
+ "HEADER_TOKEN",
+ "HEADER_WIDTH",
+ "HttpTransport",
+ "MAILBOX_POLL_S",
+ "MailboxTransport",
+ "PART_SUFFIX",
+ "PROTOCOL_VERSION",
+ "REQ_SUFFIX",
+ "RES_SUFFIX",
+ "Transport",
+ "TransportError",
+ "decode_envelope",
+ "encode_request",
+ "write_atomic",
+]
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.py
index 6db0082fdc..73f0efb9d5 100644
--- a/jarvis/brain/dispatcher.py
+++ b/jarvis/brain/dispatcher.py
@@ -27,6 +27,7 @@ from jarvis.core.protocols import (
from jarvis.safety.tool_executor import ToolExecutor
from .iteration_budget import IterationBudget
+from .loop_control import LoopControl
from .streaming import StreamingAggregate, aggregate_with_consumer, tee_text
from .tool_use_loop import ToolUseLoop
@@ -47,6 +48,7 @@ class BrainDispatcher:
deadline_s: float | None = None,
reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
+ loop_control: LoopControl | None = None,
) -> None:
self._brain = brain
self._tools = tools or {}
@@ -71,6 +73,8 @@ class BrainDispatcher:
# BrainRequest this dispatcher issues (see ToolUseLoop.reasoning_effort
# and BrainRequest.reasoning_effort). ``None`` = provider default.
self._reasoning_effort = reasoning_effort
+ # Steering / phases / verification for this turn's loop, or None.
+ self._loop_control = loop_control
@property
def brain(self) -> Brain:
@@ -89,6 +93,7 @@ class BrainDispatcher:
deadline_s=self._deadline_s,
reasoning_effort=self._reasoning_effort,
tool_context=self._tool_context,
+ loop_control=self._loop_control,
)
def set_tools(self, tools: dict[str, Tool]) -> None:
@@ -157,6 +162,7 @@ class BrainDispatcher:
deadline_s=self._deadline_s,
reasoning_effort=self._reasoning_effort,
tool_context=self._tool_context,
+ loop_control=self._loop_control,
)
return await loop.run(
messages,
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 91151eea92..eedbe41006 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -116,6 +116,7 @@ ROUTER_TOOLS = frozenset({
# "Agent society voice tools".
"delegate-to-agent",
"society-status",
+ "message-agent",
# Skills-Brain-Integration: Brain-callable executor for installed user
# skills. D9-recursion-protection is structural — SkillRunner is constructed
# without a tool_registry that would re-expose run-skill recursively.
@@ -483,7 +484,7 @@ def _load_tools_for_tier(
kontrollierer_resolver=_resolve_kontrollierer,
announcer=build_spawn_announcer(config),
)
- elif ep.name in ("delegate-to-agent", "society-status"):
+ elif ep.name in ("delegate-to-agent", "society-status", "message-agent"):
# Agent society (2026-09-02): same lazy-resolver pattern as
# spawn-worker - the society runtime is built by the server
# on first use, after the brain exists.
diff --git a/jarvis/brain/loop_control.py b/jarvis/brain/loop_control.py
new file mode 100644
index 0000000000..e68ad0559b
--- /dev/null
+++ b/jarvis/brain/loop_control.py
@@ -0,0 +1,87 @@
+"""What a caller may hand the tool-use loop: steering, phases, verification.
+
+The loop is one turn's agentic cycle — gather context, act, verify, loop
+until the answer holds. Three of those four are the loop's own; the fourth,
+verification, and the person's ability to steer while it runs, belong to
+whoever owns the conversation. So they arrive as ONE optional object:
+
+* ``drain_steer`` — messages the person sent WHILE the turn ran. The loop
+ folds them into the next round as user text, so a running job is redirected
+ instead of being restarted (Grok Bot: "send a new message to interrupt work
+ in progress").
+* ``verify`` — the check that runs when the loop would otherwise finish: it
+ judges the answer against the request and the log of tools that actually
+ ran, and may send the turn back for one revision.
+* ``on_phase`` — what the turn is doing right now (``gather`` / ``act`` /
+ ``verify``), for the timeline and the island.
+
+``LoopControl`` is ``None`` on every other path (voice, scheduled tasks,
+missions), and those turns stay byte-identical. Stdlib only: this module
+imports nothing from ``jarvis`` so the loop stays cheap to import.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable, Sequence
+from dataclasses import dataclass
+
+__all__ = ["Ask", "LoopControl", "ToolRecord", "VerifyOutcome", "VerifyRequest"]
+
+#: ``(system, user) -> raw text`` — one tool-less question on the turn's OWN
+#: brain, so a verifier needs no provider of its own (AP-6/AP-21).
+Ask = Callable[[str, str], Awaitable[str]]
+
+#: Phases a turn reports. ``gather`` opens every round (the model reads what
+#: it has), ``act`` runs when tools are about to execute, ``verify`` when the
+#: answer is being checked.
+PHASE_GATHER = "gather"
+PHASE_ACT = "act"
+PHASE_VERIFY = "verify"
+
+
+@dataclass(frozen=True, slots=True)
+class ToolRecord:
+ """One tool call that really happened — the only evidence a verifier gets.
+
+ Text in an answer is not evidence that anything ran; this log is.
+ """
+
+ name: str
+ ok: bool
+ blocked: bool = False
+ #: First ~200 characters of the result (or the error), for the verifier.
+ preview: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class VerifyRequest:
+ """What the verifier judges: the ask, the answer, and what actually ran."""
+
+ user_text: str
+ answer: str
+ tool_log: tuple[ToolRecord, ...]
+ #: 0 on the first pass, 1 after one revision, …
+ attempt: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class VerifyOutcome:
+ """``accepted`` ends the turn; otherwise ``instruction`` drives one revision."""
+
+ accepted: bool
+ instruction: str = ""
+ detail: str = ""
+
+
+@dataclass(slots=True)
+class LoopControl:
+ """The hooks one turn may bring. Every field is optional."""
+
+ #: Returns (and clears) the messages the person sent while the turn ran.
+ drain_steer: Callable[[], Sequence[str]] | None = None
+ #: The verification pass; it gets the turn's own brain as ``Ask``.
+ verify: Callable[[VerifyRequest, Ask], Awaitable[VerifyOutcome]] | None = None
+ #: ``(phase, detail)`` — reported once per change, never per token.
+ on_phase: Callable[[str, str], Awaitable[None]] | None = None
+ #: How many revisions a verdict may ask for before the turn ends anyway.
+ max_verify: int = 2
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index afc1f6b618..b5d18a62cc 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -3578,6 +3578,7 @@ class BrainManager:
reasoning_effort: ReasoningEffort | None = None,
delegated_voice: bool = False,
tool_context: dict[str, Any] | None = None,
+ loop_control: Any = None,
) -> BrainDispatcher:
"""Builds the dispatcher with an optional tool override.
@@ -3639,6 +3640,7 @@ class BrainManager:
deadline_s=deadline_s,
reasoning_effort=reasoning_effort,
tool_context=tool_context,
+ loop_control=loop_control,
**kwargs,
)
@@ -3664,6 +3666,8 @@ class BrainManager:
kwargs["tool_context"] = dict(override.tool_context)
if override.max_turns is not None:
kwargs["max_turns"] = override.max_turns
+ if override.loop_control is not None:
+ kwargs["loop_control"] = override.loop_control
return kwargs
async def render_surface_prompt(self, *, user_text: str) -> tuple[str, str]:
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index 2fabc8c3ed..4bf890e48a 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -12,6 +12,7 @@ Flow:
"""
from __future__ import annotations
+import asyncio
import json
import logging
import re
@@ -43,6 +44,15 @@ from jarvis.core.turn_language import resolve_output_language, resolve_turn_lang
from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor
from .iteration_budget import IterationBudget
+from .loop_control import (
+ PHASE_ACT,
+ PHASE_GATHER,
+ PHASE_VERIFY,
+ LoopControl,
+ ToolRecord,
+ VerifyOutcome,
+ VerifyRequest,
+)
from .streaming import StreamingAggregate, aggregate, aggregate_with_consumer
from .tool_call_recovery import extract_leaked_tool_calls
@@ -80,6 +90,21 @@ _BUDGET_FINAL_DIRECTIVE = (
"not call any more tools."
)
+# What a message the person sent DURING the turn looks like when it reaches the
+# model. It is folded into the running job rather than starting a new one, so
+# the model must be told that this is a correction in flight, not a new task.
+_STEER_PREFIX = (
+ "[the person added this while you were working - fold it into the job you "
+ "are on, do not start over]\n"
+)
+
+# What a failed verification tells the model. Unlike the directives above this
+# one keeps the tools: a revision usually needs to LOOK again, not just rewrite.
+_VERIFY_DIRECTIVE = (
+ "[verification] Your answer was checked against what you actually did. "
+ "Fix this, then answer the person again in full:\n"
+)
+
# A provider can repeat the exact same text-serialized call after receiving its
# result. The action must remain exactly-once, but the turn must not end on an
# empty ``tool_use`` round. Force one tool-less synthesis pass instead.
@@ -102,6 +127,22 @@ def _cap_tool_result_json(serialized: str) -> str:
)
+def _last_user_text(messages: list[BrainMessage]) -> str:
+ """The ask a verifier judges against, when the caller passed none.
+
+ A steer line is skipped: the person's original request is what the answer
+ has to satisfy, not the correction that refined it.
+ """
+ for message in reversed(messages):
+ if message.role != "user" or not isinstance(message.content, str):
+ continue
+ text = message.content
+ if text.startswith(_STEER_PREFIX) or text.startswith("["):
+ continue
+ return text
+ return ""
+
+
def _tool_call_signature(call: dict[str, Any]) -> tuple[str, str]:
"""Canonical name/arguments fingerprint for same-round duplicate calls."""
arguments = call.get("input", {})
@@ -597,6 +638,7 @@ class ToolUseLoop:
deadline_s: float | None = None,
reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
+ loop_control: LoopControl | None = None,
) -> None:
self._brain = brain
self._tools = tools
@@ -639,6 +681,10 @@ class ToolUseLoop:
# (jarvis/cu/brain_call.py); providers without a reasoning knob ignore
# the hint (capability hint, never a provider pin — AP-21).
self._reasoning_effort = reasoning_effort
+ # Steering, phases and verification (jarvis/brain/loop_control.py).
+ # ``None`` on every path but the chat: those turns are unchanged.
+ self._control = loop_control
+ self._last_phase: tuple[str, str] | None = None
def _resolve_tool(self, requested: str) -> tuple[Tool | None, str]:
"""Look up a model-requested tool name, tolerating separator/case drift.
@@ -764,6 +810,88 @@ class ToolUseLoop:
for tool in self._tools.values()
]
+ async def _phase(self, phase: str, detail: str = "") -> None:
+ """Report what the turn is doing — once per change, never per token."""
+ control = self._control
+ if control is None or control.on_phase is None:
+ return
+ if self._last_phase == (phase, detail):
+ return
+ self._last_phase = (phase, detail)
+ try:
+ await control.on_phase(phase, detail)
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a phase listener never breaks the turn
+ log.debug("on_phase callback raised (ignored)", exc_info=True)
+
+ def _drain_steer(self) -> list[str]:
+ """What the person typed while this turn was running."""
+ control = self._control
+ if control is None or control.drain_steer is None:
+ return []
+ try:
+ return [str(t).strip() for t in control.drain_steer() if str(t).strip()]
+ except Exception: # noqa: BLE001 — a broken inbox costs the steer, not the turn
+ log.warning("drain_steer raised (ignored)", exc_info=True)
+ return []
+
+ @staticmethod
+ def _append_steer(messages: list[BrainMessage], texts: list[str]) -> None:
+ for text in texts:
+ messages.append(BrainMessage(role="user", content=_STEER_PREFIX + text))
+
+ async def _ask_once(self, system: str, user: str) -> str:
+ """One tool-less question on THIS turn's brain — how a verifier runs
+ without a provider, a key or a model id of its own (AP-6/AP-21)."""
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content=user),),
+ tools=(),
+ system=system,
+ max_tokens=2_000,
+ stream=True,
+ )
+ agg = await aggregate(self._brain.complete(req))
+ return agg.text
+
+ async def _run_verify(
+ self,
+ user_utterance: str,
+ answer: str,
+ tool_log: tuple[ToolRecord, ...],
+ *,
+ attempt: int,
+ blocked: bool,
+ ) -> VerifyOutcome | None:
+ """The check that runs where the loop would otherwise finish.
+
+ ``None`` means no verification happened: no hook, a forced final round
+ (the turn is already out of budget or time), or the revision cap is
+ reached. A verifier that raises is logged and the turn is accepted —
+ a broken check never costs the person their answer.
+ """
+ control = self._control
+ if control is None or control.verify is None or blocked:
+ return None
+ if attempt >= max(0, control.max_verify):
+ return None
+ await self._phase(PHASE_VERIFY, "checking the answer")
+ try:
+ return await control.verify(
+ VerifyRequest(
+ user_text=user_utterance,
+ answer=answer,
+ tool_log=tool_log,
+ attempt=attempt,
+ ),
+ self._ask_once,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — fail open: an unchecked answer beats none
+ log.warning("verify hook raised — accepting the turn", exc_info=True)
+ return None
+
async def run(
self,
messages: list[BrainMessage],
@@ -822,6 +950,9 @@ class ToolUseLoop:
loop_started = time.monotonic()
deadline_forced = False
seen_call_ids: set[str] = set()
+ tool_log: list[ToolRecord] = []
+ verify_rounds = 0
+ round_no = 0
def _progress() -> None:
# Stall-timeout heartbeat (see ``on_progress`` in the docstring).
@@ -836,6 +967,16 @@ class ToolUseLoop:
_progress()
while True:
+ # A message the person sent while this turn was running joins the
+ # NEXT round as their own words. It must not touch tools_payload or
+ # deadline_forced: steering continues the job, it does not end it.
+ pending = self._drain_steer()
+ if pending:
+ self._append_steer(current_messages, pending)
+ log.info("tool_use_loop: %d steer message(s) folded in", len(pending))
+ round_no += 1
+ await self._phase(PHASE_GATHER, f"round {round_no}")
+
req = BrainRequest(
messages=tuple(current_messages),
tools=tuple(tools_payload),
@@ -931,8 +1072,40 @@ class ToolUseLoop:
)
continue
- # No tool calls → done
+ # No tool calls → the answer is written. Before it stands: did
+ # the person say something else while we worked, and does the
+ # answer hold against what actually ran?
if not agg.tool_calls:
+ late = self._drain_steer()
+ if late:
+ self._append_steer(current_messages, late)
+ continue
+ outcome = await self._run_verify(
+ user_utterance or _last_user_text(current_messages),
+ final_agg.text,
+ tuple(tool_log),
+ attempt=verify_rounds,
+ blocked=deadline_forced,
+ )
+ if outcome is not None and not outcome.accepted and outcome.instruction:
+ verify_rounds += 1
+ log.info(
+ "tool_use_loop: verification asked for a revision (%d/%d)",
+ verify_rounds,
+ self._control.max_verify if self._control else 0,
+ )
+ current_messages.append(
+ BrainMessage(role="assistant", content=agg.text)
+ )
+ current_messages.append(
+ BrainMessage(
+ role="user", content=_VERIFY_DIRECTIVE + outcome.instruction
+ )
+ )
+ # The revision IS the answer: the draft was already closed
+ # into its own block by the verify phase hook.
+ final_agg.text = ""
+ continue
break
# The deadline-forced round is the LAST round, period. With
@@ -989,6 +1162,11 @@ class ToolUseLoop:
except Exception as exc: # noqa: BLE001 — emitter must never block tool execution
log.warning("ack_emitter failed: %s", exc)
+ await self._phase(
+ PHASE_ACT,
+ ", ".join(str(tc.get("name") or "") for tc in agg.tool_calls[:3]),
+ )
+
# Add assistant turn with tool-calls to the message history
# (for providers that expect role=assistant with tool_calls)
assistant_content: list[dict[str, Any]] = []
@@ -1423,6 +1601,17 @@ class ToolUseLoop:
tool_call_id=call_id,
name=tool_name,
))
+ if self._control is not None:
+ # The verifier's only evidence that something happened.
+ body = tool_result_payload.get("output")
+ if body in (None, ""):
+ body = tool_result_payload.get("error") or ""
+ tool_log.append(ToolRecord(
+ name=tool_name,
+ ok=bool(tool_result_payload.get("success")),
+ blocked=bool(tool_result_payload.get("blocked")),
+ preview=str(body)[:200],
+ ))
# A tool just finished — another active-work boundary. Reset the
# no-progress deadline so a slow tool (a vision capture, an MCP
# round-trip) does not count as a stall.
diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.py
index ad7811a3e0..e2689ba282 100644
--- a/jarvis/brain/turn_override.py
+++ b/jarvis/brain/turn_override.py
@@ -24,6 +24,8 @@ from typing import Any
from jarvis.core.protocols import ReasoningEffort, Tool
+from .loop_control import LoopControl
+
@dataclass(slots=True)
class TurnReceipt:
@@ -105,6 +107,10 @@ class TurnOverride:
manager's own ``_system_prompt_extra``. Empty leaves the prompt
byte-identical; a surface with its own briefing sets it for its
turns only.
+ ``loop_control``
+ Steering, phase reports and the verification pass for this turn
+ (``jarvis/brain/loop_control.py``). ``None`` leaves the tool-use loop
+ exactly as it was, which is what voice, tasks and missions get.
"""
provider: str
@@ -117,6 +123,7 @@ class TurnOverride:
max_turns: int | None = None
allow_force_spawn: bool = False
system_extra: str = ""
+ loop_control: LoopControl | None = None
receipt: TurnReceipt = field(default_factory=TurnReceipt)
diff --git a/jarvis/core/binary_lookup.py b/jarvis/core/binary_lookup.py
new file mode 100644
index 0000000000..5f8718d18b
--- /dev/null
+++ b/jarvis/core/binary_lookup.py
@@ -0,0 +1,128 @@
+"""One cached answer to "where is this binary?", for the paths that ask often.
+
+``shutil.which`` is not a lookup, it is a SEARCH: it walks every directory on
+``PATH`` and, on Windows, tries every ``PATHEXT`` extension in each of them
+until something matches. Measured on the maintainer's machine with 74 PATH
+entries: 10-16 ms per call, and a MISS is the expensive case — nothing matches,
+so every directory and every extension is visited before the answer is "no".
+
+That would be unremarkable if it happened once. It does not. Opening one
+Agentic-IDE pane resolves the agent's binary twice (once when the pane is added
+to the grid, once when its PTY is spawned), the workspace's ``/agents`` sweep
+resolves every registered CLI, and the CLI catalog prober resolves one per spec.
+All of it runs on the shared event loop — the same loop that has to accept the
+new panes' WebSockets and deliver the wake microphone — so the search does not
+only cost its own milliseconds, it postpones the work it was asked about.
+Measured: ``GET /api/agentic-ide/agents`` spent 92 ms of a warm response inside
+this one function.
+
+So the answer is remembered for :data:`TTL_S`.
+
+**Why a TTL rather than a permanent cache.** A binary can appear (the user
+installs a CLI) or vanish. A permanent cache would report a freshly installed
+agent as missing for the rest of the session. A TTL bounds that to a few
+seconds, and it is deliberately the same bound
+:mod:`jarvis.workspace.agents` already gives its detection sweep — those two
+answer the same question ("is this CLI here?") and must not disagree by more
+than one of them is willing to be wrong.
+
+**Why misses are cached too.** The miss is the slow case, and it is the common
+one on a machine that has three of the eight registered CLIs installed. Caching
+only hits would leave the expensive half uncached.
+
+**Why the PATH is part of the key.** ``jarvis.core.path_augment.ensure_cli_paths``
+appends install directories to ``os.environ["PATH"]`` while the app runs — a
+GUI-launched process starts without Homebrew or the npm prefix on it. An answer
+found before that happened is not an answer to the same question, so a changed
+PATH simply misses the cache instead of returning something stale.
+
+Cross-platform by construction: ``shutil.which`` is the only OS-specific part
+and it is the standard library's problem, not this module's.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import threading
+import time
+
+#: How long a resolved (or unresolved) binary location answers for.
+#:
+#: Matched to ``jarvis.workspace.agents._DETECTION_TTL_S`` on purpose: the
+#: detection sweep and this cache answer the same question by different means,
+#: and a user who installs a CLI from inside the app should not see one of them
+#: catch up before the other. Anything that KNOWS the answer changed calls
+#: :func:`invalidate` instead of waiting this out.
+TTL_S = 30.0
+
+#: Above this many remembered lookups, expired entries are swept before another
+#: is added. The steady state is a dozen or so (one per registered CLI plus the
+#: shells), so this is only ever reached when the PATH itself keeps changing —
+#: every distinct PATH is its own key, and without a sweep those would
+#: accumulate for the life of the process.
+_MAX_ENTRIES = 256
+
+#: name + PATH -> (answered_at, resolved path or None).
+_cache: dict[tuple[str, str], tuple[float, str | None]] = {}
+#: Guards ``_cache``. Reached from the event loop AND from worker threads (the
+#: PTY spawn preparation runs in one), so a plain dict is not enough on its own.
+_lock = threading.Lock()
+
+
+def invalidate() -> None:
+ """Forget every remembered location — the next lookup searches again.
+
+ For callers that KNOW the answer just changed: a CLI installed or removed
+ from inside the app. A user watching an install finish does not want to wait
+ out :data:`TTL_S` to see the pane become available.
+ """
+ with _lock:
+ _cache.clear()
+
+
+def which(name: str) -> str | None:
+ """``shutil.which(name)``, remembered for :data:`TTL_S`.
+
+ Same contract as the standard library's: the absolute path of the
+ executable, or ``None`` when it is not on ``PATH``. An empty name is
+ ``None`` without touching the cache — that is a caller with nothing to look
+ up, not a binary that is missing.
+
+ This does NOT augment the PATH itself; a caller that needs the well-known
+ install directories on it calls
+ :func:`jarvis.core.path_augment.ensure_cli_paths` first, exactly as it did
+ before this cache existed. Doing it here would put a filesystem sweep back
+ on the path this function exists to keep cheap.
+ """
+ if not name:
+ return None
+ key = (name, os.environ.get("PATH", ""))
+ now = time.monotonic()
+ with _lock:
+ remembered = _cache.get(key)
+ if remembered is not None and now - remembered[0] < TTL_S:
+ return remembered[1]
+
+ # Deliberately OUTSIDE the lock: the search is the slow part, and holding a
+ # process-wide lock across it would serialize every pane that is starting —
+ # which is the burst this module exists to make cheap. Two callers racing on
+ # the same name both search and both store the same answer; that costs one
+ # redundant search and can never store a wrong one.
+ found = shutil.which(name)
+
+ with _lock:
+ if len(_cache) >= _MAX_ENTRIES:
+ stale = [k for k, (at, _) in _cache.items() if now - at >= TTL_S]
+ for k in stale:
+ del _cache[k]
+ if len(_cache) >= _MAX_ENTRIES:
+ # Nothing was stale — every entry is a live PATH variant. Start
+ # over rather than grow without bound; the cost is one round of
+ # re-searching, which is what this looked like before the cache.
+ _cache.clear()
+ _cache[key] = (now, found)
+ return found
+
+
+__all__ = ["TTL_S", "invalidate", "which"]
diff --git a/jarvis/friends/activity.py b/jarvis/friends/activity.py
new file mode 100644
index 0000000000..8d38e3aa5d
--- /dev/null
+++ b/jarvis/friends/activity.py
@@ -0,0 +1,334 @@
+"""ActivityLedger — the count-only sidecar a usage pulse is built from.
+
+Why a dedicated ledger
+----------------------
+"How much does my friend use Personal Jarvis" needs a number that survives
+retention. Every store that already holds this information holds it *with
+content attached*: the session database keeps transcripts, the mission store
+keeps titles, the dictation history keeps the dictated text. Deriving a shared
+usage figure from any of them means walking rows that must never be shared, in
+a process that will one day be asked to serialise what it just read.
+
+So the shareable figures live in their own file, ``socials_activity.json``,
+and that file physically cannot leak anything else: it stores four integers
+per local calendar day and nothing else. No titles, no ids, no text, no paths.
+The privacy guarantee is a property of the storage shape, not of a filter that
+someone has to remember to apply.
+
+Two details inherited from :mod:`jarvis.dictation.stats`
+--------------------------------------------------------
+1. **Days are LOCAL days**, because "did I use it today" is a wall-clock
+ question. Bucketing by UTC shifts everyone's evening onto tomorrow.
+2. **Today gets grace** in the streak — a quiet morning does not read as 0.
+
+Both helpers are imported from that module rather than re-implemented; a second
+copy of the streak rule would drift from the first one within a release.
+
+Every method degrades to "no activity" instead of raising. A counter is never
+worth costing someone a voice session.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import tempfile
+import time
+from collections.abc import Iterable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from jarvis.dictation.stats import (
+ current_streak,
+ local_day,
+ longest_streak,
+ today_key,
+)
+
+log = logging.getLogger(__name__)
+
+#: The only metrics this ledger knows. A fixed tuple rather than free-form keys:
+#: an open key space is how a "just this once" label with a project name in it
+#: ends up in a file that is designed to be shareable.
+METRICS: tuple[str, ...] = (
+ "voice_sessions",
+ "missions",
+ "agent_tasks",
+ "messages_sent",
+)
+
+#: Upper bound on retained day buckets (~10 years at four ints a day).
+MAX_DAYS_RETAINED = 3_650
+
+#: Bus event names mapped onto a metric. Anything not listed is ignored, so a
+#: new event type can never silently start feeding the shared figures.
+EVENT_METRICS: dict[str, str] = {
+ "VoiceSessionStarted": "voice_sessions",
+ "MissionCompleted": "missions",
+ "JarvisAgentTaskCompleted": "agent_tasks",
+}
+
+
+def _now_ns() -> int:
+ return time.time_ns()
+
+
+@dataclass(frozen=True, slots=True)
+class ActivityDay:
+ """One local calendar day of counts. Integers only, by construction."""
+
+ date: str
+ voice_sessions: int = 0
+ missions: int = 0
+ agent_tasks: int = 0
+ messages_sent: int = 0
+
+ @property
+ def total(self) -> int:
+ return (
+ self.voice_sessions
+ + self.missions
+ + self.agent_tasks
+ + self.messages_sent
+ )
+
+ def to_dict(self) -> dict[str, int]:
+ return {
+ "voice_sessions": self.voice_sessions,
+ "missions": self.missions,
+ "agent_tasks": self.agent_tasks,
+ "messages_sent": self.messages_sent,
+ }
+
+ def plus(self, metric: str, count: int) -> ActivityDay:
+ values = self.to_dict()
+ values[metric] = values.get(metric, 0) + count
+ return ActivityDay(date=self.date, **values)
+
+
+def default_activity_path() -> Path:
+ """``<user data>/data/socials_activity.json``."""
+ from jarvis.core.paths import user_data_dir
+
+ return Path(user_data_dir()) / "data" / "socials_activity.json"
+
+
+class ActivityLedger:
+ """Per-day counts of the things a friend may be told about.
+
+ Reads and writes are atomic (tempfile + ``os.replace``); a crash mid-write
+ leaves the previous file intact rather than a truncated one.
+ """
+
+ def __init__(self, path: Path | str | None = None) -> None:
+ self._path = Path(path) if path is not None else default_activity_path()
+ # Shared per path, like DictationStats: several callers construct their
+ # own ledger for the same file, and a per-object lock would leave the
+ # read-modify-write cycle unguarded between them.
+ from jarvis.dictation._locks import store_lock
+
+ self._lock = store_lock(self._path)
+
+ @property
+ def path(self) -> Path:
+ return self._path
+
+ # -- reading ---------------------------------------------------------
+
+ def load(self) -> tuple[dict[str, ActivityDay], int]:
+ """``(days, last_active_ns)``. Unreadable or corrupt reads as empty."""
+ days: dict[str, ActivityDay] = {}
+ last_active = 0
+ try:
+ raw = self._path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return days, last_active
+ except OSError as exc:
+ log.warning("socials activity ledger unreadable: %s", exc)
+ return days, last_active
+ try:
+ payload = json.loads(raw)
+ except (ValueError, TypeError) as exc:
+ log.warning("socials activity ledger is corrupt, ignoring it: %s", exc)
+ return days, last_active
+ if not isinstance(payload, dict):
+ return days, last_active
+
+ last_active = _as_int(payload.get("last_active_ns"))
+ stored = payload.get("days")
+ if isinstance(stored, dict):
+ for key, value in stored.items():
+ if not isinstance(value, dict):
+ continue # one bad bucket never invalidates the rest
+ days[str(key)] = ActivityDay(
+ date=str(key),
+ **{m: _as_int(value.get(m)) for m in METRICS},
+ )
+ return days, last_active
+
+ def active_days(self) -> list[str]:
+ """Local days with at least one recorded event, newest first."""
+ days, _ = self.load()
+ return sorted(
+ (d.date for d in days.values() if d.total > 0), reverse=True
+ )
+
+ def streaks(self) -> tuple[int, int]:
+ """``(current_days, longest_days)`` over the recorded days."""
+ active = self.active_days()
+ return current_streak(active), longest_streak(active)
+
+ def last_active_ns(self) -> int:
+ _, last = self.load()
+ return last
+
+ # -- writing ---------------------------------------------------------
+
+ def record(
+ self,
+ metric: str,
+ *,
+ at_ns: int | None = None,
+ count: int = 1,
+ ) -> bool:
+ """Count one event. ``False`` when nothing was recorded.
+
+ An unknown metric is dropped rather than stored — see :data:`METRICS`.
+ """
+ if metric not in METRICS:
+ log.debug("socials activity: unknown metric %r ignored", metric)
+ return False
+ amount = _as_int(count)
+ if amount <= 0:
+ return False
+ moment = _as_int(at_ns) or _now_ns()
+ day = _day_key_for(moment)
+ try:
+ with self._lock:
+ days, last_active = self.load()
+ previous = days.get(day, ActivityDay(date=day))
+ days[day] = previous.plus(metric, amount)
+ self._write(days, max(last_active, moment))
+ except Exception: # noqa: BLE001 — a counter never costs a session
+ log.warning("could not record socials activity", exc_info=True)
+ return False
+ return True
+
+ def reset(self) -> bool:
+ """Zero every count. What "stop sharing my usage" also calls."""
+ try:
+ with self._lock:
+ self._write({}, 0)
+ return True
+ except Exception: # noqa: BLE001
+ log.warning("could not reset the socials activity ledger", exc_info=True)
+ return False
+
+ def _write(self, days: dict[str, ActivityDay], last_active_ns: int) -> None:
+ ordered = sorted(days.values(), key=lambda d: d.date, reverse=True)
+ kept = ordered[:MAX_DAYS_RETAINED]
+ payload = {
+ "version": 1,
+ "last_active_ns": _as_int(last_active_ns),
+ "days": {d.date: d.to_dict() for d in kept},
+ }
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(self._path.parent), prefix=".socials_activity_", suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, ensure_ascii=False, indent=2)
+ os.replace(tmp_name, self._path)
+ except Exception:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+
+
+class ActivityRecorder:
+ """Bus observer that feeds the ledger. Lifecycle mirrors StatusPublisher.
+
+ Only the event names in :data:`EVENT_METRICS` are counted and only their
+ *arrival* is — no field of any event is ever read, so a future event
+ carrying a title or a transcript cannot start leaking through this path.
+ """
+
+ def __init__(self, bus: Any, ledger: ActivityLedger | None = None) -> None:
+ self._bus = bus
+ self._ledger = ledger or ActivityLedger()
+ self._handler: Any = None
+ self._started = False
+
+ @property
+ def ledger(self) -> ActivityLedger:
+ return self._ledger
+
+ async def start(self) -> None:
+ if self._started:
+ return
+ self._handler = self._on_event
+ self._bus.subscribe_all(self._handler)
+ self._started = True
+ log.info("socials ActivityRecorder started")
+
+ async def stop(self) -> None:
+ if not self._started:
+ return
+ if self._handler is not None:
+ unsubscribe = getattr(self._bus, "unsubscribe_all", None)
+ if unsubscribe is not None:
+ unsubscribe(self._handler)
+ self._handler = None
+ self._started = False
+ log.info("socials ActivityRecorder stopped")
+
+ async def _on_event(self, event: Any) -> None:
+ metric = EVENT_METRICS.get(type(event).__name__)
+ if metric is None:
+ return
+ timestamp = _as_int(getattr(event, "timestamp_ns", 0)) or _now_ns()
+ # The write is small and rare (a handful of events a day), but the bus
+ # dispatches wildcard handlers under a hard timeout — so it runs off the
+ # event loop rather than blocking it on a disk round-trip.
+ import asyncio
+
+ await asyncio.to_thread(self._ledger.record, metric, at_ns=timestamp)
+
+
+def _day_key_for(moment_ns: int) -> str:
+ """Nanosecond timestamp -> its LOCAL calendar day."""
+ from datetime import UTC, datetime
+
+ try:
+ stamp = datetime.fromtimestamp(moment_ns / 1_000_000_000, tz=UTC)
+ except (OSError, OverflowError, ValueError, TypeError):
+ return today_key()
+ return local_day(stamp.isoformat()) or today_key()
+
+
+def daily_totals(days: Iterable[ActivityDay]) -> int:
+ return sum(d.total for d in days)
+
+
+def _as_int(value: Any) -> int:
+ try:
+ return max(0, int(value or 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+__all__ = [
+ "EVENT_METRICS",
+ "MAX_DAYS_RETAINED",
+ "METRICS",
+ "ActivityDay",
+ "ActivityLedger",
+ "ActivityRecorder",
+ "daily_totals",
+ "default_activity_path",
+]
diff --git a/jarvis/friends/identity.py b/jarvis/friends/identity.py
new file mode 100644
index 0000000000..d6fc6251a6
--- /dev/null
+++ b/jarvis/friends/identity.py
@@ -0,0 +1,410 @@
+"""SocialIdentity — this instance's key pair, its invite codes, its envelopes.
+
+Why a key pair and not an account
+---------------------------------
+Two people running Personal Jarvis have no shared server to be accounts on.
+Anything that identifies them therefore has to be something they carry
+themselves. An Ed25519 key pair does exactly that: the public half *is* the
+identity (``node_id``), the private half proves it, and nobody has to be asked
+for permission to create one.
+
+That choice decides three other things:
+
+- **Invites are self-certifying.** An invite code carries the issuer's public
+ key and a signature over its own contents. Verifying it needs no lookup and
+ no trusted third party — if the signature checks out, the code was written by
+ whoever holds that key. A tampered code fails locally, before it reaches the
+ friend registry.
+- **Requests authenticate themselves.** Every peer request travels as a signed
+ envelope. The receiver checks the signature against the node id it already
+ has on file for that friend; an unknown or mismatched key is a 403 before any
+ handler runs.
+- **Losing the key loses the identity.** So it is stored through the same
+ keyring → ENV → file path as every other credential
+ (:func:`jarvis.core.config.get_secret`), which is the path a user can recover
+ from in-app on any OS, including a headless server with no keyring.
+
+Crypto comes from ``cryptography``, which is a base dependency on every
+platform. The optional ``board_backend``/PyNaCl stack is deliberately not used
+here: Socials has to work on a plain ``pip install .``.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import logging
+import secrets as _secrets
+import time
+from dataclasses import dataclass
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: Credential slot for the private key (hex). ENV fallback: ``SOCIALS_NODE_PRIVKEY``.
+PRIVKEY_SECRET_KEY = "socials_node_privkey" # noqa: S105 — a slot name, not a key
+
+#: Invite codes carry this prefix so a user can recognise one in a chat window
+#: and so a paste of the wrong string fails with a clear message.
+INVITE_PREFIX = "PJS1"
+
+#: How long an invite stays valid. Long enough to send by mail, short enough
+#: that an old code in a chat log is not a standing key to your friends list.
+INVITE_TTL_NS = 7 * 24 * 60 * 60 * 1_000_000_000
+
+#: Signed envelopes older or newer than this are rejected. Replay protection
+#: proper is per-endpoint (message ids are deduped); this bounds the window.
+MAX_ENVELOPE_SKEW_NS = 5 * 60 * 1_000_000_000
+
+
+class IdentityError(RuntimeError):
+ """The identity could not be loaded, created, or used."""
+
+
+class EnvelopeError(RuntimeError):
+ """A signed envelope was malformed, expired, or failed verification."""
+
+
+class InviteError(RuntimeError):
+ """An invite code was malformed, expired, or failed verification."""
+
+
+def canonical_bytes(payload: Any) -> bytes:
+ """Deterministic JSON encoding — the exact bytes a signature covers.
+
+ Sorted keys, no incidental whitespace, UTF-8. Two instances must produce
+ byte-identical output for the same object or every signature fails.
+ """
+ return json.dumps(
+ payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
+ ).encode("utf-8")
+
+
+def _b64e(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _b64d(text: str) -> bytes:
+ padded = text + "=" * (-len(text) % 4)
+ return base64.urlsafe_b64decode(padded.encode("ascii"))
+
+
+def _now_ns() -> int:
+ return time.time_ns()
+
+
+def _ed25519() -> Any:
+ try:
+ from cryptography.hazmat.primitives.asymmetric import ed25519
+ except Exception as exc: # noqa: BLE001
+ raise IdentityError(
+ "The 'cryptography' package is required for Personal Jarvis Socials."
+ ) from exc
+ return ed25519
+
+
+@dataclass(frozen=True, slots=True)
+class InvitePayload:
+ """The decoded, signature-verified contents of an invite code."""
+
+ node_id: str
+ display_name: str
+ endpoint: str | None
+ issued_at_ns: int
+ expires_at_ns: int
+ nonce: str
+
+ @property
+ def is_expired(self) -> bool:
+ return self.expires_at_ns > 0 and _now_ns() > self.expires_at_ns
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "node_id": self.node_id,
+ "display_name": self.display_name,
+ "endpoint": self.endpoint,
+ "issued_at_ns": self.issued_at_ns,
+ "expires_at_ns": self.expires_at_ns,
+ "nonce": self.nonce,
+ }
+
+
+class SocialIdentity:
+ """The local node's key pair plus everything that is signed with it.
+
+ Construct with :meth:`load_or_create` in application code; the explicit
+ constructor takes a private key so tests can build a deterministic pair
+ without touching the user's credential store.
+ """
+
+ def __init__(self, private_key_hex: str) -> None:
+ ed25519 = _ed25519()
+ try:
+ raw = bytes.fromhex(private_key_hex.strip())
+ self._private = ed25519.Ed25519PrivateKey.from_private_bytes(raw)
+ except (ValueError, TypeError) as exc:
+ raise IdentityError("Stored socials private key is not usable.") from exc
+ self._private_hex = private_key_hex.strip()
+
+ # -- construction ----------------------------------------------------
+
+ @classmethod
+ def generate(cls) -> SocialIdentity:
+ ed25519 = _ed25519()
+ key = ed25519.Ed25519PrivateKey.generate()
+ from cryptography.hazmat.primitives import serialization
+
+ raw = key.private_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PrivateFormat.Raw,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+ return cls(raw.hex())
+
+ @classmethod
+ def load_or_create(cls, *, persist: bool = True) -> SocialIdentity:
+ """Read the stored key, or mint one and store it.
+
+ A corrupt stored value is replaced rather than raised on: the identity
+ is regenerable (friends re-pair), and refusing to boot the social
+ section over an unreadable credential would be the worse failure.
+ """
+ from jarvis.core.config import get_secret, set_secret
+
+ stored = None
+ try:
+ stored = get_secret(PRIVKEY_SECRET_KEY)
+ except Exception: # noqa: BLE001 — an unreadable store means "no key yet"
+ log.debug("socials identity: credential store unreadable", exc_info=True)
+ if stored:
+ try:
+ return cls(stored)
+ except IdentityError:
+ log.warning("socials identity: stored key unusable — minting a fresh one")
+
+ identity = cls.generate()
+ if persist:
+ try:
+ if not set_secret(PRIVKEY_SECRET_KEY, identity.private_key_hex):
+ log.warning(
+ "socials identity: key could not be persisted — it will "
+ "change on the next start and friends must re-pair"
+ )
+ except Exception: # noqa: BLE001
+ log.warning("socials identity: persisting the key failed", exc_info=True)
+ return identity
+
+ # -- identity --------------------------------------------------------
+
+ @property
+ def private_key_hex(self) -> str:
+ return self._private_hex
+
+ @property
+ def node_id(self) -> str:
+ """The public key, hex — the identity a friend records for this node."""
+ from cryptography.hazmat.primitives import serialization
+
+ raw = self._private.public_key().public_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PublicFormat.Raw,
+ )
+ return raw.hex()
+
+ @property
+ def short_id(self) -> str:
+ """A human-comparable fingerprint, e.g. ``4f3c-2b91-08ad``.
+
+ Two people confirming they paired with each other read this aloud; a
+ 64-character hex string is not something anyone checks honestly.
+ """
+ node = self.node_id
+ return "-".join(node[i : i + 4] for i in range(0, 12, 4))
+
+ # -- signing ---------------------------------------------------------
+
+ def sign(self, payload: Any) -> str:
+ """Sign the canonical encoding of ``payload``; returns hex."""
+ return self._private.sign(canonical_bytes(payload)).hex()
+
+ def seal(self, body: dict[str, Any], *, issued_at_ns: int | None = None) -> dict[str, Any]:
+ """Wrap ``body`` in a signed envelope ready to POST to a peer."""
+ envelope = {
+ "node": self.node_id,
+ "issued_at_ns": int(issued_at_ns if issued_at_ns is not None else _now_ns()),
+ "body": body,
+ }
+ envelope["sig"] = self.sign(
+ {k: envelope[k] for k in ("node", "issued_at_ns", "body")}
+ )
+ return envelope
+
+ # -- invites ---------------------------------------------------------
+
+ def create_invite(
+ self,
+ *,
+ display_name: str,
+ endpoint: str | None = None,
+ ttl_ns: int = INVITE_TTL_NS,
+ now_ns: int | None = None,
+ ) -> str:
+ """Mint a signed, shareable invite code.
+
+ The code is the whole handshake: it names the issuing node, how to
+ reach it (when the user supplied a reachable address), and proves both
+ with a signature. The recipient pastes it and is done.
+ """
+ issued = int(now_ns if now_ns is not None else _now_ns())
+ payload = {
+ "v": 1,
+ "node": self.node_id,
+ "name": str(display_name or "")[:120],
+ "endpoint": _clean_endpoint(endpoint),
+ "issued_at_ns": issued,
+ "expires_at_ns": issued + max(0, int(ttl_ns)),
+ "nonce": _secrets.token_hex(8),
+ }
+ raw = canonical_bytes(payload)
+ signature = self._private.sign(raw)
+ return f"{INVITE_PREFIX}.{_b64e(raw)}.{_b64e(signature)}"
+
+
+def verify_envelope(
+ envelope: Any,
+ *,
+ now_ns: int | None = None,
+ max_skew_ns: int = MAX_ENVELOPE_SKEW_NS,
+) -> tuple[str, dict[str, Any]]:
+ """Verify a signed envelope. Returns ``(node_id, body)``.
+
+ Raises :class:`EnvelopeError` on anything that does not check out — a
+ malformed shape, a clock too far off, or a bad signature. The caller still
+ has to decide whether that node id is a friend; this function only proves
+ who wrote the request, never that they are welcome.
+ """
+ if not isinstance(envelope, dict):
+ raise EnvelopeError("Envelope is not an object.")
+ node = envelope.get("node")
+ signature = envelope.get("sig")
+ body = envelope.get("body")
+ issued = envelope.get("issued_at_ns")
+ if not isinstance(node, str) or not isinstance(signature, str):
+ raise EnvelopeError("Envelope is missing 'node' or 'sig'.")
+ if not isinstance(body, dict):
+ raise EnvelopeError("Envelope body must be an object.")
+ try:
+ issued_ns = int(issued)
+ except (TypeError, ValueError) as exc:
+ raise EnvelopeError("Envelope 'issued_at_ns' is not a number.") from exc
+
+ now = int(now_ns if now_ns is not None else _now_ns())
+ if max_skew_ns > 0 and abs(now - issued_ns) > max_skew_ns:
+ raise EnvelopeError("Envelope timestamp is outside the accepted window.")
+
+ if not verify_signature(
+ node,
+ {"node": node, "issued_at_ns": issued_ns, "body": body},
+ signature,
+ ):
+ raise EnvelopeError("Envelope signature does not verify.")
+ return node, body
+
+
+def verify_signature(node_id: str, payload: Any, signature_hex: str) -> bool:
+ """True when ``signature_hex`` is a valid signature by ``node_id``."""
+ ed25519 = _ed25519()
+ try:
+ public = ed25519.Ed25519PublicKey.from_public_bytes(bytes.fromhex(node_id))
+ public.verify(bytes.fromhex(signature_hex), canonical_bytes(payload))
+ except Exception: # noqa: BLE001 — every failure mode is "not verified"
+ return False
+ return True
+
+
+def decode_invite(code: str, *, now_ns: int | None = None) -> InvitePayload:
+ """Parse and verify an invite code.
+
+ Raises :class:`InviteError` with a message meant for a person: this is the
+ one place in Socials where a user pastes a string by hand, so "that code has
+ expired" has to be distinguishable from "that is not an invite code".
+ """
+ text = (code or "").strip()
+ if not text:
+ raise InviteError("No invite code was given.")
+ parts = text.split(".")
+ if len(parts) != 3 or parts[0] != INVITE_PREFIX:
+ raise InviteError("That does not look like a Personal Jarvis invite code.")
+ try:
+ raw = _b64d(parts[1])
+ signature = _b64d(parts[2])
+ except Exception as exc: # noqa: BLE001
+ raise InviteError("The invite code is damaged — copy it again in full.") from exc
+ try:
+ payload = json.loads(raw.decode("utf-8"))
+ except Exception as exc: # noqa: BLE001
+ raise InviteError("The invite code is damaged — copy it again in full.") from exc
+ if not isinstance(payload, dict) or payload.get("v") != 1:
+ raise InviteError("This invite code was made by an incompatible version.")
+
+ node = payload.get("node")
+ if not isinstance(node, str) or not node:
+ raise InviteError("The invite code names no node.")
+
+ ed25519 = _ed25519()
+ try:
+ public = ed25519.Ed25519PublicKey.from_public_bytes(bytes.fromhex(node))
+ # Verified against the exact bytes that were encoded, not against a
+ # re-serialised copy — re-encoding is how a signature check quietly
+ # starts depending on the local JSON implementation.
+ public.verify(signature, raw)
+ except Exception as exc: # noqa: BLE001
+ raise InviteError("The invite code's signature does not match.") from exc
+
+ invite = InvitePayload(
+ node_id=node,
+ display_name=str(payload.get("name") or "")[:120],
+ endpoint=_clean_endpoint(payload.get("endpoint")),
+ issued_at_ns=int(payload.get("issued_at_ns") or 0),
+ expires_at_ns=int(payload.get("expires_at_ns") or 0),
+ nonce=str(payload.get("nonce") or ""),
+ )
+ now = int(now_ns if now_ns is not None else _now_ns())
+ if invite.expires_at_ns > 0 and now > invite.expires_at_ns:
+ raise InviteError("This invite code has expired — ask for a fresh one.")
+ return invite
+
+
+def _clean_endpoint(value: Any) -> str | None:
+ """Normalise a peer base URL, or ``None`` when there is nothing usable.
+
+ Only ``http``/``https`` survive. An invite is pasted from a chat window, so
+ this is the boundary where a ``file://`` or ``javascript:`` string has to
+ stop rather than be handed to an HTTP client later.
+ """
+ if not value:
+ return None
+ text = str(value).strip().rstrip("/")
+ if not text:
+ return None
+ lowered = text.lower()
+ if not (lowered.startswith("http://") or lowered.startswith("https://")):
+ return None
+ return text
+
+
+__all__ = [
+ "INVITE_PREFIX",
+ "INVITE_TTL_NS",
+ "MAX_ENVELOPE_SKEW_NS",
+ "PRIVKEY_SECRET_KEY",
+ "EnvelopeError",
+ "IdentityError",
+ "InviteError",
+ "InvitePayload",
+ "SocialIdentity",
+ "canonical_bytes",
+ "decode_invite",
+ "verify_envelope",
+ "verify_signature",
+]
diff --git a/jarvis/friends/peer.py b/jarvis/friends/peer.py
new file mode 100644
index 0000000000..99e29ff31e
--- /dev/null
+++ b/jarvis/friends/peer.py
@@ -0,0 +1,353 @@
+"""Peer links — the direct, server-less connection between two Jarvis instances.
+
+The honest shape of this
+------------------------
+Personal Jarvis is a local application. Two friends running it are two laptops,
+usually both behind NAT, with no shared account and no company in the middle.
+There is therefore no way to make "just message my friend" work everywhere, and
+pretending otherwise would produce a chat window that silently drops messages.
+
+So a peer link is explicit about what it needs: **one side has to be reachable
+at an address the other can open** — a LAN address, a Tailscale/VPN name, a
+tunnel, or a published host. When that is true, everything works directly
+between the two machines and no third party sees anything. When it is not,
+delivery fails loudly, the message stays queued as undelivered, and the UI says
+which side is unreachable. That failure is a fact about home networks, not a
+bug, and the product states it rather than hiding it.
+
+What travels
+------------
+Every request is a signed envelope (:mod:`jarvis.friends.identity`). The
+receiver looks the sender's node id up in *its own* link table: an unknown key
+is rejected before any handler runs, so an exposed port is not an open inbox.
+Nothing here trusts a display name, an endpoint, or an id supplied in a body —
+those are hints shown to the user, while authorisation always comes from the
+signature.
+
+Delivery is at-most-once per message id. The receiver stores the sender's
+message id and rejects a repeat, so a retry after a timeout cannot duplicate a
+message in the thread.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from typing import Any, Literal
+from uuid import UUID
+
+import aiosqlite
+from pydantic import BaseModel, ConfigDict, Field
+
+log = logging.getLogger(__name__)
+
+PeerLinkState = Literal["pending", "active", "blocked"]
+"""``pending`` — invited, never spoken. ``active`` — a signed round-trip
+succeeded. ``blocked`` — the user cut them off; nothing in or out."""
+
+#: Peer HTTP timeout. A friend's laptop is either awake and close or it is not;
+#: a long timeout only makes the UI feel broken.
+PEER_TIMEOUT_S = 8.0
+
+#: How long a fetched pulse is considered current before the UI labels it stale.
+PULSE_FRESH_NS = 15 * 60 * 1_000_000_000
+
+
+class PeerError(RuntimeError):
+ """Base class for peer transport failures."""
+
+
+class PeerUnreachable(PeerError):
+ """The peer could not be contacted, or answered with an error.
+
+ Carries a message written for the user, because this is the error the chat
+ window shows when a friend's machine is asleep.
+ """
+
+
+class PeerLink(BaseModel):
+ """The direct connection to one friend's Jarvis instance."""
+
+ model_config = ConfigDict(frozen=False)
+
+ friend_id: UUID
+ node_id: str = Field(..., min_length=16, max_length=128)
+ endpoint: str | None = None
+ peer_display_name: str | None = None
+ state: PeerLinkState = "pending"
+ created_at_ns: int = Field(default_factory=lambda: time.time_ns())
+ last_seen_ns: int = 0
+ last_error: str | None = None
+ pulse_json: str | None = None
+ pulse_at_ns: int = 0
+
+ @property
+ def can_send(self) -> bool:
+ """Outbound is possible only with an address and without a block."""
+ return self.state != "blocked" and bool(self.endpoint)
+
+ @property
+ def short_id(self) -> str:
+ return "-".join(self.node_id[i : i + 4] for i in range(0, 12, 4))
+
+ def pulse(self) -> dict[str, Any] | None:
+ """The last fetched pulse, or ``None`` when there is none or it is unreadable."""
+ if not self.pulse_json:
+ return None
+ try:
+ value = json.loads(self.pulse_json)
+ except (ValueError, TypeError):
+ return None
+ return value if isinstance(value, dict) else None
+
+ def pulse_is_fresh(self, *, now_ns: int | None = None) -> bool:
+ if self.pulse_at_ns <= 0:
+ return False
+ now = int(now_ns if now_ns is not None else time.time_ns())
+ return (now - self.pulse_at_ns) <= PULSE_FRESH_NS
+
+
+class PeerLinkStore:
+ """SQLite store for peer links, sharing the FriendRegistry connection.
+
+ Like :class:`jarvis.friends.messages.DirectMessageStore`, this opens no
+ connection of its own — the registry owns the lifecycle, the WAL mode, and
+ the transaction boundary.
+ """
+
+ def __init__(self, conn: aiosqlite.Connection) -> None:
+ self._conn = conn
+
+ async def upsert(self, link: PeerLink) -> PeerLink:
+ await self._conn.execute(
+ "INSERT INTO friend_peer_links "
+ "(friend_id, node_id, endpoint, peer_display_name, state, "
+ " created_at_ns, last_seen_ns, last_error, pulse_json, pulse_at_ns) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(friend_id) DO UPDATE SET "
+ "node_id = excluded.node_id, "
+ "endpoint = excluded.endpoint, "
+ "peer_display_name = excluded.peer_display_name, "
+ "state = excluded.state, "
+ "last_seen_ns = excluded.last_seen_ns, "
+ "last_error = excluded.last_error, "
+ "pulse_json = excluded.pulse_json, "
+ "pulse_at_ns = excluded.pulse_at_ns",
+ (
+ str(link.friend_id),
+ link.node_id,
+ link.endpoint,
+ link.peer_display_name,
+ link.state,
+ link.created_at_ns,
+ link.last_seen_ns,
+ link.last_error,
+ link.pulse_json,
+ link.pulse_at_ns,
+ ),
+ )
+ return link
+
+ async def get(self, friend_id: UUID) -> PeerLink | None:
+ async with self._conn.execute(
+ "SELECT friend_id, node_id, endpoint, peer_display_name, state, "
+ "created_at_ns, last_seen_ns, last_error, pulse_json, pulse_at_ns "
+ "FROM friend_peer_links WHERE friend_id = ?",
+ (str(friend_id),),
+ ) as cur:
+ row = await cur.fetchone()
+ return _row_to_link(row) if row is not None else None
+
+ async def get_by_node(self, node_id: str) -> PeerLink | None:
+ async with self._conn.execute(
+ "SELECT friend_id, node_id, endpoint, peer_display_name, state, "
+ "created_at_ns, last_seen_ns, last_error, pulse_json, pulse_at_ns "
+ "FROM friend_peer_links WHERE node_id = ?",
+ (str(node_id),),
+ ) as cur:
+ row = await cur.fetchone()
+ return _row_to_link(row) if row is not None else None
+
+ async def list_all(self) -> list[PeerLink]:
+ async with self._conn.execute(
+ "SELECT friend_id, node_id, endpoint, peer_display_name, state, "
+ "created_at_ns, last_seen_ns, last_error, pulse_json, pulse_at_ns "
+ "FROM friend_peer_links ORDER BY created_at_ns ASC"
+ ) as cur:
+ rows = await cur.fetchall()
+ return [_row_to_link(r) for r in rows]
+
+ async def delete(self, friend_id: UUID) -> None:
+ await self._conn.execute(
+ "DELETE FROM friend_peer_links WHERE friend_id = ?", (str(friend_id),)
+ )
+
+ async def mark_seen(
+ self,
+ friend_id: UUID,
+ *,
+ now_ns: int | None = None,
+ state: PeerLinkState | None = None,
+ ) -> None:
+ """Record a successful exchange; optionally promote the link's state."""
+ stamp = int(now_ns if now_ns is not None else time.time_ns())
+ if state is None:
+ await self._conn.execute(
+ "UPDATE friend_peer_links SET last_seen_ns = ?, last_error = NULL "
+ "WHERE friend_id = ?",
+ (stamp, str(friend_id)),
+ )
+ return
+ await self._conn.execute(
+ "UPDATE friend_peer_links SET last_seen_ns = ?, last_error = NULL, "
+ "state = ? WHERE friend_id = ?",
+ (stamp, state, str(friend_id)),
+ )
+
+ async def mark_error(self, friend_id: UUID, message: str) -> None:
+ await self._conn.execute(
+ "UPDATE friend_peer_links SET last_error = ? WHERE friend_id = ?",
+ (str(message)[:500], str(friend_id)),
+ )
+
+ async def store_pulse(
+ self, friend_id: UUID, pulse: dict[str, Any], *, now_ns: int | None = None
+ ) -> None:
+ stamp = int(now_ns if now_ns is not None else time.time_ns())
+ await self._conn.execute(
+ "UPDATE friend_peer_links SET pulse_json = ?, pulse_at_ns = ?, "
+ "last_seen_ns = ?, last_error = NULL WHERE friend_id = ?",
+ (json.dumps(pulse, ensure_ascii=False), stamp, stamp, str(friend_id)),
+ )
+
+
+class PeerTransport:
+ """Signed HTTP calls to a friend's instance.
+
+ The client is created per call rather than held open: peer traffic is a
+ handful of requests a day, and a long-lived pool to a laptop that is asleep
+ most of the time buys nothing and complicates shutdown.
+ """
+
+ def __init__(
+ self,
+ identity: Any,
+ *,
+ timeout_s: float = PEER_TIMEOUT_S,
+ client_factory: Any | None = None,
+ ) -> None:
+ self._identity = identity
+ self._timeout_s = float(timeout_s)
+ # Tests inject a factory returning a stub client with the same surface;
+ # production leaves it None and gets httpx.
+ self._client_factory = client_factory
+
+ async def hello(
+ self,
+ link: PeerLink,
+ *,
+ display_name: str,
+ endpoint: str | None,
+ ) -> dict[str, Any]:
+ """Introduce this node to the peer and confirm the link both ways."""
+ return await self._post(
+ link,
+ "/api/friends/peer/hello",
+ {"display_name": display_name, "endpoint": endpoint},
+ )
+
+ async def deliver(
+ self,
+ link: PeerLink,
+ *,
+ message_id: str,
+ text: str,
+ created_at_ns: int,
+ ) -> dict[str, Any]:
+ """Push one direct message to the peer's inbox."""
+ return await self._post(
+ link,
+ "/api/friends/peer/inbox",
+ {
+ "message_id": str(message_id),
+ "text": str(text),
+ "created_at_ns": int(created_at_ns),
+ },
+ )
+
+ async def fetch_pulse(self, link: PeerLink) -> dict[str, Any]:
+ """Ask the peer for the usage pulse *they* chose to share with us."""
+ return await self._post(link, "/api/friends/peer/pulse", {})
+
+ # -- internals -------------------------------------------------------
+
+ async def _post(
+ self, link: PeerLink, path: str, body: dict[str, Any]
+ ) -> dict[str, Any]:
+ if link.state == "blocked":
+ raise PeerUnreachable("This friend is blocked.")
+ if not link.endpoint:
+ raise PeerUnreachable(
+ "No address on file for this friend — ask them for an invite "
+ "code that includes one."
+ )
+ envelope = self._identity.seal(body)
+ url = f"{link.endpoint.rstrip('/')}{path}"
+ try:
+ client_cm = self._make_client()
+ async with client_cm as client:
+ response = await client.post(url, json=envelope)
+ except Exception as exc: # noqa: BLE001 — every transport failure is one story
+ raise PeerUnreachable(
+ f"Could not reach {link.endpoint} — is their Jarvis running and "
+ f"reachable from here? ({type(exc).__name__})"
+ ) from exc
+
+ status = int(getattr(response, "status_code", 0))
+ if status == 403:
+ raise PeerUnreachable(
+ "The other instance does not recognise this node — they need to "
+ "accept your invite first."
+ )
+ if status >= 400:
+ raise PeerUnreachable(f"The other instance answered with HTTP {status}.")
+ try:
+ payload = response.json()
+ except Exception: # noqa: BLE001
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+ def _make_client(self) -> Any:
+ if self._client_factory is not None:
+ return self._client_factory()
+ import httpx
+
+ return httpx.AsyncClient(timeout=self._timeout_s, follow_redirects=False)
+
+
+def _row_to_link(row: aiosqlite.Row) -> PeerLink:
+ return PeerLink(
+ friend_id=UUID(row["friend_id"]),
+ node_id=row["node_id"],
+ endpoint=row["endpoint"],
+ peer_display_name=row["peer_display_name"],
+ state=row["state"],
+ created_at_ns=row["created_at_ns"],
+ last_seen_ns=row["last_seen_ns"] or 0,
+ last_error=row["last_error"],
+ pulse_json=row["pulse_json"],
+ pulse_at_ns=row["pulse_at_ns"] or 0,
+ )
+
+
+__all__ = [
+ "PEER_TIMEOUT_S",
+ "PULSE_FRESH_NS",
+ "PeerError",
+ "PeerLink",
+ "PeerLinkState",
+ "PeerLinkStore",
+ "PeerTransport",
+ "PeerUnreachable",
+]
diff --git a/jarvis/friends/profile.py b/jarvis/friends/profile.py
new file mode 100644
index 0000000000..9353f5df49
--- /dev/null
+++ b/jarvis/friends/profile.py
@@ -0,0 +1,151 @@
+"""SocialProfile — the small, deliberate face this instance shows to friends.
+
+Everything a friend can learn about you is either in this file or derived from
+the count-only ledger. That is the point of keeping it separate from the user
+profile the assistant builds (``USER.md``, the people store, the curator): that
+profile exists to make the assistant better and is full of things nobody else
+should see. Reusing it as a social profile would mean every future field added
+for the assistant's benefit becomes a field friends can read.
+
+So the social face is its own, short, hand-written object: a name, one line of
+text, an optional address to reach this instance at, and two switches. Adding
+something to it is a decision someone has to make on purpose.
+
+The two switches are the master controls that sit above the per-friend
+profiles:
+
+``share_pulse``
+ Off means no usage figures leave this machine for anyone, whatever any
+ friend's sharing profile says. A per-friend permission can only ever narrow
+ what this switch allows.
+
+``accept_invites``
+ Off means inbound handshakes are refused. Existing friends keep working;
+ strangers cannot attach themselves to this node.
+
+Stored as JSON next to the activity ledger, atomically, and every read degrades
+to defaults rather than raising.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, ConfigDict, Field
+
+log = logging.getLogger(__name__)
+
+
+class SocialProfile(BaseModel):
+ """What friends see about this instance, plus the two master switches."""
+
+ model_config = ConfigDict(frozen=False)
+
+ display_name: str = Field(default="", max_length=120)
+ tagline: str | None = Field(default=None, max_length=200)
+ #: Where friends can reach this instance. Empty when the machine is not
+ #: reachable from outside — the normal case, and the UI says so plainly.
+ endpoint: str | None = None
+ share_pulse: bool = True
+ accept_invites: bool = True
+
+ def resolved_display_name(self) -> str:
+ """The name to sign invites with, never empty."""
+ name = (self.display_name or "").strip()
+ if name:
+ return name
+ return _fallback_display_name()
+
+
+def default_profile_path() -> Path:
+ """``<user data>/data/socials_profile.json``."""
+ from jarvis.core.paths import user_data_dir
+
+ return Path(user_data_dir()) / "data" / "socials_profile.json"
+
+
+class SocialProfileStore:
+ """Atomic JSON store for :class:`SocialProfile`."""
+
+ def __init__(self, path: Path | str | None = None) -> None:
+ self._path = Path(path) if path is not None else default_profile_path()
+
+ @property
+ def path(self) -> Path:
+ return self._path
+
+ def load(self) -> SocialProfile:
+ try:
+ raw = self._path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return SocialProfile()
+ except OSError as exc:
+ log.warning("socials profile unreadable: %s", exc)
+ return SocialProfile()
+ try:
+ payload = json.loads(raw)
+ except (ValueError, TypeError) as exc:
+ log.warning("socials profile is corrupt, using defaults: %s", exc)
+ return SocialProfile()
+ if not isinstance(payload, dict):
+ return SocialProfile()
+ try:
+ return SocialProfile.model_validate(payload)
+ except Exception: # noqa: BLE001 — a bad field must not lock the section
+ log.warning("socials profile has invalid fields, using defaults")
+ return SocialProfile()
+
+ def save(self, profile: SocialProfile) -> bool:
+ """Write the profile atomically. ``False`` when it could not be stored."""
+ from .identity import _clean_endpoint
+
+ profile.endpoint = _clean_endpoint(profile.endpoint)
+ payload: dict[str, Any] = profile.model_dump()
+ try:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(self._path.parent), prefix=".socials_profile_", suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, ensure_ascii=False, indent=2)
+ os.replace(tmp_name, self._path)
+ except Exception:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+ except Exception: # noqa: BLE001
+ log.warning("could not save the socials profile", exc_info=True)
+ return False
+ return True
+
+ def update(self, **changes: Any) -> SocialProfile:
+ """Apply a partial change and persist it. Unknown keys are ignored."""
+ profile = self.load()
+ for key, value in changes.items():
+ if value is None or key not in SocialProfile.model_fields:
+ continue
+ setattr(profile, key, value)
+ self.save(profile)
+ return profile
+
+
+def _fallback_display_name() -> str:
+ """A neutral name for someone who never set one.
+
+ Deliberately not the OS user name, the machine name, or anything else the
+ system happens to know: those are real identities the user never agreed to
+ publish to somebody else's friends list. An unnamed instance stays unnamed
+ until its owner types a name.
+ """
+ return "Personal Jarvis user"
+
+
+__all__ = ["SocialProfile", "SocialProfileStore", "default_profile_path"]
diff --git a/jarvis/friends/pulse.py b/jarvis/friends/pulse.py
new file mode 100644
index 0000000000..b8ffdee7a9
--- /dev/null
+++ b/jarvis/friends/pulse.py
@@ -0,0 +1,384 @@
+"""UsagePulse — the shareable answer to "how much do you actually use this?".
+
+The product question is social: a friends list where every row reads "no data"
+is not a friends list, it is a contact book. The privacy question is that usage
+data is behavioural data — when someone works, how long, how consistently.
+
+Design
+------
+The pulse resolves that tension with three rules, in this order:
+
+1. **Counts, never content.** Every field is an integer, a small enum, or a
+ coarse level. There is no field that can carry a title, a transcript, a path
+ or an identifier, so no future caller can put one there. The one field that
+ *looks* like a timeline — :attr:`UsagePulse.activity_levels` — carries levels
+ 0–3, not counts, precisely so a friend cannot reconstruct a working day from
+ it.
+2. **Graded by the profile the user already set.** The same
+ ``minimal``/``standard``/``detailed`` choice that governs live status
+ (:mod:`jarvis.friends.status_filter`) governs the pulse. One control, one
+ mental model — a second, separate privacy switch is a switch someone forgets
+ to check.
+3. **Redacted before it leaves.** :func:`redact_pulse` runs on the *sending*
+ side. The receiving instance never has the full pulse to accidentally render,
+ log, or forward.
+
+:data:`PULSE_NEVER` is the counterpart to the status hard blacklist: fields that
+stay unshared no matter which profile is active and no matter what a custom
+whitelist asks for. It exists so the "custom whitelist" escape hatch cannot be
+used to widen the pulse past what the design allows (AP-1/AP-11,
+constraint-self-bypass protection).
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any, Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from .models import StatusProfile
+
+log = logging.getLogger(__name__)
+
+LastActiveBucket = Literal["now", "today", "this_week", "quiet", "unknown"]
+"""How recently the person used their assistant — deliberately coarse.
+
+An exact "last seen" timestamp is a presence tracker; four buckets answer
+"is it worth writing to them right now" without one.
+"""
+
+#: Days of level history a pulse carries. Two weeks is enough for a heat strip
+#: and short enough that it is not a behavioural record.
+PULSE_HISTORY_DAYS = 14
+
+#: Level thresholds for one day of activity. The exact counts stay local.
+_LEVEL_THRESHOLDS: tuple[int, ...] = (1, 3, 7)
+
+#: "Active now" window. Fifteen minutes is a session, not a heartbeat.
+_ACTIVE_NOW_NS = 15 * 60 * 1_000_000_000
+_TODAY_NS = 24 * 60 * 60 * 1_000_000_000
+_THIS_WEEK_NS = 7 * _TODAY_NS
+
+#: Fields released per profile. Cumulative on purpose: "standard" is a superset
+#: of "minimal", so raising the profile can never *remove* something a friend
+#: already sees, which is the only way the levels stay explainable in one line.
+PULSE_FIELDS: dict[StatusProfile, frozenset[str]] = {
+ "minimal": frozenset(
+ {"last_active_bucket", "streak_days", "active_days_30"}
+ ),
+ "standard": frozenset(
+ {
+ "last_active_bucket",
+ "streak_days",
+ "active_days_30",
+ "longest_streak_days",
+ "sessions_today",
+ "sessions_7d",
+ "activity_levels",
+ }
+ ),
+ "detailed": frozenset(
+ {
+ "last_active_bucket",
+ "streak_days",
+ "active_days_30",
+ "longest_streak_days",
+ "sessions_today",
+ "sessions_7d",
+ "activity_levels",
+ "missions_7d",
+ "agent_tasks_7d",
+ "dictated_words_7d",
+ "member_since_days",
+ }
+ ),
+}
+
+#: Never shared, whatever the profile or the custom whitelist says. These are
+#: the fields the local UI shows about *yourself* and that carry more precision
+#: than a friend has any reason to hold.
+PULSE_NEVER: frozenset[str] = frozenset(
+ {
+ "last_active_ns", # exact wall-clock presence
+ "generated_at_ns", # travels in the envelope, not in the payload
+ "node_id",
+ "display_name",
+ }
+)
+
+
+class UsagePulse(BaseModel):
+ """A friend's usage, as far as they chose to share it.
+
+ Fields absent from the sharing profile are ``None`` rather than zero: a
+ person who shares nothing and a person who did nothing must not look the
+ same, or the UI ends up telling a friendly lie about both.
+ """
+
+ model_config = ConfigDict(frozen=False)
+
+ #: Which grade produced this payload. The receiving UI shows it, so an empty
+ #: card reads as "they share little", not as "this feature is broken".
+ profile: StatusProfile = "minimal"
+
+ last_active_bucket: LastActiveBucket = "unknown"
+ streak_days: int | None = None
+ longest_streak_days: int | None = None
+ active_days_30: int | None = None
+ sessions_today: int | None = None
+ sessions_7d: int | None = None
+ missions_7d: int | None = None
+ agent_tasks_7d: int | None = None
+ dictated_words_7d: int | None = None
+ member_since_days: int | None = None
+
+ #: One level per day, oldest first, ``PULSE_HISTORY_DAYS`` long. Values are
+ #: 0–3 activity levels, never counts.
+ activity_levels: list[int] | None = None
+
+ #: Set on the receiving side from the envelope, so a stale card can be
+ #: labelled as stale instead of silently presented as current.
+ fetched_at_ns: int = Field(default=0)
+
+ def is_empty(self) -> bool:
+ """True when the profile released nothing but the bucket."""
+ return all(
+ getattr(self, name) is None
+ for name in (
+ "streak_days",
+ "active_days_30",
+ "sessions_7d",
+ "activity_levels",
+ )
+ )
+
+
+class LocalPulseSources(BaseModel):
+ """What :func:`build_local_pulse` was able to read, for honest degradation.
+
+ A missing dictation sidecar is not an error — it means the user never
+ dictated. The UI needs to tell those two apart, so the flags travel with
+ the pulse locally (they are stripped before sending).
+ """
+
+ model_config = ConfigDict(frozen=False)
+
+ has_activity_ledger: bool = False
+ has_dictation_stats: bool = False
+
+
+def activity_level(total: int) -> int:
+ """One day's total count -> a 0–3 level.
+
+ Bucketing is the whole privacy trick of the heat strip: "level 2" tells a
+ friend the day was busy; it does not tell them you ran eleven missions
+ between 23:00 and 02:00.
+ """
+ value = max(0, int(total or 0))
+ level = 0
+ for threshold in _LEVEL_THRESHOLDS:
+ if value >= threshold:
+ level += 1
+ return level
+
+
+def last_active_bucket(last_active_ns: int, *, now_ns: int | None = None) -> LastActiveBucket:
+ """Coarse recency bucket. ``0`` (never recorded) reads as ``unknown``."""
+ stamp = int(last_active_ns or 0)
+ if stamp <= 0:
+ return "unknown"
+ now = int(now_ns if now_ns is not None else time.time_ns())
+ delta = now - stamp
+ if delta < 0:
+ # A peer's clock ran ahead. Treat it as current rather than as a
+ # negative age that would fall through to "quiet".
+ return "now"
+ if delta <= _ACTIVE_NOW_NS:
+ return "now"
+ if delta <= _TODAY_NS:
+ return "today"
+ if delta <= _THIS_WEEK_NS:
+ return "this_week"
+ return "quiet"
+
+
+def build_local_pulse(
+ *,
+ ledger: Any | None = None,
+ now_ns: int | None = None,
+ member_since_ns: int | None = None,
+) -> tuple[UsagePulse, LocalPulseSources]:
+ """Assemble this instance's own full pulse from the local count stores.
+
+ Never raises: any store that cannot be read contributes nothing and is
+ reported as absent in the returned :class:`LocalPulseSources`.
+ """
+ now = int(now_ns if now_ns is not None else time.time_ns())
+ sources = LocalPulseSources()
+ pulse = UsagePulse(profile="detailed", fetched_at_ns=now)
+
+ days: dict[str, Any] = {}
+ last_active = 0
+ try:
+ from .activity import ActivityLedger
+
+ store = ledger if ledger is not None else ActivityLedger()
+ days, last_active = store.load()
+ sources.has_activity_ledger = bool(days) or last_active > 0
+ current, longest = store.streaks()
+ except Exception: # noqa: BLE001 — a missing ledger is "no activity", never a 500
+ log.debug("socials pulse: activity ledger unavailable", exc_info=True)
+ current, longest = 0, 0
+
+ day_keys = _recent_day_keys(now, PULSE_HISTORY_DAYS)
+ pulse.activity_levels = [
+ activity_level(getattr(days.get(key), "total", 0)) for key in day_keys
+ ]
+ week_keys = day_keys[-7:]
+ pulse.sessions_today = _sum_metric(days, day_keys[-1:], "voice_sessions")
+ pulse.sessions_7d = _sum_metric(days, week_keys, "voice_sessions")
+ pulse.missions_7d = _sum_metric(days, week_keys, "missions")
+ pulse.agent_tasks_7d = _sum_metric(days, week_keys, "agent_tasks")
+ pulse.active_days_30 = _active_days(days, _recent_day_keys(now, 30))
+ pulse.streak_days = current
+ pulse.longest_streak_days = longest
+ pulse.last_active_bucket = last_active_bucket(last_active, now_ns=now)
+
+ words, had_dictation = _dictated_words_7d(week_keys)
+ sources.has_dictation_stats = had_dictation
+ pulse.dictated_words_7d = words
+
+ since = int(member_since_ns or 0) or _first_day_ns(days)
+ if since:
+ pulse.member_since_days = max(0, int((now - since) // _TODAY_NS))
+
+ return pulse, sources
+
+
+def redact_pulse(
+ pulse: UsagePulse,
+ profile: StatusProfile,
+ custom_whitelist: list[str] | None = None,
+) -> UsagePulse:
+ """Return a copy carrying only what ``profile`` releases.
+
+ A ``custom_whitelist`` may widen the profile — it can never reach a field in
+ :data:`PULSE_NEVER`, and it can never invent a field the pulse does not have.
+ Everything else is set to ``None``, which the UI renders as "not shared"
+ rather than as zero.
+ """
+ allowed = PULSE_FIELDS.get(profile)
+ if allowed is None:
+ allowed = PULSE_FIELDS["minimal"]
+ if custom_whitelist:
+ allowed = allowed | frozenset(str(name) for name in custom_whitelist)
+ allowed = allowed - PULSE_NEVER
+
+ out = UsagePulse(profile=profile, fetched_at_ns=pulse.fetched_at_ns)
+ for name in UsagePulse.model_fields:
+ if name in {"profile", "fetched_at_ns"}:
+ continue
+ if name == "last_active_bucket":
+ # The bucket is the one field every profile releases — without it a
+ # friends list cannot tell "quiet" from "not shared" at all, and the
+ # value is already coarse by construction.
+ out.last_active_bucket = pulse.last_active_bucket
+ continue
+ if name in allowed:
+ setattr(out, name, getattr(pulse, name))
+ return out
+
+
+# ----------------------------------------------------------------------
+# Internals
+# ----------------------------------------------------------------------
+
+
+def _recent_day_keys(now_ns: int, count: int) -> list[str]:
+ """The last ``count`` LOCAL day keys, oldest first, ending today."""
+ from datetime import UTC, datetime, timedelta
+
+ try:
+ today = datetime.fromtimestamp(now_ns / 1_000_000_000, tz=UTC).astimezone().date()
+ except (OSError, OverflowError, ValueError, TypeError):
+ today = datetime.now().astimezone().date()
+ span = max(1, int(count))
+ return [(today - timedelta(days=offset)).isoformat() for offset in range(span - 1, -1, -1)]
+
+
+def _first_day_ns(days: dict[str, Any]) -> int:
+ """Epoch-ns of the earliest recorded day — "using this since".
+
+ Derived rather than stored: an install date field would be one more thing
+ to migrate, and the first day someone actually used the assistant is the
+ more honest answer anyway.
+ """
+ if not days:
+ return 0
+ from datetime import date as _date
+ from datetime import datetime
+ from datetime import time as _time
+
+ try:
+ earliest = min(_date.fromisoformat(key) for key in days)
+ except (TypeError, ValueError):
+ return 0
+ try:
+ moment = datetime.combine(earliest, _time.min).astimezone()
+ return int(moment.timestamp() * 1_000_000_000)
+ except (OSError, OverflowError, ValueError):
+ return 0
+
+
+def _sum_metric(days: dict[str, Any], keys: list[str], metric: str) -> int:
+ total = 0
+ for key in keys:
+ day = days.get(key)
+ if day is None:
+ continue
+ total += max(0, int(getattr(day, metric, 0) or 0))
+ return total
+
+
+def _active_days(days: dict[str, Any], keys: list[str]) -> int:
+ return sum(1 for key in keys if getattr(days.get(key), "total", 0) > 0)
+
+
+def _dictated_words_7d(week_keys: list[str]) -> tuple[int, bool]:
+ """Words dictated across the given days, and whether the sidecar existed.
+
+ Imported lazily: this module is read by REST handlers, and the dictation
+ package pulls in the history locks and the cleanup tables.
+ """
+ try:
+ from jarvis.dictation.stats import DictationStats
+
+ stats = DictationStats()
+ if not stats.exists:
+ return 0, False
+ _, days = stats.load()
+ except Exception: # noqa: BLE001 — a missing sidecar is "no words", never a 500
+ log.debug("socials pulse: dictation stats unavailable", exc_info=True)
+ return 0, False
+ total = 0
+ for key in week_keys:
+ day = days.get(key)
+ if day is not None:
+ total += max(0, int(getattr(day, "words", 0) or 0))
+ return total, True
+
+
+__all__ = [
+ "PULSE_FIELDS",
+ "PULSE_HISTORY_DAYS",
+ "PULSE_NEVER",
+ "LastActiveBucket",
+ "LocalPulseSources",
+ "UsagePulse",
+ "activity_level",
+ "build_local_pulse",
+ "last_active_bucket",
+ "redact_pulse",
+]
diff --git a/jarvis/friends/socials.py b/jarvis/friends/socials.py
new file mode 100644
index 0000000000..3260e3d058
--- /dev/null
+++ b/jarvis/friends/socials.py
@@ -0,0 +1,659 @@
+"""Personal Jarvis Socials — the friend-graph service.
+
+Not to be confused with :mod:`jarvis.ui.web.socials_routes`, which is CRUD for
+the *project's* marketing links (``/api/socials``). This module is the people
+side: friends who also run Personal Jarvis, what they let you see of their
+usage, and writing to them. Its HTTP surface lives under ``/api/friends``.
+
+What this service owns
+----------------------
+Everything that has to hold together across the registry, the peer transport,
+the usage pulse, and the local profile. Routes and CLI commands call it; they
+do not re-implement the ordering rules, because those rules are where the
+mistakes are:
+
+- **A message is stored before it is sent.** Delivery failure marks a row
+ undelivered; it never discards what the user typed.
+- **Peer link beats channel.** A friend reachable both directly and by Telegram
+ gets the direct path — it is the one that stays inside the two machines.
+- **Inbound authorisation comes from the signature, never from the body.** A
+ request names a node; that node is looked up in the local link table; an
+ unknown one is refused before anything is stored.
+- **Two gates before a number leaves.** The master ``share_pulse`` switch, then
+ the per-friend profile. Either one saying no is a no.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any
+from uuid import UUID, uuid4
+
+from .identity import InviteError, SocialIdentity, decode_invite
+from .messages import DirectMessage
+from .models import Friend
+from .peer import PeerLink, PeerTransport, PeerUnreachable
+from .profile import SocialProfile, SocialProfileStore
+from .pulse import UsagePulse, build_local_pulse, redact_pulse
+from .registry import FriendNotFoundError, FriendRegistry
+
+log = logging.getLogger(__name__)
+
+#: Cap on a single direct message. Matches the REST body limit so the two
+#: cannot drift into "the API accepted it, the store rejected it".
+MAX_MESSAGE_CHARS = 4096
+
+
+class SocialsError(RuntimeError):
+ """A social action could not be completed, with a message for the user."""
+
+
+class PeerRejected(SocialsError):
+ """An inbound peer request was not authorised. Always answered as 403."""
+
+
+class SocialsService:
+ """The one place the social features are composed.
+
+ Every dependency is injectable so tests can run the whole flow — invite,
+ accept, send, receive, pulse — against two in-memory registries with no
+ network at all.
+ """
+
+ def __init__(
+ self,
+ registry: FriendRegistry,
+ *,
+ identity: SocialIdentity | None = None,
+ profiles: SocialProfileStore | None = None,
+ ledger: Any | None = None,
+ transport: PeerTransport | None = None,
+ ) -> None:
+ self._registry = registry
+ self._identity = identity or SocialIdentity.load_or_create()
+ self._profiles = profiles or SocialProfileStore()
+ self._ledger = ledger
+ self._transport = transport or PeerTransport(self._identity)
+
+ # ------------------------------------------------------------------
+ # This instance
+ # ------------------------------------------------------------------
+
+ @property
+ def identity(self) -> SocialIdentity:
+ return self._identity
+
+ @property
+ def profiles(self) -> SocialProfileStore:
+ return self._profiles
+
+ def profile(self) -> SocialProfile:
+ return self._profiles.load()
+
+ def update_profile(self, **changes: Any) -> SocialProfile:
+ return self._profiles.update(**changes)
+
+ def local_pulse(self) -> UsagePulse:
+ """This instance's own, unredacted pulse — for the owner's own eyes."""
+ pulse, _ = build_local_pulse(ledger=self._ledger)
+ return pulse
+
+ def me(self) -> dict[str, Any]:
+ """Identity + profile + own pulse, as the "this is you" card shows it."""
+ profile = self.profile()
+ pulse, sources = build_local_pulse(ledger=self._ledger)
+ return {
+ "node_id": self._identity.node_id,
+ "short_id": self._identity.short_id,
+ "display_name": profile.resolved_display_name(),
+ "tagline": profile.tagline,
+ "endpoint": profile.endpoint,
+ "share_pulse": profile.share_pulse,
+ "accept_invites": profile.accept_invites,
+ "reachable": bool(profile.endpoint),
+ "pulse": pulse.model_dump(),
+ "sources": sources.model_dump(),
+ }
+
+ # ------------------------------------------------------------------
+ # Invites
+ # ------------------------------------------------------------------
+
+ def create_invite(self, *, endpoint: str | None = None) -> dict[str, Any]:
+ """Mint an invite code for this instance.
+
+ ``endpoint`` overrides the stored one for this code only — useful when
+ someone is on a LAN today and a tunnel tomorrow and does not want that
+ choice written into their profile.
+ """
+ profile = self.profile()
+ address = endpoint if endpoint is not None else profile.endpoint
+ code = self._identity.create_invite(
+ display_name=profile.resolved_display_name(), endpoint=address
+ )
+ return {
+ "code": code,
+ "node_id": self._identity.node_id,
+ "short_id": self._identity.short_id,
+ "display_name": profile.resolved_display_name(),
+ "endpoint": address,
+ # Said plainly rather than implied: a code with no address is still
+ # useful (the other side can be the reachable one), but only one of
+ # the two directions will work, and the user has to know which.
+ "reachable": bool(address),
+ }
+
+ async def accept_invite(
+ self,
+ code: str,
+ *,
+ note: str | None = None,
+ display_name: str | None = None,
+ greet: bool = True,
+ ) -> dict[str, Any]:
+ """Turn an invite code into a friend with a peer link.
+
+ Raises :class:`SocialsError` for a code that does not verify, names this
+ very instance, or belongs to a node that is already a friend — all three
+ are things a person can act on, so they get their own message.
+ """
+ try:
+ invite = decode_invite(code)
+ except InviteError as exc:
+ raise SocialsError(str(exc)) from exc
+
+ if invite.node_id == self._identity.node_id:
+ raise SocialsError("That is your own invite code.")
+
+ existing = await self._registry.peers.get_by_node(invite.node_id)
+ if existing is not None:
+ try:
+ friend = await self._registry.get_friend(existing.friend_id)
+ name = friend.display_name
+ except FriendNotFoundError:
+ name = invite.display_name or "this node"
+ raise SocialsError(f"You are already connected with {name}.")
+
+ friend = Friend(
+ display_name=(display_name or invite.display_name or "Jarvis friend")[:120],
+ note=note,
+ )
+ await self._registry.add_friend(friend)
+ link = PeerLink(
+ friend_id=friend.id,
+ node_id=invite.node_id,
+ endpoint=invite.endpoint,
+ peer_display_name=invite.display_name or None,
+ state="pending",
+ )
+ await self._registry.peers.upsert(link)
+
+ greeting: dict[str, Any] = {"attempted": False, "ok": False, "error": None}
+ if greet and link.can_send:
+ greeting["attempted"] = True
+ try:
+ await self._say_hello(link)
+ greeting["ok"] = True
+ except PeerUnreachable as exc:
+ # A pending link is a perfectly good outcome: the friend exists
+ # locally, and the handshake completes the first time either
+ # side manages to reach the other.
+ greeting["error"] = str(exc)
+ await self._registry.peers.mark_error(friend.id, str(exc))
+
+ stored = await self._registry.peers.get(friend.id)
+ return {
+ "friend": friend,
+ "link": stored or link,
+ "greeting": greeting,
+ }
+
+ async def _say_hello(self, link: PeerLink) -> None:
+ profile = self.profile()
+ await self._transport.hello(
+ link,
+ display_name=profile.resolved_display_name(),
+ endpoint=profile.endpoint,
+ )
+ await self._registry.peers.mark_seen(link.friend_id, state="active")
+
+ # ------------------------------------------------------------------
+ # Overview
+ # ------------------------------------------------------------------
+
+ async def overview(self) -> list[dict[str, Any]]:
+ """One row per friend with everything the social list renders.
+
+ Built with three queries plus one per friend rather than the naive
+ query-per-field: this endpoint is polled while the section is open.
+ """
+ friends = await self._registry.list_friends()
+ unread = await self._registry.messages.unread_counts()
+ links = {str(link.friend_id): link for link in await self._registry.peers.list_all()}
+
+ rows: list[dict[str, Any]] = []
+ for friend in friends:
+ key = str(friend.id)
+ link = links.get(key)
+ channels = await self._registry.channels_for_friend(friend.id)
+ last = await self._registry.messages.last_message(friend.id)
+ permission = await self._registry.get_status_permission(friend.id)
+ pulse = link.pulse() if link is not None else None
+ rows.append(
+ {
+ "id": key,
+ "display_name": friend.display_name,
+ "avatar_url": friend.avatar_url,
+ "note": friend.note,
+ "created_at_ns": friend.created_at_ns,
+ "channels": [c.model_dump(mode="json") for c in channels],
+ "permission_profile": permission.profile,
+ "unread": int(unread.get(key, 0)),
+ "last_message": _preview(last),
+ "peer": _link_summary(link),
+ "pulse": pulse,
+ "pulse_fresh": bool(
+ link is not None and link.pulse_is_fresh()
+ ),
+ "presence": _presence_of(link, pulse),
+ }
+ )
+ return rows
+
+ # ------------------------------------------------------------------
+ # Messaging
+ # ------------------------------------------------------------------
+
+ async def send_message(
+ self,
+ friend_id: UUID,
+ text: str,
+ *,
+ telegram_sender: Any | None = None,
+ ) -> DirectMessage:
+ """Write to a friend by the best route available.
+
+ Returns the stored message. A peer that could not be reached yields a
+ message with ``delivered=False`` rather than an exception — the text is
+ kept and can be retried; only "there is no route at all" is an error.
+ """
+ body = (text or "").strip()
+ if not body:
+ raise SocialsError("An empty message is not sent.")
+ if len(body) > MAX_MESSAGE_CHARS:
+ raise SocialsError(
+ f"That message is longer than {MAX_MESSAGE_CHARS} characters."
+ )
+ await self._registry.get_friend(friend_id) # raises FriendNotFoundError
+
+ link = await self._registry.peers.get(friend_id)
+ if link is not None and link.state == "blocked":
+ raise SocialsError("This friend is blocked.")
+
+ if link is not None and link.can_send:
+ return await self._send_via_peer(link, body)
+
+ channels = await self._registry.channels_for_friend(friend_id)
+ primary = next(
+ (c for c in channels if c.is_primary), channels[0] if channels else None
+ )
+ if primary is not None and primary.channel == "telegram" and telegram_sender is not None:
+ await telegram_sender(primary.handle, body)
+ return await self._registry.messages.add(
+ DirectMessage(
+ friend_id=friend_id,
+ direction="outbound",
+ text=body,
+ channel="telegram",
+ delivered=True,
+ )
+ )
+
+ if primary is not None and primary.channel == "jarvis_pubkey":
+ # A public key alone is an identity, not an address: there is
+ # nowhere to send it. The message is kept and marked undelivered so
+ # the thread stays honest — it becomes deliverable the moment the
+ # friend supplies an invite code carrying an address.
+ return await self._registry.messages.add(
+ DirectMessage(
+ friend_id=friend_id,
+ direction="outbound",
+ text=body,
+ channel="jarvis_pubkey",
+ delivered=False,
+ )
+ )
+
+ if link is not None:
+ raise SocialsError(
+ "No address on file for this friend — ask them for an invite "
+ "code that contains one, or link a Telegram chat."
+ )
+ if primary is not None and primary.channel == "telegram":
+ raise SocialsError(
+ "Telegram is not running, so this message cannot be sent."
+ )
+ raise SocialsError(
+ "This friend has no way to be reached yet. Accept their invite code "
+ "or link a channel first."
+ )
+
+ async def _send_via_peer(self, link: PeerLink, text: str) -> DirectMessage:
+ message = DirectMessage(
+ friend_id=link.friend_id,
+ direction="outbound",
+ text=text,
+ channel="jarvis_link",
+ delivered=False,
+ )
+ await self._registry.messages.add(message)
+ try:
+ await self._transport.deliver(
+ link,
+ message_id=str(message.id),
+ text=text,
+ created_at_ns=message.created_at_ns,
+ )
+ except PeerUnreachable as exc:
+ await self._registry.peers.mark_error(link.friend_id, str(exc))
+ return message
+ await self._registry.messages.mark_delivered(message.id)
+ await self._registry.peers.mark_seen(link.friend_id, state="active")
+ message.delivered = True
+ return message
+
+ async def retry_pending(self, friend_id: UUID) -> dict[str, int]:
+ """Re-attempt every undelivered outbound message of one thread."""
+ link = await self._registry.peers.get(friend_id)
+ pending = await self._registry.messages.pending_outbound(friend_id)
+ if link is None or not link.can_send:
+ return {"pending": len(pending), "delivered": 0}
+ delivered = 0
+ for message in pending:
+ try:
+ await self._transport.deliver(
+ link,
+ message_id=str(message.id),
+ text=message.text,
+ created_at_ns=message.created_at_ns,
+ )
+ except PeerUnreachable as exc:
+ await self._registry.peers.mark_error(friend_id, str(exc))
+ break # the next one will fail the same way
+ await self._registry.messages.mark_delivered(message.id)
+ delivered += 1
+ if delivered:
+ await self._registry.peers.mark_seen(friend_id, state="active")
+ return {"pending": len(pending) - delivered, "delivered": delivered}
+
+ async def mark_read(self, friend_id: UUID) -> int:
+ return await self._registry.messages.mark_read(friend_id)
+
+ # ------------------------------------------------------------------
+ # Pulse exchange
+ # ------------------------------------------------------------------
+
+ async def refresh_pulse(self, friend_id: UUID) -> dict[str, Any]:
+ """Fetch a friend's pulse now and cache it on the link."""
+ link = await self._registry.peers.get(friend_id)
+ if link is None:
+ raise SocialsError(
+ "This friend has no direct link — usage sharing needs one."
+ )
+ if not link.can_send:
+ raise SocialsError(
+ "No address on file for this friend, so their usage cannot be fetched."
+ )
+ try:
+ answer = await self._transport.fetch_pulse(link)
+ except PeerUnreachable as exc:
+ await self._registry.peers.mark_error(friend_id, str(exc))
+ raise SocialsError(str(exc)) from exc
+
+ if not answer.get("shared", True):
+ # An explicit "I share nothing" is information, not an error: cache
+ # it so the card can say so instead of showing a spinner forever.
+ payload = {"shared": False, "profile": answer.get("profile", "minimal")}
+ await self._registry.peers.store_pulse(friend_id, payload)
+ return payload
+
+ raw = answer.get("pulse")
+ if not isinstance(raw, dict):
+ raise SocialsError("The other instance sent an unreadable usage card.")
+ raw["fetched_at_ns"] = time.time_ns()
+ raw["shared"] = True
+ await self._registry.peers.store_pulse(friend_id, raw)
+ await self._registry.peers.mark_seen(friend_id, state="active")
+ return raw
+
+ async def refresh_all_pulses(self) -> dict[str, int]:
+ """Best-effort refresh across every linked friend."""
+ links = await self._registry.peers.list_all()
+ ok = 0
+ failed = 0
+ for link in links:
+ if not link.can_send:
+ continue
+ try:
+ await self.refresh_pulse(link.friend_id)
+ ok += 1
+ except SocialsError:
+ failed += 1
+ return {"refreshed": ok, "failed": failed}
+
+ # ------------------------------------------------------------------
+ # Inbound (called by the peer routes, after signature verification)
+ # ------------------------------------------------------------------
+
+ async def resolve_peer(self, node_id: str) -> tuple[Friend, PeerLink]:
+ """Map a verified node id onto a friend, or refuse.
+
+ This is the authorisation boundary. A node that is not in the link
+ table, or one whose friend row has vanished, gets nothing — the caller
+ turns :class:`PeerRejected` into a 403 with no detail about which of the
+ two it was.
+ """
+ link = await self._registry.peers.get_by_node(node_id)
+ if link is None or link.state == "blocked":
+ raise PeerRejected("Unknown node.")
+ try:
+ friend = await self._registry.get_friend(link.friend_id)
+ except FriendNotFoundError as exc:
+ raise PeerRejected("Unknown node.") from exc
+ return friend, link
+
+ async def handle_hello(self, node_id: str, body: dict[str, Any]) -> dict[str, Any]:
+ """Complete a handshake initiated by the other side.
+
+ Two cases. A node already on file is confirming the link — mark it
+ active and answer. An unknown node is a stranger: accepted only when
+ ``accept_invites`` is on, and then only as a *pending* friend the user
+ still sees and can delete. Nothing here is silent.
+ """
+ profile = self.profile()
+ peer_name = str(body.get("display_name") or "").strip()[:120] or "Jarvis friend"
+ peer_endpoint = _clean(body.get("endpoint"))
+
+ link = await self._registry.peers.get_by_node(node_id)
+ if link is not None:
+ if link.state == "blocked":
+ raise PeerRejected("Unknown node.")
+ link.peer_display_name = peer_name
+ if peer_endpoint:
+ link.endpoint = peer_endpoint
+ link.state = "active"
+ link.last_seen_ns = time.time_ns()
+ link.last_error = None
+ await self._registry.peers.upsert(link)
+ return self._hello_answer(profile, known=True)
+
+ if not profile.accept_invites:
+ raise PeerRejected("Not accepting new links.")
+
+ friend = Friend(
+ display_name=peer_name,
+ note="Reached out to you — accepted automatically.",
+ )
+ await self._registry.add_friend(friend)
+ await self._registry.peers.upsert(
+ PeerLink(
+ friend_id=friend.id,
+ node_id=node_id,
+ endpoint=peer_endpoint,
+ peer_display_name=peer_name,
+ state="active",
+ last_seen_ns=time.time_ns(),
+ )
+ )
+ log.info("socials: accepted a new peer link from %s", node_id[:12])
+ return self._hello_answer(profile, known=False)
+
+ def _hello_answer(self, profile: SocialProfile, *, known: bool) -> dict[str, Any]:
+ return {
+ "ok": True,
+ "known": known,
+ "node_id": self._identity.node_id,
+ "display_name": profile.resolved_display_name(),
+ "endpoint": profile.endpoint,
+ }
+
+ async def handle_inbox(self, node_id: str, body: dict[str, Any]) -> dict[str, Any]:
+ """Store one inbound direct message from a verified peer."""
+ _, link = await self.resolve_peer(node_id)
+ text = str(body.get("text") or "").strip()
+ if not text:
+ raise SocialsError("Empty message.")
+ if len(text) > MAX_MESSAGE_CHARS:
+ text = text[:MAX_MESSAGE_CHARS]
+ remote_id = str(body.get("message_id") or "") or str(uuid4())
+ created = _as_int(body.get("created_at_ns")) or time.time_ns()
+
+ stored = await self._registry.messages.add_once(
+ DirectMessage(
+ friend_id=link.friend_id,
+ direction="inbound",
+ text=text,
+ channel="jarvis_link",
+ created_at_ns=created,
+ delivered=True,
+ remote_id=remote_id,
+ )
+ )
+ await self._registry.peers.mark_seen(link.friend_id, state="active")
+ # A duplicate answers "accepted" too: the sender retried because it did
+ # not hear back, and a 409 would only make it retry again.
+ return {"ok": True, "duplicate": stored is None}
+
+ async def handle_pulse_request(self, node_id: str) -> dict[str, Any]:
+ """Answer a verified peer with the pulse they are allowed to see."""
+ _, link = await self.resolve_peer(node_id)
+ profile = self.profile()
+ permission = await self._registry.get_status_permission(link.friend_id)
+ if not profile.share_pulse:
+ return {"shared": False, "profile": permission.profile}
+ full, _ = build_local_pulse(ledger=self._ledger)
+ shared = redact_pulse(full, permission.profile, permission.custom_whitelist)
+ await self._registry.peers.mark_seen(link.friend_id, state="active")
+ return {"shared": True, "pulse": shared.model_dump(exclude={"fetched_at_ns"})}
+
+ # ------------------------------------------------------------------
+ # Link management
+ # ------------------------------------------------------------------
+
+ async def set_link_state(self, friend_id: UUID, state: str) -> PeerLink:
+ link = await self._registry.peers.get(friend_id)
+ if link is None:
+ raise SocialsError("This friend has no direct link.")
+ if state not in {"pending", "active", "blocked"}:
+ raise SocialsError(f"Unknown link state {state!r}.")
+ link.state = state # type: ignore[assignment]
+ await self._registry.peers.upsert(link)
+ return link
+
+ async def set_link_endpoint(self, friend_id: UUID, endpoint: str | None) -> PeerLink:
+ """Point an existing link at a new address (a friend moved networks)."""
+ link = await self._registry.peers.get(friend_id)
+ if link is None:
+ raise SocialsError("This friend has no direct link.")
+ link.endpoint = _clean(endpoint)
+ link.last_error = None
+ await self._registry.peers.upsert(link)
+ return link
+
+
+# ----------------------------------------------------------------------
+# Helpers
+# ----------------------------------------------------------------------
+
+
+def _preview(message: DirectMessage | None) -> dict[str, Any] | None:
+ """A one-line thread preview. Truncated here, not in the UI, so the API
+ never ships a whole conversation to render forty pixels of text."""
+ if message is None:
+ return None
+ text = message.text
+ return {
+ "direction": message.direction,
+ "text": text[:140] + ("…" if len(text) > 140 else ""),
+ "timestamp_ns": message.created_at_ns,
+ "delivered": message.delivered,
+ }
+
+
+def _link_summary(link: PeerLink | None) -> dict[str, Any] | None:
+ if link is None:
+ return None
+ return {
+ "node_id": link.node_id,
+ "short_id": link.short_id,
+ "endpoint": link.endpoint,
+ "state": link.state,
+ "last_seen_ns": link.last_seen_ns,
+ "last_error": link.last_error,
+ "can_send": link.can_send,
+ }
+
+
+def _presence_of(link: PeerLink | None, pulse: dict[str, Any] | None) -> str:
+ """What the dot next to a friend's name means.
+
+ Presence is the friend's *own* statement about themselves (their pulse
+ bucket), not our observation of them. When they share no bucket we fall
+ back to "when did this link last work", which is honest about being a
+ connection fact rather than a claim about the person.
+ """
+ if isinstance(pulse, dict):
+ bucket = pulse.get("last_active_bucket")
+ if isinstance(bucket, str) and bucket != "unknown":
+ return bucket
+ if link is None:
+ return "unknown"
+ if link.state == "blocked":
+ return "blocked"
+ if link.last_seen_ns <= 0:
+ return "never"
+ from .pulse import last_active_bucket as _bucket
+
+ return _bucket(link.last_seen_ns)
+
+
+def _clean(value: Any) -> str | None:
+ from .identity import _clean_endpoint
+
+ return _clean_endpoint(value)
+
+
+def _as_int(value: Any) -> int:
+ try:
+ return max(0, int(value or 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+__all__ = [
+ "MAX_MESSAGE_CHARS",
+ "PeerRejected",
+ "SocialsError",
+ "SocialsService",
+]
diff --git a/jarvis/missions/subagent_fanout.py b/jarvis/missions/subagent_fanout.py
new file mode 100644
index 0000000000..69d4ed17e8
--- /dev/null
+++ b/jarvis/missions/subagent_fanout.py
@@ -0,0 +1,375 @@
+"""Bounded second-layer sub-agent fan-out for mission workers.
+
+A top-level mission worker (the sub-agent the user spawned) may fan out into
+N parallel child sub-agents, each with its own prompt, and gets every child's
+final answer back as text. This module is the runner that actually spawns and
+drains those children; the model-facing entry is
+``jarvis.plugins.tool.spawn_subagents.SpawnSubagentsTool`` (granted through
+the ADR-0025 worker tool broker).
+
+Exactly TWO layers, enforced structurally, never by prompt:
+
+1. Only top-level mission workers receive the ``spawn_subagents`` grant in
+ their broker binding (``jarvis/missions/init.py``).
+2. Children spawned here get a knowledge-only capability inventory WITHOUT
+ the fan-out tool — the broker refuses the name as "tool not granted".
+3. Child worker ids carry the ``::sub`` marker and the tool refuses any call
+ whose calling worker_id contains it (defense in depth).
+
+Children are WORKERS, not missions: they run through the same worker factory
+and provider routing as the parent (a Claude parent fans out Claude clones, a
+Codex parent Codex clones, …), each in its own plain subdirectory under the
+mission dir — deliberately NOT the parent's git worktree, so ten parallel
+children can never trample one shared checkout. The child's deliverable is its
+final answer text (plus whatever files it wrote in its own directory, whose
+path the parent receives); the parent integrates results in its worktree.
+
+Board + budget visibility ride the existing event vocabulary: each child
+publishes ``WorkerSpawned`` / ``WorkerDraftReady`` / ``WorkerKilled`` on the
+mission event store, so the {name}-Agents board shows the children under the
+mission node and the ``BudgetTracker`` (subscribed to ``WorkerDraftReady``)
+counts their cost against the mission budget with zero extra wiring.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from .events import (
+ EventEnvelope,
+ WorkerDraftReady,
+ WorkerKilled,
+ WorkerSpawned,
+ now_ms,
+)
+from .stream_evidence import extract_stream_evidence
+
+logger = logging.getLogger(__name__)
+
+#: Marker embedded in every child worker id. The fan-out tool refuses callers
+#: whose worker_id contains it — a child can never fan out again (layer wall).
+SUBAGENT_WORKER_MARKER = "::sub"
+
+#: How many children may RUN at the same time. The total per mission is
+#: budgeted by the tool; this only bounds simultaneous subprocesses so a
+#: user-authorized larger fan-out cannot fork-bomb the host.
+_MAX_CONCURRENT_CHILDREN = 10
+
+#: Per-child wall-clock defaults/bounds (seconds). The child timeout is a
+#: worker-internal budget (same contract as the orchestrator's iteration
+#: timeouts); the outer ``asyncio.timeout`` below is the hard backstop.
+DEFAULT_CHILD_TIMEOUT_S = 300
+MIN_CHILD_TIMEOUT_S = 60
+MAX_CHILD_TIMEOUT_S = 900
+_CHILD_TIMEOUT_GRACE_S = 120.0
+
+#: Cap for a single child's answer text inside the aggregated tool result.
+_MAX_CHILD_ANSWER_CHARS = 40_000
+
+
+@dataclass(frozen=True, slots=True)
+class SubagentResult:
+ """One child's terminal outcome, safe to hand back to the parent worker."""
+
+ index: int
+ ok: bool
+ answer: str
+ workspace: str
+ error: str = ""
+ duration_s: float = 0.0
+ cost_usd: float = 0.0
+ tokens_used: int = 0
+
+
+class SubagentFanoutRunner:
+ """Spawns bounded, parallel child workers for one mission.
+
+ Wired once at mission bootstrap (``bootstrap_missions``) with the SAME
+ worker factory / env builder / job factory the Kontrollierer uses, so a
+ child runs on exactly the provider routing the parent did.
+
+ ``worker_factory(step, inventory)`` must accept the capability-inventory
+ override — the runner passes a knowledge-only inventory WITHOUT the
+ fan-out tool, which is what makes the two-layer wall structural.
+ """
+
+ def __init__(
+ self,
+ *,
+ worker_factory: Callable[..., Any],
+ env_builder: Callable[[Path], dict[str, str]],
+ job_factory: Callable[[], Any],
+ isolation_root: Path,
+ manager: Any,
+ child_inventory_builder: Callable[[str], Any],
+ ) -> None:
+ self._worker_factory = worker_factory
+ self._env_builder = env_builder
+ self._job_factory = job_factory
+ self._isolation_root = Path(isolation_root)
+ self._manager = manager
+ self._child_inventory_builder = child_inventory_builder
+
+ async def run(
+ self,
+ *,
+ mission_id: str,
+ prompts: list[str],
+ timeout_s: int = DEFAULT_CHILD_TIMEOUT_S,
+ ) -> list[SubagentResult]:
+ """Run one bounded fan-out round; never raises.
+
+ Every child failure is contained in its own :class:`SubagentResult`
+ so one crashed clone can never take down the siblings or the parent's
+ tool call.
+ """
+ timeout = max(MIN_CHILD_TIMEOUT_S, min(int(timeout_s), MAX_CHILD_TIMEOUT_S))
+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"
+ fanout_root = mission_dir / "subagents"
+ sem = asyncio.Semaphore(_MAX_CONCURRENT_CHILDREN)
+ existing = self._next_child_ordinal(fanout_root)
+
+ async def _guarded(index: int, prompt: str) -> SubagentResult:
+ async with sem:
+ try:
+ return await self._run_child(
+ mission_id=mission_id,
+ mission_dir=mission_dir,
+ ordinal=existing + index,
+ prompt=prompt,
+ timeout_s=timeout,
+ )
+ except Exception as exc: # noqa: BLE001 - one child stays one child
+ logger.exception(
+ "Mission %s: sub-agent %d crashed outside the worker",
+ mission_id,
+ index,
+ )
+ return SubagentResult(
+ index=index,
+ ok=False,
+ answer="",
+ workspace="",
+ error=f"{type(exc).__name__}: {exc}"[:300],
+ )
+
+ results = await asyncio.gather(
+ *(_guarded(i, p) for i, p in enumerate(prompts))
+ )
+ return list(results)
+
+ @staticmethod
+ def _next_child_ordinal(fanout_root: Path) -> int:
+ """First free ``sub-NN`` ordinal, so repeated rounds never collide."""
+ try:
+ taken = [
+ int(p.name[4:])
+ for p in fanout_root.iterdir()
+ if p.is_dir() and p.name.startswith("sub-") and p.name[4:].isdigit()
+ ]
+ except OSError:
+ return 0
+ return (max(taken) + 1) if taken else 0
+
+ async def _run_child(
+ self,
+ *,
+ mission_id: str,
+ mission_dir: Path,
+ ordinal: int,
+ prompt: str,
+ timeout_s: int,
+ ) -> SubagentResult:
+ from .ids import uuid7_str
+ from .kontrollierer.decomposer import Step
+ from .kontrollierer.worker_prompt import compose_worker_prompt
+ from .workers.worker_tool_broker import EmptyWorkerToolBrokerBinding
+
+ started = asyncio.get_running_loop().time()
+ workspace = mission_dir / "subagents" / f"sub-{ordinal:02d}"
+ log_dir = workspace / "logs"
+ log_dir.mkdir(parents=True, exist_ok=True)
+ worker_id = f"{mission_id[:13]}{SUBAGENT_WORKER_MARKER}-{ordinal:02d}"
+
+ step = Step(
+ task_id=uuid7_str(),
+ slug=f"subagent-{ordinal:02d}",
+ prompt=prompt,
+ )
+ # Knowledge-only inventory WITHOUT spawn_subagents: the structural
+ # layer wall. The broker will answer "tool not granted" to any spawn
+ # attempt from this child.
+ inventory = self._child_inventory_builder(prompt)
+ worker = self._worker_factory(step, inventory)
+
+ broker_binding: Any = EmptyWorkerToolBrokerBinding()
+ bind_broker = getattr(inventory, "bind_broker", None)
+ if callable(bind_broker):
+ try:
+ issued = bind_broker(
+ ttl_s=timeout_s + 60.0,
+ mission_id=mission_id,
+ worker_id=worker_id,
+ )
+ if issued is not None:
+ broker_binding = issued
+ except Exception: # noqa: BLE001 - children degrade to tool-less
+ logger.debug(
+ "sub-agent %s: knowledge-tool grant unavailable",
+ worker_id,
+ exc_info=True,
+ )
+
+ child_prompt = compose_worker_prompt(
+ "",
+ (
+ "You are ONE of several parallel sub-agents working on parts "
+ "of a larger task; a coordinating agent will integrate the "
+ "results. Work ONLY inside your assigned working directory. "
+ "Your final message IS your deliverable back to the "
+ "coordinator: end with a complete, self-contained answer "
+ "(plus the relative paths of any files you created).\n\n"
+ f"Your sub-task: {prompt}"
+ ),
+ )
+
+ cost = 0.0
+ tokens = 0
+ error: str | None = None
+ timed_out = False
+ spawned_emitted = False
+ job = self._job_factory()
+ try:
+ async with job:
+ async with asyncio.timeout(timeout_s + _CHILD_TIMEOUT_GRACE_S):
+ async for ev in worker.spawn(
+ child_prompt,
+ worktree=workspace,
+ env=self._env_builder(mission_dir),
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model=step.model,
+ allowed_tools=step.allowed_tools,
+ mission_id=mission_id,
+ _broker_binding=broker_binding,
+ timeout_s=timeout_s,
+ ):
+ if not spawned_emitted:
+ spawned_emitted = True
+ await self._publish(
+ mission_id,
+ WorkerSpawned(
+ worker_id=worker_id,
+ pid=int(getattr(worker, "last_pid", 0) or 0),
+ cli=worker.cli,
+ model=step.model,
+ worktree=str(workspace),
+ ),
+ )
+ ev_cost = getattr(ev, "cost_usd", None)
+ if ev_cost is not None:
+ cost = float(ev_cost)
+ ev_tokens = (
+ getattr(ev, "tokens_used", None)
+ or getattr(ev, "total_tokens", None)
+ or getattr(ev, "num_turns", None)
+ )
+ if ev_tokens is not None:
+ tokens = int(ev_tokens)
+ if getattr(ev, "is_error", False):
+ upstream = (
+ getattr(ev, "result", None)
+ or getattr(ev, "subtype", None)
+ or "worker reported is_error=True"
+ )
+ error = str(upstream)[:300]
+ if getattr(ev, "timed_out", False):
+ timed_out = True
+ except TimeoutError:
+ timed_out = True
+ error = error or f"sub-agent exceeded {timeout_s}s"
+ finally:
+ await broker_binding.aclose()
+
+ duration = asyncio.get_running_loop().time() - started
+ answer = self._read_final_answer(log_dir)
+ ok = error is None and not timed_out and bool(answer.strip())
+ if not ok and error is None:
+ error = (
+ f"sub-agent exceeded {timeout_s}s"
+ if timed_out
+ else "sub-agent produced no final answer"
+ )
+
+ if ok:
+ await self._publish(
+ mission_id,
+ WorkerDraftReady(
+ worker_id=worker_id,
+ artifact_uri=workspace.resolve().as_uri(),
+ diff="",
+ tokens_used=tokens,
+ cost_usd=cost,
+ session_id="",
+ ),
+ )
+ else:
+ await self._publish(
+ mission_id,
+ WorkerKilled(
+ worker_id=worker_id,
+ reason="timeout" if timed_out else "worker_error",
+ error_detail=(error or "")[:300] or None,
+ ),
+ )
+
+ return SubagentResult(
+ index=ordinal,
+ ok=ok,
+ answer=answer[:_MAX_CHILD_ANSWER_CHARS],
+ workspace=str(workspace),
+ error=error or "",
+ duration_s=round(duration, 1),
+ cost_usd=cost,
+ tokens_used=tokens,
+ )
+
+ @staticmethod
+ def _read_final_answer(log_dir: Path) -> str:
+ stream_path = log_dir / "stream.jsonl"
+ try:
+ stream_text = stream_path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return ""
+ return extract_stream_evidence(stream_text).final_answer
+
+ async def _publish(self, mission_id: str, payload: Any) -> None:
+ """Best-effort board/budget event — a publish fault never fails a child."""
+ try:
+ await self._manager.store.append_and_publish(
+ EventEnvelope(
+ mission_id=mission_id,
+ source_actor="worker",
+ ts_ms=now_ms(),
+ payload=payload,
+ )
+ )
+ except Exception: # noqa: BLE001 - visibility is best-effort
+ logger.debug(
+ "sub-agent event publish failed for %s", mission_id, exc_info=True
+ )
+
+
+__all__ = [
+ "DEFAULT_CHILD_TIMEOUT_S",
+ "MAX_CHILD_TIMEOUT_S",
+ "MIN_CHILD_TIMEOUT_S",
+ "SUBAGENT_WORKER_MARKER",
+ "SubagentFanoutRunner",
+ "SubagentResult",
+]
diff --git a/jarvis/plugins/tool/message_agent.py b/jarvis/plugins/tool/message_agent.py
new file mode 100644
index 0000000000..66bc81c5da
--- /dev/null
+++ b/jarvis/plugins/tool/message_agent.py
@@ -0,0 +1,39 @@
+"""The lead's internal messaging hand, sharing the society delivery path."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from jarvis.core.protocols import ToolResult
+from jarvis.plugins.tool.delegate_to_agent import RuntimeResolver
+from jarvis.society.agent_tools import MessageAgentTool
+
+log = logging.getLogger(__name__)
+
+
+class LeadMessageAgentTool:
+ name = "message_agent"
+ risk_tier = "safe"
+ is_action_tool = True
+ schema = MessageAgentTool.schema
+ description = (
+ "Send an INTERNAL chat message to one of the user's Jarvis agents by name or id. "
+ "Use for 'send the Gmail agent a test message': this does NOT send email. "
+ "No extra confirmation is needed for internal messages. For assigning work use "
+ "delegate_to_agent. Report queued, delivered or failed exactly as returned."
+ )
+
+ def __init__(self, *, runtime_resolver: RuntimeResolver) -> None:
+ self._resolve = runtime_resolver
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ try:
+ runtime = self._resolve()
+ if runtime is None:
+ return ToolResult(success=False, output=None, error="society unavailable")
+ await runtime.ensure_started()
+ return await MessageAgentTool(runtime, runtime.lead_id).execute(args, ctx)
+ except Exception as exc: # noqa: BLE001 — return an honest, inspectable tool failure
+ log.warning("message_agent: delivery failed", exc_info=True)
+ return ToolResult(success=False, output=None, error=str(exc))
diff --git a/jarvis/plugins/tool/spawn_subagents.py b/jarvis/plugins/tool/spawn_subagents.py
new file mode 100644
index 0000000000..e45df3d4aa
--- /dev/null
+++ b/jarvis/plugins/tool/spawn_subagents.py
@@ -0,0 +1,297 @@
+"""SpawnSubagentsTool — bounded parallel sub-agent fan-out for mission workers.
+
+The sanctioned exception to the "no spawn tools in worker sets" rule
+(AP-5/AP-14): a TOP-LEVEL mission worker may fan its task out into parallel
+child sub-agents — exactly one extra layer, never more. The legacy recursive
+vehicles (``spawn_worker``, ``multi_spawn``, ``run_skill``) stay forbidden;
+this tool exists precisely so that the one legitimate fan-out shape has a
+guarded door instead of a hole in the fence.
+
+Runaway protection, all deterministic (control flow, not prompts):
+
+* **Layer wall** — children get a broker grant WITHOUT this tool
+ (``SubagentFanoutRunner``), and this tool additionally refuses any caller
+ whose worker_id carries the child marker. Two layers, by construction.
+* **Fan-out budget** — at most :data:`DEFAULT_FANOUT_BUDGET` children per
+ mission, CUMULATIVE across calls, so a looping orchestrator exhausts its
+ budget instead of multiplying. The budget rises only when the USER's own
+ words named a bigger number next to agent vocabulary, and never beyond
+ :data:`ABSOLUTE_FANOUT_CEILING`.
+* **Origin gate** — executes only for broker-brokered mission-worker calls
+ (``tool_origin == "mission_worker"``); the router/realtime surfaces never
+ see the tool at all (it lives on the gateway's worker-only catalog).
+
+Distribution model: the tool blocks until every child finished and returns
+each child's final answer text plus its working directory, so the calling
+worker can integrate the results in its own worktree. Children run on the
+same provider routing as the parent.
+"""
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Callable
+from typing import Any, Final
+
+from jarvis.core.protocols import ExecutionContext, ToolResult
+
+log = logging.getLogger(__name__)
+
+#: Default per-mission fan-out budget (cumulative across calls). Maintainer
+#: mandate 2026-08-14: up to 10 sub-agents unless the user explicitly asked
+#: for more.
+DEFAULT_FANOUT_BUDGET: Final[int] = 10
+
+#: Hard ceiling no request can exceed, user-authorized or not. This is the
+#: bill-shock backstop — a bug that tries to spawn 5 000 clones dies here.
+ABSOLUTE_FANOUT_CEILING: Final[int] = 50
+
+#: Runner resolver — mirrors the spawn_worker lazy-resolver pattern (AD-OC1):
+#: the fan-out runner is built by the mission bootstrap AFTER the brain.
+RunnerResolver = Callable[[], Any | None]
+
+#: A number the USER spoke next to agent vocabulary ("20 subagents",
+#: "spawne 25 Agenten", "15 workers"). Both orders, bounded gap, digits only —
+#: deterministic, judged on the user's words (mirrors the spawn-gate
+#: philosophy), never on the model's paraphrase.
+_USER_COUNT_RE: Final[re.Pattern[str]] = re.compile(
+ r"(?:\b(\d{1,3})\b[^\d\n]{0,40}?"
+ r"(?:sub-?agent|agent|worker|clone|klon|instanz|instance)"
+ r"|(?:sub-?agent|agent|worker|clone|klon|instanz|instance)\w*"
+ r"[^\d\n]{0,25}?\b(\d{1,3})\b)",
+ re.IGNORECASE,
+)
+
+
+def user_authorized_fanout(user_text: str) -> int:
+ """Largest child count the user's own words authorize, floor = default.
+
+ Returns :data:`DEFAULT_FANOUT_BUDGET` when no explicit number is present,
+ and never more than :data:`ABSOLUTE_FANOUT_CEILING`.
+ """
+ best = DEFAULT_FANOUT_BUDGET
+ for match in _USER_COUNT_RE.finditer(user_text or ""):
+ raw = match.group(1) or match.group(2)
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ continue
+ best = max(best, value)
+ return min(best, ABSOLUTE_FANOUT_CEILING)
+
+
+class SpawnSubagentsTool:
+ """Fan a mission out into parallel child sub-agents (one layer only)."""
+
+ name: str = "spawn_subagents"
+ risk_tier: str = "monitor"
+ # The description doubles as the orchestration hint — CLI workers read
+ # tool capabilities from the broker's tool listing, so this is the one
+ # text every backend is guaranteed to see (ADR-0011: models pick tools by
+ # description).
+ description: str = (
+ "Fan your task out into parallel sub-agents (max 10 per mission "
+ "unless the user explicitly asked for more). Use this DELIBERATELY, "
+ "and only when the task genuinely splits into independent parts that "
+ "benefit from parallel work (research angles, per-module analysis, "
+ "content sections) — never for a step you can just do yourself, and "
+ "never in a loop. You are the coordinator: write each prompt fully "
+ "self-contained (a sub-agent shares none of your context), then "
+ "integrate the returned answers yourself. The call blocks until all "
+ "sub-agents finish and returns each one's final answer text plus its "
+ "working directory (copy any files you need from there into your own "
+ "workspace). Sub-agents cannot spawn further sub-agents."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "prompts": {
+ "type": "array",
+ "items": {"type": "string"},
+ "minItems": 1,
+ "maxItems": ABSOLUTE_FANOUT_CEILING,
+ "description": (
+ "One complete, self-contained task instruction per "
+ "sub-agent. Include every fact the sub-agent needs — it "
+ "cannot see your conversation, your files, or the other "
+ "sub-agents. Keep it to at most 10 prompts unless the "
+ "user explicitly requested a larger number."
+ ),
+ },
+ "timeout_s": {
+ "type": "integer",
+ "default": 300,
+ "minimum": 60,
+ "maximum": 900,
+ "description": (
+ "Per-sub-agent time budget in seconds (default 300)."
+ ),
+ },
+ },
+ "required": ["prompts"],
+ }
+
+ def __init__(
+ self,
+ *,
+ runner: Any | None = None,
+ runner_resolver: RunnerResolver | None = None,
+ ) -> None:
+ if runner is None and runner_resolver is None:
+ raise ValueError(
+ "SpawnSubagentsTool requires either 'runner' or 'runner_resolver'"
+ )
+ self._runner = runner
+ self._runner_resolver = runner_resolver
+ # Cumulative children per mission_id — the loop guard. Process-local
+ # is correct here: the runner lives in the same process, and a fresh
+ # app start means fresh missions.
+ self._spawned_per_mission: dict[str, int] = {}
+
+ def _resolve_runner(self) -> Any | None:
+ if self._runner is not None:
+ return self._runner
+ if self._runner_resolver is not None:
+ return self._runner_resolver()
+ return None
+
+ async def execute(
+ self, args: dict[str, Any], ctx: ExecutionContext
+ ) -> ToolResult:
+ from jarvis.missions.subagent_fanout import (
+ DEFAULT_CHILD_TIMEOUT_S,
+ MAX_CHILD_TIMEOUT_S,
+ MIN_CHILD_TIMEOUT_S,
+ SUBAGENT_WORKER_MARKER,
+ )
+
+ origin = str(ctx.config.get("tool_origin") or "")
+ if origin != "mission_worker":
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ "spawn_subagents is only available to mission workers "
+ "through the supervisor tool broker."
+ ),
+ )
+ mission_id = str(ctx.config.get("mission_id") or "").strip()
+ worker_id = str(ctx.config.get("worker_id") or "")
+ if not mission_id:
+ return ToolResult(
+ success=False, output=None, error="missing mission attribution"
+ )
+ if SUBAGENT_WORKER_MARKER in worker_id:
+ # Layer wall, second line of defense (the first is the child's
+ # grant, which does not contain this tool at all).
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ "Depth limit: you are already a sub-agent. Sub-agents "
+ "cannot spawn further sub-agents — do this part of the "
+ "work yourself."
+ ),
+ )
+
+ prompts = [
+ p.strip()
+ for p in (args.get("prompts") or [])
+ if isinstance(p, str) and p.strip()
+ ]
+ if not prompts:
+ return ToolResult(
+ success=False, output=None, error="prompts must not be empty"
+ )
+
+ budget = user_authorized_fanout(ctx.user_utterance)
+ already = self._spawned_per_mission.get(mission_id, 0)
+ remaining = budget - already
+ if len(prompts) > remaining:
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ f"Fan-out budget exceeded: this mission may start "
+ f"{budget} sub-agents in total ({already} already used, "
+ f"{max(remaining, 0)} left), and only an explicit user "
+ f"request for a larger number raises the limit. Reduce "
+ f"the batch or consolidate prompts — do not retry in a "
+ f"loop."
+ ),
+ )
+
+ runner = self._resolve_runner()
+ if runner is None:
+ return ToolResult(
+ success=False,
+ output=None,
+ error="sub-agent fan-out is not available in this session",
+ )
+
+ try:
+ raw_timeout = int(args.get("timeout_s") or DEFAULT_CHILD_TIMEOUT_S)
+ except (TypeError, ValueError):
+ raw_timeout = DEFAULT_CHILD_TIMEOUT_S
+ timeout_s = max(MIN_CHILD_TIMEOUT_S, min(raw_timeout, MAX_CHILD_TIMEOUT_S))
+
+ # Reserve the budget BEFORE the first await so two concurrent calls
+ # from one worker cannot both pass the check (same synchronous-arm
+ # discipline as the spawn_worker cooldown gate).
+ self._spawned_per_mission[mission_id] = already + len(prompts)
+ log.info(
+ "Mission %s: fanning out %d sub-agent(s) (budget %d, used %d)",
+ mission_id,
+ len(prompts),
+ budget,
+ already + len(prompts),
+ )
+ try:
+ results = await runner.run(
+ mission_id=mission_id,
+ prompts=prompts,
+ timeout_s=timeout_s,
+ )
+ except Exception as exc: # noqa: BLE001 - the parent must get an answer
+ log.exception("Mission %s: sub-agent fan-out crashed", mission_id)
+ return ToolResult(
+ success=False,
+ output=None,
+ error=f"sub-agent fan-out failed: {type(exc).__name__}: {exc}",
+ )
+
+ ok_count = sum(1 for r in results if r.ok)
+ sections = []
+ for pos, r in enumerate(results, start=1):
+ head = f"--- Sub-agent {pos}/{len(results)} "
+ head += "(ok" if r.ok else f"(FAILED: {r.error or 'unknown'}"
+ head += f", {r.duration_s:.0f}s) — workspace: {r.workspace}"
+ sections.append(f"{head}\n{r.answer or '(no answer)'}")
+ return ToolResult(
+ success=ok_count > 0,
+ output={
+ "subagents_total": len(results),
+ "subagents_ok": ok_count,
+ "budget_remaining": budget - self._spawned_per_mission[mission_id],
+ "combined": "\n\n".join(sections),
+ "results": [
+ {
+ "index": r.index,
+ "ok": r.ok,
+ "workspace": r.workspace,
+ "error": r.error,
+ "duration_s": r.duration_s,
+ }
+ for r in results
+ ],
+ },
+ error=None if ok_count > 0 else "every sub-agent failed",
+ )
+
+
+__all__ = [
+ "ABSOLUTE_FANOUT_CEILING",
+ "DEFAULT_FANOUT_BUDGET",
+ "SpawnSubagentsTool",
+ "user_authorized_fanout",
+]
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index b292d17009..44ef01d176 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -3152,6 +3152,11 @@ class RealtimeVoiceSession:
return (
"[Agent society — the user's own agents, live right now]\n"
f"Agents on the user's team: {roster}.\n"
+ "To send a message TO an agent, use message_agent (target, text), or "
+ "ask jarvis_action to use message_agent if it is not directly available. "
+ "This is an internal chat message, not an email: never use gmail or "
+ "another external messaging connector for it. Internal messages need "
+ "no extra confirmation. Use delegate_to_agent only for assigning work. "
"Those are the user's OWN AGENTS from the Agents section (each with "
"its own chat, tools and instructions) — not people you know, not "
"coding terminals, and not the retired sub-agent system. When the "
@@ -4216,6 +4221,21 @@ class RealtimeVoiceSession:
muted_s,
)
+ def _grounded_confirmation(self, transcript: str) -> bool:
+ """Keep a real answer captured after playback out of fuzzy echo matching."""
+ from jarvis.voice.echo_confirmation import classify_response
+
+ bridge = self._tool_bridge
+ if bridge is None or not bridge.has_pending_confirmation:
+ return False
+ stamp = self._last_voiced_input_monotonic
+ now = time.monotonic()
+ horizon = self._echo_playback_horizon
+ return bool(
+ stamp > 0 and stamp > horizon and 0 <= now - stamp <= 8.0
+ and classify_response(transcript, language=self._language) in {"confirm", "veto"}
+ )
+
def _user_is_speaking(self) -> bool:
"""True while the microphone still carries the user's voice.
@@ -4932,7 +4952,7 @@ class RealtimeVoiceSession:
# One strict judgment per barge capture: consume the
# window so later ordinary short answers are exempt.
self._local_barge_short_echo_until = 0.0
- if self._echo_guard.is_echo(
+ if not self._grounded_confirmation(transcript) and self._echo_guard.is_echo(
echo_probe, judge_short=judge_short
):
log.info(
diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.py
index fb2358ff82..d6f6f11da4 100644
--- a/jarvis/realtime/tools.py
+++ b/jarvis/realtime/tools.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import hashlib
import json
import logging
@@ -527,6 +528,10 @@ class RealtimeToolBridge:
self._wire_to_name: dict[str, str] = {}
self._declarations: tuple[dict[str, Any], ...] = self._build_declarations()
self._pending: _PendingConfirmation | None = None
+ self._execution_lock = asyncio.Lock()
+ self._confirmed_receipt: tuple[str, dict[str, Any]] | None = None
+ self._confirmed_user_text = ""
+ self._confirmed_arguments: dict[str, Any] = {}
self._vetoed_tool = ""
self._last_user_text = ""
@@ -767,7 +772,18 @@ class RealtimeToolBridge:
self._declarations = self._build_declarations()
return self._declarations != previous_declarations
+ @property
+ def has_pending_confirmation(self) -> bool:
+ return self._pending is not None
+
async def handle_user_transcript(self, text: str) -> None:
+ # Duplicate final transcripts and repeated affirmations still refer to
+ # the same approved action. A new request releases the receipt.
+ if (
+ text != self._last_user_text
+ and classify_response(text, language=self._language) != "confirm"
+ ):
+ self._confirmed_receipt = None
self._last_user_text = text
self._vetoed_tool = ""
pending = self._pending
@@ -782,6 +798,25 @@ class RealtimeToolBridge:
self._pending = None
async def execute(
+ self, *, wire_name: str, arguments: dict[str, Any], trace_id: UUID | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ # Provider retries can overlap a slow execute_confirmed. Serialize the
+ # check and execution so a second call cannot create another approval.
+ async with self._execution_lock:
+ name = self._declared_name_for_wire(wire_name)
+ receipt = self._confirmed_receipt
+ if receipt is not None and receipt[0] == name:
+ if (
+ self._last_user_text == self._confirmed_user_text
+ or arguments == self._confirmed_arguments
+ ):
+ return name, dict(receipt[1])
+ self._confirmed_receipt = None
+ return await self._execute_once(
+ wire_name=wire_name, arguments=arguments, trace_id=trace_id
+ )
+
+ async def _execute_once(
self,
*,
wire_name: str,
@@ -790,6 +825,18 @@ class RealtimeToolBridge:
) -> tuple[str, dict[str, Any]]:
name = self._declared_name_for_wire(wire_name)
name, arguments = self._maybe_reroute_music(name, arguments)
+ if name == "gmail":
+ from jarvis.society.lead_card import society_agent_names
+ from jarvis.society.message_routing import is_internal_message_request
+
+ if is_internal_message_request(self._last_user_text, society_agent_names()):
+ return name, {
+ "success": False, "blocked": True,
+ "error": "This request addresses an internal agent. Use message_agent "
+ "with the teammate's name and message; do not send email or ask for "
+ "email approval.",
+ }
+
descriptor = self._descriptors.get(name)
if descriptor is None:
await self._publish_denied(wire_name, "unknown realtime tool")
@@ -834,11 +881,15 @@ class RealtimeToolBridge:
}
result = await self._execute_confirmed(pending.trace_id)
self._pending = None
- return name, _bounded_result(
+ response = _bounded_result(
bool(getattr(result, "success", False)),
getattr(result, "output", None),
getattr(result, "error", None),
)
+ self._confirmed_receipt = (name, response)
+ self._confirmed_user_text = self._last_user_text
+ self._confirmed_arguments = dict(arguments)
+ return name, response
trace_id = trace_id or uuid4()
result = await self._execute_tool(name, arguments, trace_id)
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index 6c074ea73b..f5e70b4865 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -27,6 +27,7 @@ from typing import Any, Final
from jarvis.core.protocols import ToolResult
+from .delivery import incoming_context
from .events import MsgType
from .failure_reasons import FailureReason, retry_action
from .memory import MemoryRefused
@@ -74,7 +75,7 @@ class MessageAgentTool:
"""Send one message to ONE teammate. Fire-and-forget."""
name: str = MESSAGE_TOOL_NAME
- risk_tier: str = "monitor"
+ risk_tier: str = "safe"
description: str = (
"Send a message to ONE teammate in your agent society. Compose the message "
"yourself — never forward another message verbatim — and address the one "
@@ -118,6 +119,16 @@ class MessageAgentTool:
caller = await rt.roster.get(self._agent_id)
if caller is None or caller.state is not AgentState.ACTIVE:
return _failure(FailureReason.BLOCKED_BY_POLICY, "caller is not an active agent")
+ if any(
+ name in caller.denies
+ for name in (
+ MESSAGE_TOOL_NAME,
+ "message_agent",
+ "core:message_agent",
+ "core:society_message_agent",
+ )
+ ):
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "internal messaging is disabled")
target_key = str(args.get("target", "")).strip()
text = str(args.get("text", "")).strip()[:_MAX_TEXT]
if not target_key or not text:
@@ -137,7 +148,8 @@ class MessageAgentTool:
payload: dict[str, Any] = {}
if isinstance(refs, list) and refs:
payload["refs"] = [str(r) for r in refs][:20]
- trace_id = f"chat:{caller.agent_id}:{target.agent_id}"
+ incoming = incoming_context.get()
+ trace_id = incoming.trace_id if incoming is not None else None
env = await rt.say(
from_agent=caller.agent_id,
to_agent=target.agent_id,
@@ -145,10 +157,15 @@ class MessageAgentTool:
trace_id=trace_id,
msg_type=msg_type,
payload=payload,
+ parent_event_id=incoming.message_id if incoming is not None else None,
)
+ status = await rt.store.delivery_status(env.event_id)
return ToolResult(
- success=True,
+ success=status != "failed",
+ error="Internal message delivery failed" if status == "failed" else None,
output={
+ "status": status,
+ "message_id": env.event_id,
"delivered_to": target.name,
"kind": kind,
"seq": env.seq,
diff --git a/jarvis/society/capabilities.py b/jarvis/society/capabilities.py
index 35e1515510..25fadc533e 100644
--- a/jarvis/society/capabilities.py
+++ b/jarvis/society/capabilities.py
@@ -61,6 +61,8 @@ NEVER_GRANTED: Final[frozenset[str]] = frozenset(
"reveal-key-preview",
"profile-update",
"society_message_agent",
+ "message_agent",
+ "message-agent",
}
)
diff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.py
index 4062cf63b7..c439d14940 100644
--- a/jarvis/society/chat_binding.py
+++ b/jarvis/society/chat_binding.py
@@ -22,8 +22,9 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any, Final
+from .delivery import DeliveryBusy, IncomingMessage, incoming_context
from .events import MsgType, SocietyEnvelope
-from .roster import AgentRecord, PermissionCeiling
+from .roster import LEAD_AGENT_ID, AgentRecord, PermissionCeiling
from .scheduler import DeliverHook
log = logging.getLogger(__name__)
@@ -155,15 +156,61 @@ def make_deliver_hook(
) -> DeliverHook:
"""The scheduler's deliver hook over the agent-chat service."""
- async def _deliver(target: AgentRecord, env: SocietyEnvelope) -> None:
+ async def _receive(
+ target: AgentRecord, env: SocietyEnvelope
+ ) -> tuple[Any, Any, IncomingMessage]:
svc = get_service()
if svc is None:
- raise RuntimeError("agent chat service unavailable: message stays in the inbox")
- cfg = get_cfg()
- session = ensure_session(svc, cfg, target)
- if svc.is_running(session.session_id):
- raise RuntimeError(f"target busy: {target.name} is running a turn")
- sender = resolve_name(env.from_agent) if resolve_name else env.from_agent
- await svc.send(session.session_id, frame_incoming(env, sender))
+ raise DeliveryBusy("agent chat service unavailable: message stays in the inbox")
+ if resolve_name is not None:
+ sender = resolve_name(env.from_agent)
+ else:
+ from .runtime import current_runtime
+
+ runtime = current_runtime()
+ record = await runtime.roster.get(env.from_agent) if runtime is not None else None
+ sender = record.name if record is not None else env.from_agent
+ incoming = IncomingMessage(
+ message_id=env.event_id,
+ sender_id=env.from_agent,
+ sender_name=sender,
+ sender_kind=("jarvis" if env.from_agent == LEAD_AGENT_ID else "user" if env.from_agent == "user" else "agent"),
+ text=env.text,
+ prompt=frame_incoming(env, sender),
+ trace_id=env.trace_id,
+ )
+ if target.agent_id == LEAD_AGENT_ID:
+ sessions = svc.store.list_sessions(limit=1, surface="jarvis")
+ if not sessions:
+ raise DeliveryBusy("Jarvis chat is not open yet")
+ session = sessions[0]
+ else:
+ session = ensure_session(svc, get_cfg(), target)
+ await svc.receive_message(session.session_id, incoming)
+ return svc, session, incoming
+ async def _deliver(target: AgentRecord, env: SocietyEnvelope) -> None:
+ svc, session, incoming = await _receive(target, env)
+ if target.agent_id == LEAD_AGENT_ID:
+ receipt = svc.store.incoming_message(session.session_id, env.event_id)
+ if receipt is not None and receipt["status"] != "delivered":
+ await svc.message_status(session.session_id, env.event_id, "delivered")
+ return
+ receipt = svc.store.incoming_message(session.session_id, env.event_id)
+ if receipt is not None and receipt["status"] == "delivered":
+ return
+ if svc.is_running(session.session_id):
+ raise DeliveryBusy(f"target busy: {target.name} is running a turn")
+ token = incoming_context.set(incoming)
+ try:
+ from jarvis.agent_chat.service import SessionBusy
+
+ await svc.send(session.session_id, incoming.prompt, incoming=incoming)
+ except SessionBusy as exc:
+ raise DeliveryBusy(str(exc)) from exc
+ finally:
+ incoming_context.reset(token)
+
+ # The scheduler can project later FIFO entries without starting their turns.
+ setattr(_deliver, "receive", _receive) # noqa: B010 — optional callable capability
return _deliver
diff --git a/jarvis/society/delivery.py b/jarvis/society/delivery.py
new file mode 100644
index 0000000000..2dfa72c9dc
--- /dev/null
+++ b/jarvis/society/delivery.py
@@ -0,0 +1,36 @@
+"""Trusted provenance for internal chat messages and their delivery receipts."""
+
+from __future__ import annotations
+
+from contextvars import ContextVar
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict
+
+
+class IncomingMessage(BaseModel):
+ """Persisted chat payload; callers cannot choose this through the public API."""
+
+ model_config = ConfigDict(frozen=True, extra="forbid")
+
+ message_id: str
+ sender_id: str
+ sender_name: str
+ sender_kind: Literal["jarvis", "agent", "user"]
+ text: str
+ prompt: str
+ trace_id: str
+ status: Literal["queued", "delivered", "failed"] = "queued"
+ turn_id: str = ""
+ error: str = ""
+
+
+# asyncio tasks inherit this context when a receiving turn is started. No
+# model argument or REST body can select a sender or a conversation trace.
+incoming_context: ContextVar[IncomingMessage | None] = ContextVar(
+ "society_incoming_message", default=None
+)
+
+
+class DeliveryBusy(RuntimeError):
+ """The canonical chat is occupied; keep the envelope in the durable queue."""
diff --git a/jarvis/society/lead_card.py b/jarvis/society/lead_card.py
index 3cc34e1f13..0794a7d33d 100644
--- a/jarvis/society/lead_card.py
+++ b/jarvis/society/lead_card.py
@@ -58,6 +58,9 @@ def _rule_block(lead_name: str) -> str:
"listed below live in the Agents section, each with its own chat, its own tools "
"and its own standing instructions. When the user says \"agent\", \"my agents\" "
"or \"the team\", they mean THESE agents.\n"
+ "- Send internal messages with message_agent (target, text). A message TO an email "
+ "specialist is not email: never call gmail for this. Internal messages need no extra "
+ "confirmation. Report the actual queued/delivered/failed receipt.\n"
"- Hand work to an agent with delegate_to_agent (the agent's name and the task in "
"full). The agent works in the background; you acknowledge now and its result "
"comes back to this conversation.\n"
diff --git a/jarvis/society/message_routing.py b/jarvis/society/message_routing.py
new file mode 100644
index 0000000000..eb727da41e
--- /dev/null
+++ b/jarvis/society/message_routing.py
@@ -0,0 +1,27 @@
+"""Disambiguate an internal addressee from an external messaging connector."""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+
+
+def is_internal_message_request(text: str, agent_names: Iterable[str]) -> bool:
+ """Require both a message request and a named teammate, not just 'Gmail'."""
+ norm = text.casefold()
+ if not re.search(r"\b(message|nachricht|testnachricht|mensaje)\w*\b", norm): # i18n-allow: speech-input vocabulary
+ return False
+ if not re.search(
+ r"\b(send|write|tell|schreib\w*|sende?\w*|schick\w*|env[ií]\w*|escrib\w*)\b", norm
+ ):
+ return False
+ for name in agent_names:
+ words = re.findall(r"\w+", name.casefold())
+ if not words:
+ continue
+ pattern = r"\s+".join(
+ r"agent(?:en|s|e)?" if word == "agent" else re.escape(word) for word in words
+ )
+ if re.search(r"\b" + pattern + r"\b", norm):
+ return True
+ return False
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index 0dc467d09a..a16c9719d5 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -22,6 +22,7 @@ import logging
from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
from typing import Any
+from uuid import uuid4
from .approvals import Approvals
from .bridge import MissionBridge
@@ -153,35 +154,65 @@ class SocietyRuntime:
creator_factory=default_creator_factory(self._get_cfg),
notify=self._notify_chat,
)
+ self._start_lock = asyncio.Lock()
+ self._delivery_task: asyncio.Task[None] | None = None
+ self._delivery_unsubscribe: Callable[[], None] | None = None
self._started = False
# ------------------------------------------------------------ lifecycle
async def ensure_started(self) -> SocietyRuntime:
- if self._started:
+ async with self._start_lock:
+ if self._started:
+ return self
+ await self.store.open()
+ self.scheduler._budget = self._get_budget() # noqa: SLF001 — the runtime owns its scheduler
+ self.scheduler.attach()
+ self._delivery_unsubscribe = self.store.bus.subscribe_all(self._delivery_failed)
+ bus = self._get_mission_bus()
+ if bus is not None:
+ self.bridge.attach(bus)
+ self.checkpoints.attach()
+ self.quests.attach()
+ self.world_feed.attach()
+ await self.seed_lead()
+ if self._seed_starter_team:
+ created = await seed_first_run(self.roster, self.store)
+ if created:
+ log.info("society: starter team seeded: %s", ", ".join(created))
+ # Warm the roster snapshot so the lead card (lead_card.py) — a
+ # synchronous reader on the brain's prompt build — sees the team from
+ # the first turn, not from the first REST listing.
+ await self.roster.refresh()
+ self._started = True
+ self._delivery_task = asyncio.create_task(self._deliver_pending())
+ set_current_runtime(self)
+ log.info("society runtime started (%s)", self.store.path)
return self
- await self.store.open()
- self.scheduler._budget = self._get_budget() # noqa: SLF001 — the runtime owns its scheduler
- self.scheduler.attach()
- bus = self._get_mission_bus()
- if bus is not None:
- self.bridge.attach(bus)
- self.checkpoints.attach()
- self.quests.attach()
- self.world_feed.attach()
- await self.seed_lead()
- if self._seed_starter_team:
- created = await seed_first_run(self.roster, self.store)
- if created:
- log.info("society: starter team seeded: %s", ", ".join(created))
- # Warm the roster snapshot so the lead card (lead_card.py) — a
- # synchronous reader on the brain's prompt build — sees the team from
- # the first turn, not from the first REST listing.
- await self.roster.refresh()
- self._started = True
- set_current_runtime(self)
- log.info("society runtime started (%s)", self.store.path)
- return self
+
+ async def _delivery_failed(self, env: SocietyEnvelope) -> None:
+ """Project a terminal scheduler veto onto an already-visible chat receipt."""
+ if env.msg_type is not MsgType.VETO or not env.parent_event_id:
+ return
+ svc = self._get_chat()
+ if svc is None:
+ return
+ for original in await self.store.events_for_trace(env.trace_id):
+ if original.event_id != env.parent_event_id or not original.to_agent:
+ continue
+ session_id = f"society:{original.to_agent}"
+ if svc.store.incoming_message(session_id, original.event_id) is not None:
+ await svc.message_status(session_id, original.event_id, "failed", error=env.text)
+ break
+
+ async def _deliver_pending(self) -> None:
+ """Recover committed messages and retry busy chats without opening sockets."""
+ while True:
+ try:
+ await self.scheduler.drain_deliveries()
+ except Exception: # noqa: BLE001 — one failed pass must not lose the queue
+ log.warning("society: delivery recovery failed", exc_info=True)
+ await asyncio.sleep(1.0)
@property
def data_dir(self) -> Path:
@@ -196,6 +227,13 @@ class SocietyRuntime:
return self._get_cfg()
async def close(self) -> None:
+ if self._delivery_task is not None:
+ self._delivery_task.cancel()
+ await asyncio.gather(self._delivery_task, return_exceptions=True)
+ self._delivery_task = None
+ if self._delivery_unsubscribe is not None:
+ self._delivery_unsubscribe()
+ self._delivery_unsubscribe = None
await self.browser.close()
for task in list(self._watchers):
task.cancel()
@@ -597,6 +635,7 @@ class SocietyRuntime:
trace_id: str | None = None,
msg_type: MsgType = MsgType.SAY,
payload: dict[str, Any] | None = None,
+ parent_event_id: str | None = None,
) -> SocietyEnvelope:
"""Append one envelope on behalf of ``from_agent`` (REST, user, tests)."""
body = dict(payload or {})
@@ -606,8 +645,9 @@ class SocietyRuntime:
msg_type=msg_type,
from_agent=from_agent,
to_agent=to_agent,
- trace_id=trace_id or f"chat:{from_agent}:{to_agent}",
+ trace_id=trace_id or f"chat:{uuid4().hex}",
payload=body,
+ parent_event_id=parent_event_id,
)
)
diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.py
index 6b2577c866..b467ba1ccc 100644
--- a/jarvis/society/scheduler.py
+++ b/jarvis/society/scheduler.py
@@ -28,10 +28,12 @@ the mission machinery is imported only when it is actually used.
from __future__ import annotations
+import asyncio
import logging
from collections.abc import Awaitable, Callable
from typing import Any, Final
+from .delivery import DeliveryBusy
from .events import SCHEDULER_ACTOR as _SCHEDULER
from .events import USER_ACTOR as _USER
from .events import MsgType, SocietyEnvelope, Tier
@@ -90,6 +92,7 @@ class SocietyScheduler:
self._deliver = deliver
self._budget = budget_tracker
self._trace_cap = trace_message_cap
+ self._delivery_lock = asyncio.Lock()
#: run_id → agent_id of work the scheduler started and has not seen end.
self._running: dict[str, str] = {}
self._unsubscribe: Callable[[], None] | None = None
@@ -137,7 +140,7 @@ class SocietyScheduler:
elif env.msg_type in _DELIVERED and env.to_agent and env.to_agent != _USER:
# Envelopes for the person (HOLD/RELEASE on approvals) are read by
# the UI, the bar and voice — never delivered to a roster row.
- await self._on_deliver(env)
+ await self.drain_deliveries()
async def _veto(self, env: SocietyEnvelope, reason: FailureReason, detail: str) -> None:
log.info(
@@ -282,23 +285,51 @@ class SocietyScheduler:
if isinstance(target, AgentRecord):
await self._deliver(target, env)
- async def _on_deliver(self, env: SocietyEnvelope) -> None:
- if await self._store.kill_switch():
- await self._veto(env, FailureReason.KILL_SWITCH, "the society is halted")
- return
- if await self._store.count_in_trace(env.trace_id) > self._trace_cap:
- await self._veto(
- env, FailureReason.MESSAGE_CAP, f"trace exceeded {self._trace_cap} messages"
- )
+ async def drain_deliveries(self) -> None:
+ """FIFO per recipient. Busy recipients never block other conversations."""
+ if self._delivery_lock.locked():
return
+ async with self._delivery_lock:
+ busy: set[str | None] = set()
+ for env in await self._store.pending_deliveries():
+ if env.to_agent in busy:
+ receive = getattr(self._deliver, "receive", None)
+ target = await self._resolve_target(env)
+ if receive is not None and isinstance(target, AgentRecord):
+ try:
+ await receive(target, env)
+ except DeliveryBusy:
+ pass # No chat service yet; the durable queue will retry.
+ except Exception:
+ log.warning("society: queued receipt projection failed", exc_info=True)
+ continue
+ if not await self._on_deliver(env):
+ busy.add(env.to_agent)
+
+ async def _on_deliver(self, env: SocietyEnvelope) -> bool:
+ if await self._store.delivery_status(env.event_id) != "queued":
+ return True
+ reason = None
+ if await self._store.kill_switch():
+ reason = FailureReason.KILL_SWITCH
+ elif await self._store.count_in_trace(env.trace_id) > self._trace_cap:
+ reason = FailureReason.MESSAGE_CAP
target = await self._resolve_target(env)
if isinstance(target, FailureReason):
- await self._veto(env, target, f"target {env.to_agent!r} cannot receive")
- return
+ reason = reason or target
+ if reason is not None:
+ await self._store.mark_delivery(env.event_id, "failed", str(reason))
+ await self._veto(env, reason, f"message could not reach {env.to_agent}")
+ return True
if self._deliver is None:
- log.debug("society scheduler: no deliverer wired; %s stays in the inbox", env.msg_type)
- return
+ return False
try:
await self._deliver(target, env)
- except Exception as exc: # noqa: BLE001 — delivery failure is a typed veto
+ except DeliveryBusy:
+ return False
+ except Exception as exc: # noqa: BLE001 — persist the failure and report it
+ await self._store.mark_delivery(env.event_id, "failed", str(exc))
await self._veto(env, classify_error(exc), f"delivery failed: {exc}")
+ return True
+ await self._store.mark_delivery(env.event_id, "delivered")
+ return True
diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sql
index 5da76d5895..d13ea399a4 100644
--- a/jarvis/society/society_schema.sql
+++ b/jarvis/society/society_schema.sql
@@ -153,3 +153,17 @@ CREATE TABLE IF NOT EXISTS society_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
+
+-- Only newly appended internal messages enter the durable delivery queue.
+-- The trigger closes the crash window between event insertion and publication.
+CREATE TABLE IF NOT EXISTS society_deliveries (
+ event_id TEXT PRIMARY KEY REFERENCES society_events(event_id),
+ status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'delivered', 'failed')),
+ error TEXT NOT NULL DEFAULT ''
+);
+CREATE TRIGGER IF NOT EXISTS society_queue_message AFTER INSERT ON society_events
+WHEN NEW.msg_type IN ('SAY', 'QUERY', 'ANSWER', 'PROPOSE', 'HOLD', 'RELEASE')
+ AND NEW.to_agent IS NOT NULL AND NEW.to_agent != 'user' AND NEW.from_agent != 'scheduler'
+BEGIN
+ INSERT OR IGNORE INTO society_deliveries (event_id) VALUES (NEW.event_id);
+END;
diff --git a/jarvis/society/store.py b/jarvis/society/store.py
index 32137e57f7..5a46b5445e 100644
--- a/jarvis/society/store.py
+++ b/jarvis/society/store.py
@@ -38,6 +38,7 @@ def day_start_ms(at_ms: int) -> int:
)
return int(day.timestamp() * 1000)
+
log = logging.getLogger(__name__)
__all__ = ["SocietyStore", "SCHEMA_VERSION"]
@@ -260,6 +261,29 @@ class SocietyStore:
await self._bus.publish(stored)
return stored
+ async def delivery_status(self, event_id: str) -> str:
+ async with self.conn.execute(
+ "SELECT status FROM society_deliveries WHERE event_id = ?", (event_id,)
+ ) as cur:
+ row = await cur.fetchone()
+ return str(row[0]) if row else "queued"
+
+ async def mark_delivery(self, event_id: str, status: str, error: str = "") -> None:
+ await self.conn.execute(
+ "UPDATE society_deliveries SET status = ?, error = ? WHERE event_id = ?",
+ (status, error, event_id),
+ )
+
+ async def pending_deliveries(self) -> list[SocietyEnvelope]:
+ async with self.conn.execute(
+ "SELECT e.seq, e.event_id, e.msg_type, e.from_agent, e.to_agent, e.trace_id, "
+ "e.parent_event_id, e.ts_ms, e.cost_usd, e.payload_json "
+ "FROM society_events e JOIN society_deliveries d ON d.event_id = e.event_id "
+ "WHERE d.status = 'queued' ORDER BY e.seq"
+ ) as cur:
+ rows = await cur.fetchall()
+ return [_row_to_envelope(row) for row in rows]
+
async def events_since(self, after_seq: int = 0, *, limit: int = 1000) -> list[SocietyEnvelope]:
cur = await self.conn.execute(
f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE seq > ? " # noqa: S608 — identifiers from a fixed allowlist, values bound
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
index c540e7dbb2..83a8d726bd 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
@@ -1,3 +1,4 @@
+import { InternalMessageBubble } from "./InternalMessageBubble";
import {
memo,
useEffect,
@@ -100,6 +101,9 @@ export function AgentTimeline({
return (
<>
{items.map((item) => {
+ if (item.type === "internal") {
+ return <InternalMessageBubble key={item.id} item={item} />;
+ }
if (item.type === "user") {
return (
<div
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.test.tsx
new file mode 100644
index 0000000000..260061b931
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.test.tsx
@@ -0,0 +1,65 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import en from "@/i18n/locales/en.json";
+import de from "@/i18n/locales/de.json";
+import es from "@/i18n/locales/es.json";
+import { InternalMessageBubble } from "./InternalMessageBubble";
+import { EMPTY_TIMELINE, reduceEvent, reduceEvents } from "./reduce";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+
+const locale = vi.hoisted(() => ({ strings: {} as Record<string, string> }));
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => locale.strings[key.split(".")[1]] ?? key }));
+
+const incoming: AgentChatEvent = {
+ seq: 1, ts_ms: 1000, kind: "agent_message",
+ payload: {
+ message_id: "m1", sender_id: "jarvis", sender_name: "Jarvis", sender_kind: "jarvis",
+ text: "A test message", prompt: "[say from Jarvis]\nA test message", trace_id: "t1",
+ status: "queued", turn_id: "", error: "",
+ },
+};
+const delivered: AgentChatEvent = {
+ seq: 2, ts_ms: 2000, kind: "agent_message_status",
+ payload: { message_id: "m1", status: "delivered", turn_id: "turn1", error: "" },
+};
+
+afterEach(cleanup);
+
+it.each([en, de, es])("shows the trusted sender and live delivery status in each locale", (resource) => {
+ locale.strings = resource.agent_chat;
+ let timeline = reduceEvent(EMPTY_TIMELINE, incoming);
+ const item = timeline.items[0];
+ if (item.type !== "internal") throw new Error("Expected an internal message");
+ const view = render(<InternalMessageBubble item={item} />);
+ expect(screen.getByText("Jarvis")).toBeTruthy();
+ expect(screen.getByText(resource.agent_chat.delivery_queued)).toBeTruthy();
+ expect(screen.getByText("A test message")).toBeTruthy();
+ timeline = reduceEvent(timeline, delivered);
+ const updated = timeline.items[0];
+ if (updated.type !== "internal") throw new Error("Expected an internal message");
+ view.rerender(<InternalMessageBubble item={updated} />);
+ expect(screen.getByText(resource.agent_chat.delivery_delivered)).toBeTruthy();
+ expect(screen.queryByText(resource.agent_chat.delivery_queued)).toBeNull();
+});
+
+it("reopening matches live state and duplicate envelopes remain one message", () => {
+ const live = reduceEvent(reduceEvent(EMPTY_TIMELINE, incoming), delivered);
+ const reopened = reduceEvents(EMPTY_TIMELINE, [incoming, delivered]);
+ expect(reopened).toEqual(live);
+ expect(reduceEvent(live, incoming).items).toHaveLength(1);
+ expect(reduceEvent(EMPTY_TIMELINE, { ...incoming, kind: "user_message", payload: { text: "Old message" } }).items[0].type).toBe("user");
+});
+
+it("shows agent authors and a terminal failure without changing the message", () => {
+ locale.strings = en.agent_chat;
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ { ...incoming, payload: { ...incoming.payload, sender_id: "scout", sender_name: "Scout", sender_kind: "agent" } },
+ { ...delivered, payload: { ...delivered.payload, status: "failed", error: "The recipient is paused" } },
+ ]);
+ const item = timeline.items[0];
+ if (item.type !== "internal") throw new Error("Expected an internal message");
+ render(<InternalMessageBubble item={item} />);
+ expect(screen.getByText("Scout")).toBeTruthy();
+ expect(screen.getByText("Failed")).toBeTruthy();
+ expect(screen.getByText("The recipient is paused")).toBeTruthy();
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
new file mode 100644
index 0000000000..3a4785dee7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
@@ -0,0 +1,19 @@
+import type { InternalMessageItem } from "./reduce";
+import { useT } from "@/i18n";
+
+/** Shared by the lead's timeline and the society's canonical agent chat. */
+export function InternalMessageBubble({ item }: { item: InternalMessageItem }) {
+ const t = useT();
+ return (
+ <div data-testid="agent-message-internal" data-message-id={item.id}
+ className="max-w-[85%] self-start rounded-lg border border-border bg-card px-4 py-3 text-reading">
+ <div className="mb-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
+ <span className="font-medium text-foreground">{item.message.sender_name}</span>
+ <span>{t("agent_chat.internal_message")}</span>
+ <span aria-live="polite">{t(`agent_chat.delivery_${item.message.status}`)}</span>
+ </div>
+ <div className="whitespace-pre-wrap">{item.message.text}</div>
+ {item.message.error && <div className="text-destructive">{item.message.error}</div>}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
index 49e0fc9976..afba5e88eb 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -1,4 +1,4 @@
-import type { AgentChatEvent } from "@/lib/agentChatApi";
+import type { AgentChatEvent, InternalMessage } from "@/lib/agentChatApi";
import { readToolChoices, type ToolChoice } from "./toolChoices";
/**
@@ -141,7 +141,14 @@ export interface NoticeItem {
resolved: string;
}
-export type TimelineItem = UserItem | TurnItem | ErrorItem | NoticeItem;
+export interface InternalMessageItem {
+ type: "internal";
+ id: string;
+ message: InternalMessage;
+ tsMs: number;
+}
+
+export type TimelineItem = UserItem | TurnItem | ErrorItem | NoticeItem | InternalMessageItem;
export interface PendingApproval {
approvalId: string;
@@ -211,11 +218,7 @@ function replaceAt<T>(arr: T[], index: number, value: T): T[] {
return next;
}
-function updateTurn(
- tl: Timeline,
- turnId: string,
- fn: (turn: TurnItem) => TurnItem,
-): Timeline {
+function updateTurn(tl: Timeline, turnId: string, fn: (turn: TurnItem) => TurnItem): Timeline {
const idx = findTurn(tl.items, turnId);
if (idx < 0) return tl;
const turn = tl.items[idx] as TurnItem;
@@ -261,6 +264,30 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
const turnId = str(p.turn_id);
switch (ev.kind) {
+ case "agent_message": {
+ const id = str(p.message_id);
+ if (!id || base.items.some((item) => item.type === "internal" && item.id === id)) return base;
+ return { ...base, items: [...base.items, {
+ type: "internal", id, tsMs: ev.ts_ms,
+ message: {
+ message_id: id, sender_id: str(p.sender_id), sender_name: str(p.sender_name),
+ sender_kind: p.sender_kind === "jarvis" ? "jarvis" : p.sender_kind === "user" ? "user" : "agent",
+ text: str(p.text), prompt: str(p.prompt), trace_id: str(p.trace_id),
+ status: p.status === "delivered" || p.status === "failed" ? p.status : "queued",
+ turn_id: str(p.turn_id), error: str(p.error),
+ },
+ }] };
+ }
+ case "agent_message_status":
+ return { ...base, items: base.items.map((item) =>
+ item.type === "internal" && item.id === str(p.message_id)
+ ? { ...item, message: { ...item.message,
+ status: p.status === "delivered" || p.status === "failed" ? p.status : "queued",
+ turn_id: str(p.turn_id), error: str(p.error),
+ } }
+ : item,
+ ) };
+
case "user_message":
return {
...base,
@@ -474,7 +501,10 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
if (n !== null) counts[k] = n;
}
if (Object.keys(counts).length === 0) return base;
- return updateTurn(base, turnId, (turn) => ({ ...turn, liveUsage: counts }));
+ return updateTurn(base, turnId, (turn) => ({
+ ...turn,
+ liveUsage: counts,
+ }));
}
case "approval_required": {
@@ -545,7 +575,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
// A turn that ended mid-stream closes its live reasoning block.
blocks: turn.blocks.map((b) =>
b.kind === "reasoning" && b.live
- ? { ...b, live: false, durationMs: b.durationMs ?? Math.max(0, ev.ts_ms - b.startedMs) }
+ ? {
+ ...b,
+ live: false,
+ durationMs: b.durationMs ?? Math.max(0, ev.ts_ms - b.startedMs),
+ }
: b,
),
durationMs: num(p.duration_ms) ?? Math.max(0, ev.ts_ms - turn.startedMs),
diff --git a/jarvis/ui/web/frontend/src/components/deck/room/GigiFigure.tsx b/jarvis/ui/web/frontend/src/components/deck/room/GigiFigure.tsx
new file mode 100644
index 0000000000..a85b6f43f2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/room/GigiFigure.tsx
@@ -0,0 +1,232 @@
+import { useMemo, useRef, useState } from "react";
+import { useFrame, type ThreeEvent } from "@react-three/fiber";
+import * as THREE from "three";
+import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js";
+import { MASCOT } from "@/lib/deckRoom";
+
+/**
+ * Gigi in three dimensions — the same mascot, extruded.
+ *
+ * No modelled or generated mesh: the figure is the mascot's OWN outline
+ * (the path `MascotGigi.tsx` draws) pulled into depth, so it is exactly on
+ * brand — the rounded head, the zigzag hem, the eyes, the mouth, the two
+ * arms, the scanlines and the glitch pixels, all at their SVG coordinates.
+ * A free route, and the only one that keeps the pixel-ghost a pixel-ghost
+ * (an image-to-3D generator rounds the hem and invents detail).
+ *
+ * The marked parts are unlit (`MeshBasicMaterial`) on purpose: the mascot
+ * GLOWS, it is not lit — which also keeps it readable on the light
+ * terrace. The dark body is lit, so the room's light and the floor's
+ * reflection give it volume.
+ *
+ * It lives: a slow breath, a turn toward the pointer, a blink every few
+ * seconds. Pressing it is the click-shaped wake word, exactly like the
+ * orb on the flat board (`onPress`).
+ */
+const BODY_PATH =
+ "M 58 90 Q 58 36 128 36 Q 198 36 198 90 L 198 208 L 180 186 L 160 208 L 140 186 L 120 208 L 100 186 L 80 208 L 58 186 Z";
+/** SVG box 256, figure from y=36 to y=208 → MASCOT.height world units. */
+const S = MASCOT.height / 172;
+const DEPTH = 0.55;
+/**
+ * The figure's two marking values. Every glowing part of the mascot -- eyes,
+ * mouth, belt line, the lit arm, the outline and the point light -- is MARK;
+ * MARK_DIM carries the shaded side, so the figure keeps a light direction.
+ *
+ * Held identical to the same two stops in `wiki-video/public/gigi.svg`, which
+ * draws the flat version of this figure.
+ */
+const MARK = "#FFFFFF";
+const MARK_DIM = "#C9C9C9";
+
+/** SVG (x, y) → world (x, y) with the hem on the floor and the figure centred. */
+function svgToWorld(x: number, y: number): [number, number] {
+ return [(x - 128) * S, (208 - y) * S];
+}
+
+function useBodyGeometry() {
+ return useMemo(() => {
+ const loader = new SVGLoader();
+ const { paths } = loader.parse(`<svg xmlns="http://www.w3.org/2000/svg"><path d="${BODY_PATH}"/></svg>`);
+ const shapes = paths.flatMap((p) => SVGLoader.createShapes(p));
+ const geo = new THREE.ExtrudeGeometry(shapes, {
+ depth: DEPTH / S,
+ bevelEnabled: true,
+ bevelThickness: 2,
+ bevelSize: 2,
+ bevelSegments: 2,
+ curveSegments: 24,
+ });
+ // SVG y grows downward: flip, scale to world, hem at y=0, centred in x.
+ geo.scale(S, -S, S);
+ geo.translate(-128 * S, 208 * S, 0);
+ geo.computeVertexNormals();
+ const edges = new THREE.EdgesGeometry(geo, 28);
+ return { geo, edges };
+ }, []);
+}
+
+function Pixel({ x, y, w, h, z, color }: { x: number; y: number; w: number; h: number; z: number; color: string }) {
+ const [wx, wy] = svgToWorld(x + w / 2, y + h / 2);
+ return (
+ <mesh position={[wx, wy, z]}>
+ <boxGeometry args={[w * S, h * S, 0.06]} />
+ <meshBasicMaterial color={color} />
+ </mesh>
+ );
+}
+
+function Arm({ d, z }: { d: [number, number, number, number, number, number]; z: number }) {
+ const curve = useMemo(() => {
+ const [ax, ay, cx, cy, bx, by] = d;
+ const [x0, y0] = svgToWorld(ax, ay);
+ const [x1, y1] = svgToWorld(cx, cy);
+ const [x2, y2] = svgToWorld(bx, by);
+ return new THREE.QuadraticBezierCurve3(
+ new THREE.Vector3(x0, y0, z),
+ new THREE.Vector3(x1, y1, z),
+ new THREE.Vector3(x2, y2, z),
+ );
+ }, [d, z]);
+ return (
+ <mesh>
+ <tubeGeometry args={[curve, 16, 2.75 * S, 12, false]} />
+ <meshBasicMaterial color={MARK} />
+ </mesh>
+ );
+}
+
+export function GigiFigure({
+ onPress,
+ pressLabel,
+ pressDisabled,
+ /** 0…1, the voice level — brightens the glow and the eyes. */
+ levelRef,
+}: {
+ onPress?: () => void;
+ pressLabel?: string;
+ pressDisabled?: boolean;
+ levelRef: { current: number };
+}) {
+ const { geo, edges } = useBodyGeometry();
+ const group = useRef<THREE.Group>(null);
+ const eyes = useRef<THREE.Group>(null);
+ const glow = useRef<THREE.PointLight>(null);
+ const [hover, setHover] = useState(false);
+ const blink = useRef({ next: 2.5, until: 0 });
+ const front = DEPTH + 0.02;
+
+ useFrame((state, dt) => {
+ const g = group.current;
+ if (!g) return;
+ const t = state.clock.elapsedTime;
+ // breath
+ g.position.y = MASCOT.position[1] + Math.sin(t * 1.3) * 0.035;
+ // turn toward the pointer, gently
+ const targetY = state.pointer.x * 0.32;
+ g.rotation.y += (targetY - g.rotation.y) * Math.min(1, dt * 3);
+ // blink
+ const e = eyes.current;
+ if (e) {
+ if (t > blink.current.next && blink.current.until === 0) blink.current.until = t + 0.13;
+ if (blink.current.until !== 0 && t > blink.current.until) {
+ blink.current.until = 0;
+ blink.current.next = t + 2.5 + Math.random() * 4;
+ }
+ const closed = blink.current.until !== 0;
+ e.scale.y += ((closed ? 0.12 : 1) - e.scale.y) * Math.min(1, dt * 18);
+ }
+ // the glow follows the voice
+ if (glow.current) glow.current.intensity = 1.4 + levelRef.current * 4.5 + (hover ? 0.4 : 0);
+ });
+
+ const press = (e: ThreeEvent<MouseEvent>) => {
+ e.stopPropagation();
+ if (!pressDisabled) onPress?.();
+ };
+
+ return (
+ <group
+ ref={group}
+ position={[MASCOT.position[0], MASCOT.position[1], MASCOT.position[2]]}
+ onClick={press}
+ onPointerOver={(e) => {
+ e.stopPropagation();
+ setHover(true);
+ document.body.style.cursor = pressDisabled ? "default" : "pointer";
+ }}
+ onPointerOut={() => {
+ setHover(false);
+ document.body.style.cursor = "";
+ }}
+ name={pressLabel}
+ >
+ {/* body */}
+ <mesh geometry={geo} castShadow receiveShadow>
+ <meshStandardMaterial color="#0e0e0e" roughness={0.48} metalness={0.18} />
+ </mesh>
+ <lineSegments geometry={edges}>
+ <lineBasicMaterial color={MARK} transparent opacity={0.9} />
+ </lineSegments>
+
+ {/* scanlines */}
+ <Pixel x={58} y={131} w={140} h={2.4} z={front} color={MARK} />
+ <Pixel x={58} y={159.5} w={140} h={1.4} z={front} color={MARK_DIM} />
+ {/* chromatic slices */}
+ <Pixel x={64} y={118} w={18} h={10} z={front} color="#5a5a5a" />
+ <Pixel x={170} y={118} w={18} h={10} z={front} color="#5a5a5a" />
+ {/* glitch pixels, floating just off the body */}
+ {[
+ [200, 104, 6, 6],
+ [208, 128, 4, 4],
+ [202, 146, 9, 3],
+ [197, 168, 3, 5],
+ [206, 176, 5, 3],
+ ].map(([x, y, w, h]) => (
+ <Pixel key={`r${x}${y}`} x={x} y={y} w={w} h={h} z={front * 0.6} color={MARK} />
+ ))}
+ {[
+ [44, 96, 6, 4],
+ [48, 124, 4, 6],
+ [40, 148, 8, 3],
+ [50, 170, 3, 5],
+ ].map(([x, y, w, h]) => (
+ <Pixel key={`l${x}${y}`} x={x} y={y} w={w} h={h} z={front * 0.6} color={MARK_DIM} />
+ ))}
+
+ {/* eyes (blink by scaling the group) */}
+ <group ref={eyes} position={[0, svgToWorld(0, 108)[1], 0]}>
+ <group position={[0, -svgToWorld(0, 108)[1], 0]}>
+ <EyeDisc cx={102} cy={108} rx={10} ry={14} z={front} color={MARK} />
+ <EyeDisc cx={154} cy={108} rx={10} ry={14} z={front} color={MARK} />
+ <EyeDisc cx={104} cy={112} rx={4} ry={6} z={front + 0.03} color="#050505" />
+ <EyeDisc cx={156} cy={112} rx={4} ry={6} z={front + 0.03} color="#050505" />
+ <EyeDisc cx={106} cy={105} rx={2} ry={2} z={front + 0.05} color="#ffffff" />
+ <EyeDisc cx={158} cy={105} rx={2} ry={2} z={front + 0.05} color="#ffffff" />
+ </group>
+ </group>
+ {/* mouth */}
+ <EyeDisc cx={128} cy={146} rx={7} ry={10} z={front} color={MARK} />
+ <EyeDisc cx={128} cy={146} rx={3} ry={5} z={front + 0.03} color="#050505" />
+
+ {/* arms */}
+ <Arm d={[58, 140, 40, 148, 42, 162]} z={DEPTH / 2} />
+ <Arm d={[198, 140, 216, 148, 214, 162]} z={DEPTH / 2} />
+
+ {/* the glow the mascot throws onto the floor and the wall */}
+ <pointLight ref={glow} color={MARK} intensity={1.4} distance={9} decay={2} position={[0, 1.6, 1.2]} />
+ </group>
+ );
+}
+
+/** A flat ellipse facing the viewer — an eye, a pupil, the mouth. */
+function EyeDisc({ cx, cy, rx, ry, z, color }: { cx: number; cy: number; rx: number; ry: number; z: number; color: string }) {
+ const [x, y] = svgToWorld(cx, cy);
+ return (
+ <mesh position={[x, y, z]} scale={[rx * S, ry * S, 1]}>
+ <circleGeometry args={[1, 40]} />
+ <meshBasicMaterial color={color} />
+ </mesh>
+ );
+}
+
diff --git a/jarvis/ui/web/frontend/src/components/deck/room/RoomPanels.tsx b/jarvis/ui/web/frontend/src/components/deck/room/RoomPanels.tsx
new file mode 100644
index 0000000000..9f8070d4fb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/deck/room/RoomPanels.tsx
@@ -0,0 +1,134 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { useFrame, useThree } from "@react-three/fiber";
+import type * as THREE from "three";
+import { CSS3DObject, CSS3DRenderer } from "three/examples/jsm/renderers/CSS3DRenderer.js";
+import { PANEL_SCALE, type RoomPanel } from "@/lib/deckRoom";
+
+/**
+ * The instruments as panels in the room — real DOM, placed in 3D.
+ *
+ * The cards (log, terminals, the memory map, …) are the SAME React
+ * components the flat board uses, with their stores, queries and
+ * translations. They cannot be painted into WebGL, and drei's `<Html>`
+ * would mount them in a second React root, cut off from every provider
+ * above the Canvas (QueryClient, i18n, theme). And a DOM portal cannot be
+ * opened from INSIDE the Canvas either — the scene is rendered by R3F's
+ * own reconciler, which knows meshes, not divs.
+ *
+ * So the panels live in two halves that share one CSS3DRenderer:
+ *
+ * - `RoomPanelsDom`, rendered OUTSIDE the Canvas in the ordinary DOM tree,
+ * mounts the renderer's overlay next to the canvas, makes one
+ * `CSS3DObject` per panel (position, turn, px→world scale), adds them to
+ * the scene it is handed, and fills each panel's element through a
+ * react-dom portal — same React root, every provider intact.
+ * - `CssTick`, rendered INSIDE the Canvas, asks the renderer to project the
+ * panels once per frame with the very camera the WebGL scene renders
+ * with — so a panel turned 0.5 rad toward the viewer at z=2.2 is exactly
+ * where its light on the floor says it is.
+ *
+ * Size: a panel's DOM box is `width × height` px; `PANEL_SCALE` turns px
+ * into world units, so a 430 px panel stands 4.3 units wide in the room.
+ * The overlay ignores the pointer; the panels themselves take it, so a
+ * click lands on the card and a click beside it lands on the scene (the
+ * mascot).
+ */
+export function useCss3dRenderer(): CSS3DRenderer {
+ return useMemo(() => new CSS3DRenderer(), []);
+}
+
+/** Inside the Canvas: one projection per frame, after the WebGL render. */
+export function CssTick({ renderer }: { renderer: CSS3DRenderer }) {
+ const { scene, camera, size } = useThree();
+ useEffect(() => {
+ renderer.setSize(size.width, size.height);
+ }, [renderer, size.width, size.height]);
+ useFrame(() => {
+ renderer.render(scene, camera);
+ }, 1);
+ return null;
+}
+
+/** Outside the Canvas: the overlay, the objects, the portals. */
+export function RoomPanelsDom({
+ renderer,
+ scene,
+ host,
+ panels,
+ render,
+}: {
+ renderer: CSS3DRenderer;
+ /** The Canvas's scene, once it exists (from `onCreated`). */
+ scene: THREE.Scene | null;
+ /** The element the canvas sits in — the overlay is appended to it. */
+ host: HTMLElement | null;
+ panels: readonly RoomPanel[];
+ /** What goes into each panel's DOM box. */
+ render: (panel: RoomPanel) => ReactNode;
+}) {
+ // One DOM element per panel, made once, owned by its CSS3DObject. The
+ // inner body is React's portal target so three's matrix never lands on a
+ // node React reconciles.
+ const objects = useMemo(
+ () =>
+ panels.map((p) => {
+ const el = document.createElement("div");
+ el.className = "deck-room-panel";
+ el.style.width = `${p.width}px`;
+ el.style.height = `${p.height}px`;
+ el.dataset.panel = p.id;
+ const body = document.createElement("div");
+ body.className = "deck-room-panel-body";
+ el.appendChild(body);
+ const obj = new CSS3DObject(el);
+ obj.position.set(p.position[0], p.position[1], p.position[2]);
+ obj.rotation.y = p.rotationY;
+ obj.scale.setScalar(PANEL_SCALE);
+ return { panel: p, body, obj };
+ }),
+ [panels],
+ );
+
+ useLayoutEffect(() => {
+ if (!host) return;
+ const dom = renderer.domElement;
+ dom.className = "deck-room-css3d";
+ host.appendChild(dom);
+ return () => {
+ dom.remove();
+ };
+ }, [host, renderer]);
+
+ useLayoutEffect(() => {
+ if (!scene) return;
+ for (const { obj } of objects) scene.add(obj);
+ return () => {
+ for (const { obj } of objects) scene.remove(obj);
+ };
+ }, [scene, objects]);
+
+ return (
+ <>
+ {objects.map(({ panel, body }) => (
+ <PortalInto key={panel.id} el={body}>
+ {render(panel)}
+ </PortalInto>
+ ))}
+ </>
+ );
+}
+
+function PortalInto({ el, children }: { el: HTMLElement; children: ReactNode }) {
+ return createPortal(children, el);
+}
+
+/**
+ * The Canvas's scene, captured from `onCreated` for the DOM half. A state
+ * (not a ref) on purpose: the panels must re-render once the scene exists.
+ */
+export function useSceneHandle(): [THREE.Scene | null, (s: THREE.Scene) => void] {
+ const [scene, setScene] = useState<THREE.Scene | null>(null);
+ const ref = useRef(setScene);
+ return [scene, ref.current];
+}
diff --git a/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx b/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
index f9fbd14100..3eb67c237a 100644
--- a/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/DecisionPath.tsx
@@ -8,59 +8,74 @@
* explanation derived from a recorded fact. Neither is ever invented — a step
* with no recorded rationale says so instead of guessing.
*
- * The six kinds are told apart by their GLYPH, not by six hues: a decision
- * kind is neither a status nor an identity, and painting `risk` rose made
- * every routing trace look like it contained an error.
+ * A timeline, so it reads top-down and left-aligned: the glyph column is the
+ * spine, the rationale hangs under the label it explains. The six kinds are
+ * told apart by their GLYPH, never by six hues — a decision kind is neither a
+ * status nor an identity.
*/
+import type { LucideIcon } from "lucide-react";
+import { Brain, CircleDot, Layers, RotateCcw, Route, Scale, Workflow } from "lucide-react";
+
+import { Badge } from "@/components/ui/badge";
import { useT } from "@/i18n";
import type { DecisionStep } from "./types";
-const KIND_ICON: Record<string, string> = {
- tier: "◆",
- route: "→",
- risk: "⚖",
- brain: "🧠",
- mission: "⚙",
- fallback: "↺",
+const KIND_ICON: Record<string, LucideIcon> = {
+ tier: Layers,
+ route: Route,
+ risk: Scale,
+ brain: Brain,
+ mission: Workflow,
+ fallback: RotateCcw,
};
export function DecisionPath({ steps }: { steps: DecisionStep[] }) {
const t = useT();
if (steps.length === 0) {
return (
- <span className="text-body text-muted-foreground">
+ <p className="text-base text-muted-foreground">
{t("run_inspector.decision.empty")}
- </span>
+ </p>
);
}
return (
- <ol className="space-y-1" data-testid="decision-path">
- {steps.map((s, i) => (
- <li
- key={i}
- data-decision-kind={s.kind}
- className="rounded-md px-2 py-1.5 transition-colors hover:bg-secondary"
- >
- <div className="flex flex-wrap items-baseline gap-1.5 text-body">
- <span className="w-4 shrink-0 text-center text-muted-foreground">
- {KIND_ICON[s.kind] ?? "·"}
- </span>
- <span className="font-medium text-foreground">{s.label}</span>
- {s.detail && (
- <span className="font-mono text-micro text-muted-foreground">
- {s.detail}
- </span>
- )}
- <span className="ml-auto rounded-full bg-secondary px-2 py-px text-micro text-muted-foreground">
- {s.rationale_source || t("run_inspector.decision.no_source")}
- </span>
- </div>
- <p className="mt-1 pl-[22px] text-meta text-muted-foreground [overflow-wrap:anywhere]">
- {s.rationale || t("run_inspector.decision.no_rationale")}
- </p>
- </li>
- ))}
+ <ol className="space-y-0.5" data-testid="decision-path">
+ {steps.map((s, i) => {
+ const Icon = KIND_ICON[s.kind] ?? CircleDot;
+ const last = i === steps.length - 1;
+ return (
+ <li
+ key={i}
+ data-decision-kind={s.kind}
+ className="grid grid-cols-[20px_minmax(0,1fr)] gap-x-3"
+ >
+ {/* The spine: glyph, then a hairline down to the next step. */}
+ <div className="flex flex-col items-center">
+ <Icon aria-hidden className="mt-1 h-4 w-4 shrink-0 text-muted-foreground" />
+ {!last && <span aria-hidden className="w-px flex-1 bg-border" />}
+ </div>
+ <div className="min-w-0 pb-3">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="text-base font-medium text-foreground-strong">
+ {s.label}
+ </span>
+ {s.detail && (
+ <span className="font-mono text-sm text-muted-foreground">
+ {s.detail}
+ </span>
+ )}
+ <Badge variant="outline" className="ml-auto shrink-0">
+ {s.rationale_source || t("run_inspector.decision.no_source")}
+ </Badge>
+ </div>
+ <p className="mt-1 text-sm text-muted-foreground [overflow-wrap:anywhere]">
+ {s.rationale || t("run_inspector.decision.no_rationale")}
+ </p>
+ </div>
+ </li>
+ );
+ })}
</ol>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx b/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx
index 78df3e4a01..7a0b118bba 100644
--- a/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/EnvironmentPanel.tsx
@@ -11,17 +11,6 @@ import { useT } from "@/i18n";
import type { RunEnvironment } from "./types";
-function Row({ label, value }: { label: string; value: string }) {
- return (
- <div className="flex min-w-0 items-baseline gap-2">
- <span className="w-24 shrink-0 text-meta text-muted-foreground">{label}</span>
- <span className="min-w-0 flex-1 break-words font-mono text-meta text-foreground [overflow-wrap:anywhere]">
- {value}
- </span>
- </div>
- );
-}
-
export function EnvironmentPanel({ env }: { env: RunEnvironment }) {
const t = useT();
const rows: Array<[string, string]> = [];
@@ -32,9 +21,10 @@ export function EnvironmentPanel({ env }: { env: RunEnvironment }) {
push(t("run_inspector.env.mode"), env.voice_mode);
push(t("run_inspector.env.surface"), env.surface);
- push(t("run_inspector.env.started_by"), env.wake_keyword
- ? `${env.wake_source} · "${env.wake_keyword}"`
- : env.wake_source);
+ push(
+ t("run_inspector.env.started_by"),
+ env.wake_keyword ? `${env.wake_source} · "${env.wake_keyword}"` : env.wake_source,
+ );
push(t("run_inspector.env.ended_by"), env.hangup_reason);
push(t("run_inspector.env.language"), env.language);
push(t("run_inspector.env.providers"), env.providers.join(", "));
@@ -42,23 +32,34 @@ export function EnvironmentPanel({ env }: { env: RunEnvironment }) {
push(t("run_inspector.env.tiers"), env.tiers.join(", "));
push(t("run_inspector.env.voices"), env.voices.join(", "));
if (env.input_sample_rate || env.output_sample_rate) {
- push(t("run_inspector.env.audio"),
- `${env.input_sample_rate ?? "?"} Hz in · ${env.output_sample_rate ?? "?"} Hz out`);
+ push(
+ t("run_inspector.env.audio"),
+ `${env.input_sample_rate ?? "?"} Hz in · ${env.output_sample_rate ?? "?"} Hz out`,
+ );
}
if (rows.length === 0) {
return (
- <span className="text-body text-muted-foreground">
- {t("run_inspector.env.empty")}
- </span>
+ <p className="text-base text-muted-foreground">{t("run_inspector.env.empty")}</p>
);
}
return (
- <div className="grid gap-stack sm:grid-cols-2" data-testid="environment-panel">
+ // Label/value pairs, not a table: every value is a short recorded fact, so
+ // the label sits in its own fixed column and the value keeps the monospace
+ // spelling it was written with.
+ <dl
+ className="grid grid-cols-[minmax(0,7rem)_minmax(0,1fr)] gap-x-4 gap-y-2.5"
+ data-testid="environment-panel"
+ >
{rows.map(([label, value]) => (
- <Row key={label} label={label} value={value} />
+ <div key={label} className="contents">
+ <dt className="truncate text-sm text-muted-foreground">{label}</dt>
+ <dd className="min-w-0 break-words font-mono text-sm text-foreground [overflow-wrap:anywhere]">
+ {value}
+ </dd>
+ </div>
))}
- </div>
+ </dl>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/ErrorPanel.tsx b/jarvis/ui/web/frontend/src/components/runs/ErrorPanel.tsx
index c8b9a4773c..0bd611ce8b 100644
--- a/jarvis/ui/web/frontend/src/components/runs/ErrorPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/ErrorPanel.tsx
@@ -1,21 +1,73 @@
-import type { ErrorEntry } from "./types";
+import { useT } from "@/i18n";
+
+import type { ErrorEntry, RunTurn } from "./types";
/**
- * Recorded faults for one run. `fault` ink on the normal lift surface — an
- * error says what failed, it does not repaint the panel red.
+ * Recorded faults, one row each.
+ *
+ * A fault is a status, so it keeps its hue — but only as ink on the soft
+ * destructive wash the rest of the app uses for the same job. An error says
+ * what failed; it does not repaint the panel red.
*/
export function ErrorPanel({ errors }: { errors: ErrorEntry[] }) {
- if (errors.length === 0)
- return <span className="text-body text-muted-foreground">—</span>;
+ const t = useT();
+ if (errors.length === 0) {
+ return (
+ <p className="text-base text-muted-foreground">
+ {t("run_inspector.errors.empty")}
+ </p>
+ );
+ }
return (
- <ul className="space-y-1">
+ <ul className="space-y-1.5" data-testid="error-panel">
{errors.map((e, i) => (
- <li key={i} className="rounded-md bg-secondary px-2 py-1.5 text-meta">
- <span className="font-semibold text-destructive">{e.source}</span>
- {e.layer && <span className="text-muted-foreground"> · {e.layer}</span>}
- <span className="text-muted-foreground"> — {e.message}</span>
- </li>
+ <ErrorRow key={`${e.source}-${i}`} entry={e} />
+ ))}
+ </ul>
+ );
+}
+
+/**
+ * Every fault of a whole run, each one carrying the turn it happened in — the
+ * "this run went wrong, where?" read that used to require opening five turn
+ * cards and clicking through five forensic tabs.
+ */
+export function RunErrorList({ turns }: { turns: RunTurn[] }) {
+ const t = useT();
+ const rows = turns.flatMap((turn) =>
+ turn.errors.map((entry) => ({ entry, idx: turn.idx })),
+ );
+ if (rows.length === 0) {
+ return (
+ <p className="text-base text-muted-foreground">
+ {t("run_inspector.errors.empty")}
+ </p>
+ );
+ }
+ return (
+ <ul className="space-y-1.5" data-testid="run-errors">
+ {rows.map(({ entry, idx }, i) => (
+ <ErrorRow key={`${idx}-${entry.source}-${i}`} entry={entry} turnIdx={idx} />
))}
</ul>
);
}
+
+function ErrorRow({ entry, turnIdx }: { entry: ErrorEntry; turnIdx?: number }) {
+ return (
+ <li className="rounded-md border border-destructive/20 bg-destructive/[0.12] px-3 py-2 text-sm">
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ {turnIdx !== undefined && (
+ <span className="font-medium text-foreground-strong">Turn {turnIdx + 1}</span>
+ )}
+ <span className="font-mono font-medium text-destructive">{entry.source}</span>
+ {entry.layer && (
+ <span className="font-mono text-muted-foreground">{entry.layer}</span>
+ )}
+ </div>
+ <p className="mt-1 break-words text-foreground-secondary [overflow-wrap:anywhere]">
+ {entry.message}
+ </p>
+ </li>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx b/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx
index ee1af29072..283b95dc7e 100644
--- a/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/EventStream.tsx
@@ -10,25 +10,27 @@
*
* Completeness only becomes readable through the lane split (speech / brain /
* tool / vision / …) plus a text filter, so a 500-event Computer-Use turn is
- * still navigable.
+ * still navigable — and the rows scroll inside their OWN box, so a long stream
+ * never turns the whole view into one endless page.
*/
import { useMemo, useState } from "react";
import { ChevronDown, ChevronRight, Copy, Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import { robustCopy } from "@/lib/clipboard";
+import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
import { useT } from "@/i18n";
import type { RawEvent } from "./types";
/**
- * Nine lanes used to mean nine hues — slate, violet, fuchsia, sky, cyan, rose
- * and near-white — which spent the product's entire colour budget on a filter
- * strip and left the one lane that matters (`error`) no louder than the rest.
- *
- * The lane NAME is printed in the chip and the event `kind` is printed in the
- * row, so the words already carry the distinction. Only `error` keeps a hue,
- * because only `error` is a status.
+ * Nine lanes used to mean nine hues, which spent the product's entire colour
+ * budget on a filter strip and left the one lane that matters (`error`) no
+ * louder than the rest. The lane NAME is printed in the chip and the event
+ * `kind` is printed in the row, so the words already carry the distinction.
+ * Only `error` keeps a hue, because only `error` is a status.
*/
function isFaultLane(category: string): boolean {
return category === "error";
@@ -73,9 +75,9 @@ export function EventStream({
if (events.length === 0) {
return (
- <span className="text-body text-muted-foreground">
+ <p className="text-base text-muted-foreground">
{t("run_inspector.stream.empty")}
- </span>
+ </p>
);
}
@@ -110,7 +112,7 @@ export function EventStream({
};
return (
- <div className="space-y-stack" data-testid="event-stream">
+ <div className="space-y-3" data-testid="event-stream">
{/* Lane filters + search */}
<div className="flex flex-wrap items-center gap-1.5">
{Object.entries(counts)
@@ -118,94 +120,107 @@ export function EventStream({
.map(([cat, n]) => {
// With no explicit selection every lane is on; a lane switched off
// recedes rather than disappears, so the strip keeps its shape.
- const active = lanes.size === 0 || lanes.has(cat);
+ const on = lanes.size === 0 || lanes.has(cat);
+ const picked = lanes.has(cat);
return (
<button
key={cat}
type="button"
+ aria-pressed={picked}
data-testid={`lane-${cat}`}
- data-active={lanes.has(cat)}
+ data-active={picked}
onClick={() => toggleLane(cat)}
- className={`inline-flex items-center gap-1 rounded-full bg-secondary px-2 py-0.5 text-micro font-medium transition-opacity ${
- isFaultLane(cat) ? "text-destructive" : "text-foreground"
- } ${active ? "" : "opacity-40"}`}
+ className={cn(
+ "inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-xs font-medium transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ picked
+ ? "border-accent/20 bg-accent-soft text-accent"
+ : on
+ ? "border-border bg-secondary text-muted-foreground hover:text-foreground"
+ : "border-border bg-transparent text-foreground-faint hover:text-muted-foreground",
+ isFaultLane(cat) && on && !picked && "text-destructive",
+ )}
>
{cat}
- <span className="tabular-nums text-muted-foreground">{n}</span>
+ <span className="tabular-nums opacity-70">{n}</span>
</button>
);
})}
<div className="ml-auto flex items-center gap-1.5">
<div className="relative">
- <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground" />
- <input
- type="text"
+ <Search
+ aria-hidden
+ className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
value={needle}
onChange={(e) => setNeedle(e.target.value)}
placeholder={t("run_inspector.stream.filter")}
+ aria-label={t("run_inspector.stream.filter")}
data-testid="event-filter"
- className="h-7 w-40 rounded-md bg-input pl-6 pr-2 text-micro text-foreground outline-none placeholder:text-faint-foreground focus:ring-2 focus:ring-border-strong"
+ className="h-8 w-44 pl-8 text-sm"
/>
</div>
- <button
- type="button"
+ <Button
+ variant="ghost"
+ size="sm"
onClick={copyStream}
title={t("run_inspector.stream.copy")}
- className="inline-flex h-7 items-center gap-1 rounded-md px-2 text-micro text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
>
- <Copy className="h-3 w-3" />
+ <Copy aria-hidden />
JSONL
- </button>
+ </Button>
</div>
</div>
{truncated && (
- <div className="rounded-md bg-secondary px-2 py-1 text-micro text-warning">
+ <p className="rounded-md border border-warning/20 bg-warning/[0.12] px-3 py-2 text-sm text-warning">
{t("run_inspector.stream.truncated")}
- </div>
+ </p>
)}
- {/* Rows. Fill on hover is the separation device — no rules between them. */}
- <ol>
+ {/* Rows. Their own scroll box: a 500-event turn must not push the run
+ detail into a page-long scroll. Fill on hover is the separation
+ device — no rules between them. */}
+ <ol className="max-h-[26rem] overflow-y-auto scrollbar-jarvis">
{visible.map((e) => {
const isOpen = open.has(e.seq);
const hasPayload = Object.keys(e.payload ?? {}).length > 0;
+ const Chevron = isOpen ? ChevronDown : ChevronRight;
return (
<li key={`${e.seq}-${e.ts_ms}`} data-kind={e.kind} data-category={e.category}>
<button
type="button"
onClick={() => hasPayload && toggleRow(e.seq)}
- className={`flex w-full items-start gap-2 rounded-md px-2 py-1 text-left transition-colors hover:bg-secondary ${
- hasPayload ? "" : "cursor-default"
- }`}
+ aria-expanded={hasPayload ? isOpen : undefined}
+ className={cn(
+ "flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-secondary",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ !hasPayload && "cursor-default",
+ )}
>
- <span className="mt-[3px] w-4 shrink-0 text-muted-foreground">
- {hasPayload ? (
- isOpen ? (
- <ChevronDown className="h-3 w-3" />
- ) : (
- <ChevronRight className="h-3 w-3" />
- )
- ) : null}
+ <span className="mt-0.5 w-4 shrink-0 text-muted-foreground">
+ {hasPayload && <Chevron aria-hidden className="h-3.5 w-3.5" />}
</span>
- <span className="w-16 shrink-0 text-right font-mono text-micro tabular-nums text-muted-foreground">
+ <span className="w-16 shrink-0 text-right font-mono text-sm tabular-nums text-muted-foreground">
{fmtOffset(e.offset_ms)}
</span>
<span
- className={`w-48 shrink-0 font-mono text-micro ${
- isFaultLane(e.category) ? "text-destructive" : "text-foreground"
- }`}
+ className={cn(
+ "w-48 shrink-0 font-mono text-sm",
+ isFaultLane(e.category) ? "text-destructive" : "text-foreground",
+ )}
>
{e.kind}
</span>
{/* No truncation: the summary IS the information. Long lines
wrap instead of being cut at the container edge. */}
- <span className="min-w-0 flex-1 break-words text-micro text-muted-foreground [overflow-wrap:anywhere]">
+ <span className="min-w-0 flex-1 break-words text-sm text-muted-foreground [overflow-wrap:anywhere]">
{e.summary}
</span>
</button>
{isOpen && (
- <pre className="overflow-x-auto rounded-md bg-secondary px-3 py-2 font-mono text-micro text-muted-foreground">
+ <pre className="mx-2 mb-1 overflow-x-auto rounded-md bg-secondary px-3 py-2 font-mono text-sm text-muted-foreground">
{JSON.stringify(e.payload, null, 2)}
</pre>
)}
@@ -214,11 +229,11 @@ export function EventStream({
})}
</ol>
- <div className="text-micro tabular-nums text-muted-foreground">
+ <p className="text-xs tabular-nums text-muted-foreground">
{visible.length === events.length
? `${events.length} ${t("run_inspector.stream.events")}`
: `${visible.length} / ${events.length} ${t("run_inspector.stream.events")}`}
- </div>
+ </p>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/FeatureBadges.tsx b/jarvis/ui/web/frontend/src/components/runs/FeatureBadges.tsx
index 8c20d29cbb..f30a788331 100644
--- a/jarvis/ui/web/frontend/src/components/runs/FeatureBadges.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/FeatureBadges.tsx
@@ -1,20 +1,21 @@
import type { LucideIcon } from "lucide-react";
import { Bot, Monitor, Sparkles, Terminal } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
import { agentBrand } from "@/lib/agentBrand";
+import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
/**
* "Which agents / tools / CLIs ran" — Computer-Use, the agent system and Skill
- * are called out by name and by glyph; everything else (CLI/tool names) gets a
- * monospace chip.
+ * are called out by name and by glyph; everything else (CLI/tool names) keeps
+ * its monospace spelling because it IS an identifier.
*
- * These used to be painted sky / violet / fuchsia, which spent hue on three
- * things that are neither a status nor an identity — and made a run that
- * happened to touch a skill louder than one that failed. The glyph is what
- * distinguishes them now; the surface is the same neutral lift every chip in
- * the product rests on. The sub_agent label is still resolved per render: it
- * carries the wake-word-derived assistant name ("Ruben" -> "Ruben-Agent").
+ * These are neither a status nor an identity, so they carry no hue: the glyph
+ * is what distinguishes them and the surface is the one neutral badge every
+ * label in the product rests on. The sub_agent label is still resolved per
+ * render — it carries the wake-word-derived assistant name ("Ruben" ->
+ * "Ruben-Agent").
*/
const AGENT_META: Record<string, { label: string | null; Icon: LucideIcon }> = {
computer_use: { label: "Computer-Use", Icon: Monitor },
@@ -36,38 +37,28 @@ export function FeatureBadges({
if (!tags.length) return null;
const shown = max ? tags.slice(0, max) : tags;
const rest = tags.length - shown.length;
- // 11px is the type floor, so the two sizes differ in padding only.
- const pad = size === "xs" ? "px-1.5 py-px" : "px-2 py-0.5";
- const icon = size === "xs" ? "h-3 w-3" : "h-3.5 w-3.5";
+ // 12 px is the type floor, so the two sizes differ in height and padding.
+ const compact = size === "xs" ? "h-5 px-1.5" : undefined;
return (
<div className="flex flex-wrap items-center gap-1" data-testid="feature-badges">
- {shown.map((t) => {
- const m = AGENT_META[t];
- if (m) {
- const { Icon } = m;
- return (
- <span
- key={t}
- data-feature={t}
- className={`inline-flex items-center gap-1 rounded-full bg-secondary text-micro font-medium text-foreground ${pad}`}
- >
- <Icon className={icon} strokeWidth={2.25} />
- {m.label ?? agentBrand(assistantName)}
- </span>
- );
- }
+ {shown.map((tag) => {
+ const meta = AGENT_META[tag];
+ const Icon = meta ? meta.Icon : Terminal;
return (
- <span
- key={t}
- data-feature={t}
- className={`inline-flex items-center gap-1 rounded-full bg-secondary font-mono text-micro text-muted-foreground ${pad}`}
+ <Badge
+ key={tag}
+ variant="secondary"
+ data-feature={tag}
+ className={cn(meta ? "text-foreground" : "font-mono", compact)}
>
- <Terminal className={icon} strokeWidth={2} />
- {t}
- </span>
+ <Icon aria-hidden />
+ {meta ? (meta.label ?? agentBrand(assistantName)) : tag}
+ </Badge>
);
})}
- {rest > 0 && <span className="text-micro text-muted-foreground">+{rest}</span>}
+ {rest > 0 && (
+ <span className="text-xs tabular-nums text-muted-foreground">+{rest}</span>
+ )}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/LatencyWaterfall.tsx b/jarvis/ui/web/frontend/src/components/runs/LatencyWaterfall.tsx
index 5b6ff2410e..560fcde6fd 100644
--- a/jarvis/ui/web/frontend/src/components/runs/LatencyWaterfall.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/LatencyWaterfall.tsx
@@ -1,10 +1,12 @@
+import { cn } from "@/lib/utils";
+
import type { LatencyEntry } from "./types";
/**
* Per-phase latency, one bar each. The three SLO states are the three status
* hues: a phase inside budget is alive, a warned one is degraded, a breached
- * one is a fault. `warn` used to be painted in --foreground, which made the
- * middle state the brightest bar in the chart.
+ * one is a fault. Nothing else in the chart carries colour, so the eye lands
+ * on the phase that actually missed its budget.
*/
const BAR: Record<string, string> = {
ok: "bg-success",
@@ -13,28 +15,29 @@ const BAR: Record<string, string> = {
};
export function LatencyWaterfall({ entries }: { entries: LatencyEntry[] }) {
- if (entries.length === 0)
- return <span className="text-body text-muted-foreground">n/a</span>;
+ if (entries.length === 0) {
+ return <p className="text-base text-muted-foreground">n/a</p>;
+ }
const max = Math.max(...entries.map((e) => e.duration_ms), 1);
return (
- <div className="space-y-1">
+ <div className="space-y-1.5">
{entries.map((e) => (
<div
key={e.phase}
- className="flex items-center gap-2"
+ className="flex items-center gap-3"
data-testid={`lat-${e.phase}`}
data-slo={e.slo_status}
>
- <span className="w-40 shrink-0 truncate font-mono text-micro text-muted-foreground">
+ <span className="w-44 shrink-0 truncate font-mono text-sm text-muted-foreground">
{e.phase}
</span>
- <div className="h-2 flex-1 rounded-full bg-secondary">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-secondary">
<div
- className={`h-2 rounded-full ${BAR[e.slo_status] ?? BAR.ok}`}
+ className={cn("h-full rounded-full", BAR[e.slo_status] ?? BAR.ok)}
style={{ width: `${Math.max(3, (e.duration_ms / max) * 100)}%` }}
/>
</div>
- <span className="w-14 shrink-0 text-right font-mono text-micro tabular-nums text-foreground">
+ <span className="w-16 shrink-0 text-right font-mono text-sm tabular-nums text-foreground">
{e.duration_ms.toFixed(0)}ms
</span>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx b/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
index f9ecc60a9d..fed4e353d5 100644
--- a/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/MetricsPanel.tsx
@@ -1,129 +1,106 @@
-import type { ReactNode } from "react";
-
-import { fmtInt, fmtMs, useRunLocale } from "./format";
-import type { Run } from "./types";
-
/**
- * One measured number with the word for it underneath.
+ * Deep-dive analytics for a single run: the six headline numbers, then the
+ * three distributions that say what the run was actually made of.
*
- * A real tile — `.jarvis-stat-tile` is the shared lift surface — rather than
- * the outlined transparent box it used to be, and the label is sentence case
- * at the type floor instead of a 9px letter-spaced all-caps line. `breach`
- * is the only tone carrying hue, because it is the only one that is a fault.
+ * The tiles are the app's shared `StatTile`, so a number here is drawn exactly
+ * like a number on the agent board or in Spend. Only a breached SLO and a
+ * barge-in carry a tone — everything else is a measurement, not a status.
*/
-export function StatChip({
- label,
- value,
- tone = "default",
-}: {
- label: string;
- value: ReactNode;
- tone?: "default" | "warn" | "breach";
-}) {
- const valueCls =
- tone === "breach"
- ? "text-destructive"
- : tone === "warn"
- ? "text-warning"
- : "text-foreground-strong";
- return (
- <div className="jarvis-stat-tile">
- <div className={`font-mono text-title tabular-nums ${valueCls}`}>{value}</div>
- <div className="mt-0.5 text-micro text-muted-foreground">{label}</div>
- </div>
- );
-}
+import { Badge } from "@/components/ui/badge";
+import { StatTile } from "@/components/extensions/primitives";
+import { useT } from "@/i18n";
-/** A group's name. One weight, one size, no letter-spaced caps. */
-function GroupLabel({ children }: { children: ReactNode }) {
+import { fmtInt, fmtMs, useRunLocale } from "./format";
+import type { Run } from "./types";
+
+/** A group's name inside the panel. One weight, one size, no caps. */
+function GroupLabel({ children }: { children: string }) {
return (
- <div className="mb-stack text-title font-semibold text-foreground-strong">
- {children}
- </div>
+ <h3 className="mb-2 text-base font-medium text-foreground-strong">{children}</h3>
);
}
/** A neutral count chip: `name ×n`. */
function CountChip({ name, count }: { name: string; count: number }) {
return (
- <span className="inline-flex items-center gap-1 rounded-full bg-secondary px-2 py-0.5 font-mono text-micro text-muted-foreground">
+ <Badge variant="secondary" className="font-mono">
{name}
<span className="tabular-nums text-foreground">×{count}</span>
- </span>
+ </Badge>
);
}
-/** Deep-dive analytics grid for a single run. */
export function MetricsPanel({ run }: { run: Run }) {
+ const t = useT();
const locale = useRunLocale();
const a = run.analytics;
const providers = Object.entries(a.cost_by_provider);
const tools = Object.entries(a.tool_counts).sort((x, y) => y[1] - x[1]);
const eventKinds = Object.entries(run.event_counts ?? {}).sort((x, y) => y[1] - x[1]);
return (
- <div className="space-y-group" data-testid="metrics-panel">
- <div className="grid grid-cols-2 gap-stack sm:grid-cols-3 lg:grid-cols-4">
- <StatChip label="Think" value={fmtMs(a.total_think_ms)} />
- <StatChip label="Speak" value={fmtMs(a.total_speak_ms)} />
- <StatChip label="Tokens in" value={fmtInt(a.total_tokens_in, locale)} />
- <StatChip label="Tokens out" value={fmtInt(a.total_tokens_out, locale)} />
- <StatChip
- label="Interruptions"
- value={a.interruptions}
- tone={a.interruptions > 0 ? "warn" : "default"}
+ <div className="space-y-6" data-testid="metrics-panel">
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ <StatTile label={t("run_inspector.metrics.think")} value={fmtMs(a.total_think_ms)} />
+ <StatTile label={t("run_inspector.metrics.speak")} value={fmtMs(a.total_speak_ms)} />
+ <StatTile
+ label={t("run_inspector.metrics.tokens_in")}
+ value={fmtInt(a.total_tokens_in, locale)}
/>
- <StatChip
- label="Worst latency"
+ <StatTile
+ label={t("run_inspector.metrics.tokens_out")}
+ value={fmtInt(a.total_tokens_out, locale)}
+ />
+ <StatTile
+ label={t("run_inspector.metrics.interruptions")}
+ value={fmtInt(a.interruptions, locale)}
+ tone={a.interruptions > 0 ? "warn" : "ok"}
+ />
+ <StatTile
+ label={t("run_inspector.metrics.worst_latency")}
value={a.worst_slo_status}
- tone={
- a.worst_slo_status === "breach"
- ? "breach"
- : a.worst_slo_status === "warn"
- ? "warn"
- : "default"
- }
+ tone={a.worst_slo_status === "breach" ? "danger" : "ok"}
/>
</div>
{providers.length > 0 && (
- <div>
- <GroupLabel>Cost by provider</GroupLabel>
- <div className="space-y-1">
+ <section>
+ <GroupLabel>{t("run_inspector.metrics.cost_by_provider")}</GroupLabel>
+ <dl className="space-y-1.5">
{providers.map(([p, c]) => (
- <div key={p} className="flex items-center justify-between text-body">
- <span className="text-muted-foreground">{p}</span>
- <span className="font-mono tabular-nums text-foreground">
+ <div key={p} className="flex items-baseline justify-between gap-3 text-sm">
+ <dt className="min-w-0 truncate text-muted-foreground">{p}</dt>
+ <dd className="shrink-0 font-mono tabular-nums text-foreground">
${c.toFixed(4)}
- </span>
+ </dd>
</div>
))}
- </div>
- </div>
+ </dl>
+ </section>
)}
{/* Event-kind histogram — the fastest read on what dominated this run.
A run that is 90% LatencySpan looks very different from one that is
40% CUStepProfiled, and the shape alone often locates a problem. */}
{eventKinds.length > 0 && (
- <div>
- <GroupLabel>Recorded events</GroupLabel>
+ <section>
+ <GroupLabel>{t("run_inspector.metrics.recorded_events")}</GroupLabel>
<div className="flex flex-wrap gap-1" data-testid="event-histogram">
{eventKinds.map(([kind, n]) => (
<CountChip key={kind} name={kind} count={n} />
))}
</div>
- </div>
+ </section>
)}
{tools.length > 0 && (
- <div>
- <GroupLabel>Tool usage</GroupLabel>
+ <section>
+ <GroupLabel>{t("run_inspector.metrics.tool_usage")}</GroupLabel>
<div className="flex flex-wrap gap-1">
{tools.map(([name, n]) => (
<CountChip key={name} name={name} count={n} />
))}
</div>
- </div>
+ </section>
)}
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/runs/OutcomeBadge.tsx b/jarvis/ui/web/frontend/src/components/runs/OutcomeBadge.tsx
index 7b69cc7fa2..1d65f99743 100644
--- a/jarvis/ui/web/frontend/src/components/runs/OutcomeBadge.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/OutcomeBadge.tsx
@@ -1,27 +1,34 @@
+import { Badge } from "@/components/ui/badge";
+import { cn } from "@/lib/utils";
+
/**
* The functional outcome of a run or a turn — distinct from SLO latency.
*
- * The ramp used to be inverted: "success" drew the same grey dot as an unknown
- * value, "partial" was painted in --foreground and so became the loudest mark
- * on the screen, and "failed" reached for a literal rose. Status is the only
- * place hue is allowed in this product, and it has exactly three jobs — life,
- * degraded, fault. So the dot carries the hue, the chip stays on the neutral
- * lift every other small surface uses, and the unknown value is the ONE that
- * recedes (--faint-foreground), never the successful one.
+ * Status is the only place hue is allowed in this product, and it has exactly
+ * three jobs: life, degraded, fault. The badge is the shared soft wash
+ * (`success` / `warning` / `destructive`), the dot is the same hue at 8 px,
+ * and an unrecorded outcome is the ONE that recedes into the neutral outline —
+ * never the successful one.
*
* An unknown value still degrades to a neutral style rather than throwing
* (BUG-008 string contract).
*/
-type OutcomeStyle = { label: string; dot: string };
+type BadgeTone = "success" | "warning" | "destructive" | "outline";
+
+type OutcomeStyle = { label: string; dot: string; tone: BadgeTone };
const OUTCOME_STYLE: Record<string, OutcomeStyle> = {
- success: { label: "Success", dot: "bg-success" },
- partial: { label: "Partial", dot: "bg-warning" },
- failed: { label: "Failed", dot: "bg-destructive" },
+ success: { label: "Success", dot: "bg-success", tone: "success" },
+ partial: { label: "Partial", dot: "bg-warning", tone: "warning" },
+ failed: { label: "Failed", dot: "bg-destructive", tone: "destructive" },
};
-const FALLBACK: OutcomeStyle = { label: "—", dot: "bg-faint-foreground" };
+const FALLBACK: OutcomeStyle = {
+ label: "—",
+ dot: "bg-foreground-faint",
+ tone: "outline",
+};
export function outcomeStyle(outcome: string): OutcomeStyle {
return OUTCOME_STYLE[outcome] ?? FALLBACK;
@@ -29,7 +36,7 @@ export function outcomeStyle(outcome: string): OutcomeStyle {
export function OutcomeDot({
outcome,
- className = "",
+ className,
}: {
outcome: string;
className?: string;
@@ -37,7 +44,12 @@ export function OutcomeDot({
return (
<span
data-outcome={outcome}
- className={`inline-block h-2 w-2 shrink-0 rounded-full ${outcomeStyle(outcome).dot} ${className}`}
+ aria-hidden
+ className={cn(
+ "inline-block h-2 w-2 shrink-0 rounded-full",
+ outcomeStyle(outcome).dot,
+ className,
+ )}
/>
);
}
@@ -45,12 +57,9 @@ export function OutcomeDot({
export function OutcomeBadge({ outcome }: { outcome: string }) {
const s = outcomeStyle(outcome);
return (
- <span
- data-outcome={outcome}
- className="inline-flex items-center gap-1.5 rounded-full bg-secondary px-2.5 py-0.5 text-micro font-medium text-foreground"
- >
- <span className={`h-1.5 w-1.5 rounded-full ${s.dot}`} />
+ <Badge variant={s.tone} data-outcome={outcome}>
+ <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", s.dot)} aria-hidden />
{s.label}
- </span>
+ </Badge>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
index 8c4f5fdb96..854774a01e 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunDetail.tsx
@@ -1,39 +1,76 @@
-import { useState } from "react";
-import type { ReactNode } from "react";
-import { useRunDetail } from "@/hooks/useRuns";
+/**
+ * One recorded run, end to end.
+ *
+ * The header answers "what am I looking at" in one line — what was asked, how
+ * it ended, when, how long, what it cost — and everything deeper is a tab, so
+ * the forensic material is one click away instead of five stacked disclosures.
+ * The turn stream is the default tab because that is the read a developer
+ * opens a run for; environment, metrics, faults and the session frame sit
+ * beside it.
+ */
+import { useEffect, useState } from "react";
+import { ArrowLeft, Download } from "lucide-react";
+
import { Badge } from "@/components/ui/badge";
-import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import { runExportUrl } from "@/components/runs/api";
-import { RunTurnCard } from "@/components/runs/RunTurnCard";
-import { OutcomeBadge } from "@/components/runs/OutcomeBadge";
-import { FeatureBadges } from "@/components/runs/FeatureBadges";
-import { MetricsPanel } from "@/components/runs/MetricsPanel";
-import { EnvironmentPanel } from "@/components/runs/EnvironmentPanel";
-import { EventStream } from "@/components/runs/EventStream";
-import type { RunEnvironment } from "@/components/runs/types";
-import { useRunLocale } from "@/components/runs/format";
+import { Button } from "@/components/ui/button";
+import { TabBar } from "@/components/layout/SectionTabBar";
+import { PanelSkeleton, SkeletonBar } from "@/components/layout/PanelSkeleton";
+import { useRunDetail } from "@/hooks/useRuns";
import { useT } from "@/i18n";
+import { runExportUrl } from "./api";
+import { EnvironmentPanel } from "./EnvironmentPanel";
+import { RunErrorList } from "./ErrorPanel";
+import { EventStream } from "./EventStream";
+import { FeatureBadges } from "./FeatureBadges";
+import { MetricsPanel } from "./MetricsPanel";
+import { OutcomeBadge } from "./OutcomeBadge";
+import { RunTurnCard } from "./RunTurnCard";
+import { fmtInt, useRunLocale } from "./format";
+import type { RunEnvironment } from "./types";
+
const EMPTY_ENV: RunEnvironment = {
voice_mode: "", surface: "", wake_source: "", wake_keyword: "", language: "",
hangup_reason: "", providers: [], models: [], tiers: [], voices: [],
input_sample_rate: null, output_sample_rate: null,
};
-export function RunDetail({ sessionId }: { sessionId: string }) {
+type TabId = "turns" | "environment" | "metrics" | "errors" | "session_events";
+
+export function RunDetail({
+ sessionId,
+ onBack,
+}: {
+ sessionId: string;
+ /** Narrow layouts only: return to the run list. */
+ onBack?: () => void;
+}) {
const t = useT();
const locale = useRunLocale();
const { data: run, isLoading } = useRunDetail(sessionId);
- const [showMetrics, setShowMetrics] = useState(false);
- const [showEnv, setShowEnv] = useState(false);
- const [showSessionEvents, setShowSessionEvents] = useState(false);
+ const [tab, setTab] = useState<TabId>("turns");
+
+ // A different run starts on its own default tab — "Errors" from the previous
+ // run would otherwise open on one that recorded none.
+ useEffect(() => setTab("turns"), [sessionId]);
+
if (isLoading || !run) {
// The real column at its real height with bars where the turn cards go —
// a centred "…" in a black rectangle is indistinguishable from a section
// that failed to load.
return (
- <div className="mx-auto w-full max-w-reading p-5">
- <PanelSkeleton rows={4} rowHeight={132} label={t("run_inspector.title")} />
+ <div className="flex h-full min-h-0 flex-col" data-testid="run-detail-loading">
+ <div className="shrink-0 border-b border-border px-6 py-5">
+ <div className="mx-auto w-full max-w-3xl space-y-2">
+ <SkeletonBar className="h-7 w-64" />
+ <SkeletonBar className="h-4 w-80" />
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 overflow-hidden px-6 py-5">
+ <div className="mx-auto w-full max-w-3xl">
+ <PanelSkeleton rows={4} rowHeight={148} label={t("run_inspector.loading")} />
+ </div>
+ </div>
</div>
);
}
@@ -51,160 +88,126 @@ export function RunDetail({ sessionId }: { sessionId: string }) {
// store). A missing slice must render as "nothing to show", never crash the
// whole inspector — the BUG-008 degrade-don't-throw contract.
const env: RunEnvironment = run.environment ?? EMPTY_ENV;
- const eventCounts = run.event_counts ?? {};
const sessionEvents = run.session_events ?? [];
- const totalEvents = Object.values(eventCounts).reduce((s, n) => s + n, 0);
+ const totalEvents = Object.values(run.event_counts ?? {}).reduce((s, n) => s + n, 0);
+ const errorCount = run.turns.reduce((s, turn) => s + turn.errors.length, 0);
+
+ // The run's own name: what was actually asked. A run with no captured
+ // utterance falls back to its recorded start, never to a bare id.
+ const headline = run.turns.find((x) => x.user_text.trim())?.user_text.trim();
+ const title = headline || started.toLocaleString(locale);
+
+ const facts = [
+ headline ? started.toLocaleString(locale) : null,
+ ended ? ended.toLocaleTimeString(locale) : null,
+ `${run.turns.length} ${t("run_inspector.facts.turns")}`,
+ a.total_duration_s !== null ? `${a.total_duration_s.toFixed(1)}s` : null,
+ run.session.total_cost_usd > 0 ? `$${run.session.total_cost_usd.toFixed(3)}` : null,
+ tokens > 0 ? `${fmtInt(tokens, locale)} ${t("run_inspector.facts.tokens")}` : null,
+ totalEvents > 0
+ ? `${fmtInt(totalEvents, locale)} ${t("run_inspector.stream.events")}`
+ : null,
+ run.session.hangup_reason || null,
+ ].filter(Boolean);
+
+ const tabs = [
+ { id: "turns", label: t("run_inspector.tab.turns"), count: run.turns.length },
+ { id: "environment", label: t("run_inspector.tab.environment") },
+ { id: "metrics", label: t("run_inspector.tab.metrics") },
+ ...(errorCount > 0
+ ? [{ id: "errors", label: t("run_inspector.tab.errors"), count: errorCount }]
+ : []),
+ ...(sessionEvents.length > 0
+ ? [
+ {
+ id: "session_events",
+ label: t("run_inspector.tab.session_events"),
+ count: sessionEvents.length,
+ },
+ ]
+ : []),
+ ];
+ const activeTab = tabs.some((x) => x.id === tab) ? tab : "turns";
return (
<div className="flex h-full min-h-0 flex-col" data-testid="run-detail">
- {/* ── Run header (sticky) ─────────────────────────────────── */}
- <div className="shrink-0 border-b border-border px-5 py-4">
- <div className="mx-auto flex w-full max-w-reading items-start justify-between gap-3">
- <div className="min-w-0 space-y-2">
- <div className="flex items-center gap-2">
- <OutcomeBadge outcome={run.outcome} />
- <span className="font-mono text-meta tabular-nums text-muted-foreground">
- {started.toLocaleString(locale)}
- {ended && ` — ${ended.toLocaleTimeString(locale)}`}
- </span>
- </div>
- <div className="flex flex-wrap items-center gap-1.5">
- <Badge variant="secondary">{run.turns.length} turns</Badge>
- {a.total_duration_s !== null && (
- <Badge variant="outline">{a.total_duration_s.toFixed(1)}s</Badge>
- )}
- {run.session.total_cost_usd > 0 && (
- <Badge variant="outline">${run.session.total_cost_usd.toFixed(3)}</Badge>
- )}
- {tokens > 0 && (
- <Badge variant="outline">{tokens.toLocaleString(locale)} tok</Badge>
- )}
- {run.session.hangup_reason && (
- <Badge variant="outline">{run.session.hangup_reason}</Badge>
- )}
- {totalEvents > 0 && (
- <Badge variant="outline">
- {totalEvents.toLocaleString(locale)} {t("run_inspector.stream.events")}
- </Badge>
- )}
- <LatencyChip status={a.worst_slo_status} />
- </div>
- {/* The run's recorded setup, always visible: mode + provider decide
- how every number below should be read. */}
- <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
- {[env.voice_mode, env.wake_source, env.language, ...env.providers, ...env.models]
- .filter(Boolean)
- .map((v, i) => (
- <span
- key={`${v}-${i}`}
- className="rounded-full bg-secondary px-2 py-0.5 font-mono text-micro text-muted-foreground"
+ {/* ── Run header ───────────────────────────────────────────── */}
+ <div className="shrink-0 border-b border-border px-6 pt-5">
+ <div className="mx-auto w-full max-w-3xl">
+ {onBack && (
+ <Button variant="ghost" size="sm" onClick={onBack} className="-ml-3 mb-2">
+ <ArrowLeft aria-hidden />
+ {t("run_inspector.back")}
+ </Button>
+ )}
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2
+ className="truncate text-xl font-semibold text-foreground-strong"
+ title={title}
+ >
+ {title}
+ </h2>
+ <OutcomeBadge outcome={run.outcome} />
+ {a.worst_slo_status !== "ok" && (
+ <Badge
+ variant={a.worst_slo_status === "breach" ? "destructive" : "warning"}
>
- {v}
- </span>
- ))}
- </div>
- {tags.length > 0 && (
- <div className="pt-0.5">
- <FeatureBadges tags={tags} />
+ {t("run_inspector.latency")} {a.worst_slo_status}
+ </Badge>
+ )}
</div>
- )}
+ <p className="mt-1 truncate text-sm tabular-nums text-muted-foreground">
+ {facts.join(" · ")}
+ </p>
+ </div>
+ <Button asChild variant="outline" size="sm">
+ <a href={runExportUrl(sessionId)} target="_blank" rel="noreferrer">
+ <Download aria-hidden />
+ {t("run_inspector.export_raw")}
+ </a>
+ </Button>
</div>
- <a
- className="shrink-0 rounded-md px-2 py-1 text-meta text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- href={runExportUrl(sessionId)}
- target="_blank"
- rel="noreferrer"
- >
- {t("run_inspector.export_raw")}
- </a>
- </div>
- </div>
-
- {/* ── Scrollable body (centered reading column) ───────────── */}
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto w-full max-w-reading space-y-stack p-5">
- <Collapsible
- label={t("run_inspector.environment")}
- open={showEnv}
- onToggle={() => setShowEnv((v) => !v)}
- testId="environment-toggle"
- >
- <EnvironmentPanel env={env} />
- </Collapsible>
-
- <Collapsible
- label={t("run_inspector.deep_dive")}
- open={showMetrics}
- onToggle={() => setShowMetrics((v) => !v)}
- >
- <MetricsPanel run={run} />
- </Collapsible>
-
- {/* Events the recorder stored WITHOUT a turn id — the session frame
- (wake, session open/close, provider switches between turns). They
- belong to no turn card and were previously dropped entirely. */}
- {sessionEvents.length > 0 && (
- <Collapsible
- label={`${t("run_inspector.session_events")} · ${sessionEvents.length}`}
- open={showSessionEvents}
- onToggle={() => setShowSessionEvents((v) => !v)}
- testId="session-events-toggle"
- >
- <EventStream events={sessionEvents} />
- </Collapsible>
+ {tags.length > 0 && (
+ <div className="mt-3">
+ <FeatureBadges tags={tags} />
+ </div>
)}
- {run.turns.map((turn) => (
- <RunTurnCard key={turn.trace_id} turn={turn} />
- ))}
+ <TabBar
+ className="mt-4"
+ tabs={tabs}
+ active={activeTab}
+ onChange={(id) => setTab(id as TabId)}
+ />
</div>
</div>
- </div>
- );
-}
-
-/**
- * The worst latency this run reached, shown only when it is not "ok".
- * `warn` is degraded and `breach` is a fault — it used to be drawn in
- * --foreground, which made a warning the brightest chip in the header.
- */
-function LatencyChip({ status }: { status: string }) {
- if (status === "ok") return null;
- return (
- <Badge variant={status === "breach" ? "fault" : "degraded"}>latency {status}</Badge>
- );
-}
-/**
- * A disclosure row. No box: the header is a row that hovers and the body is
- * separated by the padding it opens into, which is what the rest of the app
- * does. An outline around a closed section is chrome around nothing.
- */
-function Collapsible({
- label, open, onToggle, children, testId = "metrics-toggle",
-}: {
- label: string; open: boolean; onToggle: () => void; children: ReactNode; testId?: string;
-}) {
- return (
- <div>
- <button
- type="button"
- data-testid={testId}
- onClick={onToggle}
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-body font-medium text-foreground transition-colors hover:bg-secondary"
- >
- <span className="text-muted-foreground">{open ? "▾" : "▸"}</span>
- {label}
- </button>
- {open && (
- <div
- data-testid={testId.replace(/-toggle$/, "")}
- className="px-2 pb-stack pt-stack"
- >
- {children}
+ {/* ── Scrollable body (one reading column) ─────────────────── */}
+ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-6 py-5">
+ <div className="mx-auto w-full max-w-3xl">
+ {activeTab === "turns" &&
+ (run.turns.length === 0 ? (
+ // A recorded session that never completed a turn: real, and not
+ // the same thing as a section that failed to render.
+ <p className="text-base text-muted-foreground">
+ {t("run_inspector.no_turns")}
+ </p>
+ ) : (
+ <div className="space-y-3">
+ {run.turns.map((turn) => (
+ <RunTurnCard key={turn.trace_id} turn={turn} />
+ ))}
+ </div>
+ ))}
+ {activeTab === "environment" && <EnvironmentPanel env={env} />}
+ {activeTab === "metrics" && <MetricsPanel run={run} />}
+ {activeTab === "errors" && <RunErrorList turns={run.turns} />}
+ {activeTab === "session_events" && <EventStream events={sessionEvents} />}
</div>
- )}
+ </div>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunList.tsx b/jarvis/ui/web/frontend/src/components/runs/RunList.tsx
index 257f4cf116..224dc21dfd 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunList.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunList.tsx
@@ -1,16 +1,18 @@
import { cn } from "@/lib/utils";
-import type { RunListItem } from "./types";
-import { OutcomeDot } from "./OutcomeBadge";
+
import { FeatureBadges } from "./FeatureBadges";
+import { OutcomeDot } from "./OutcomeBadge";
+import type { RunListItem } from "./types";
/**
* The run rail. One row per recorded session.
*
* Separation is fill, not rule: the row rests on the rail's own ground, hover
- * lifts it to --secondary and selection keeps that lift with the label in the
- * ink ceiling. The old row drew a border AND a 2px left tick AND a background
- * — three devices saying the same thing, of which the fill is the only one an
- * eye actually reads on near-black.
+ * lifts it to --secondary and selection keeps that lift plus the shared
+ * `jarvis-nav-active` tick, which is the one selected-row treatment every rail
+ * in the app wears. The outcome is a dot, latency and faults are words in
+ * their status ink — a run that is merely slow must never read like one that
+ * failed.
*/
export function RunList({
items,
@@ -22,7 +24,7 @@ export function RunList({
onSelect: (id: string) => void;
}) {
return (
- <ul className="space-y-1 p-2" data-testid="run-list">
+ <ul className="space-y-0.5" data-testid="run-list">
{items.map((r) => {
const selected = r.session_id === selectedId;
const slow = r.slo_status === "breach" || r.slo_status === "warn";
@@ -31,29 +33,32 @@ export function RunList({
<button
type="button"
onClick={() => onSelect(r.session_id)}
+ aria-current={selected ? "true" : undefined}
className={cn(
- "flex w-full flex-col gap-1.5 rounded-md px-3 py-2.5 text-left transition-colors",
- selected
- ? "bg-secondary text-foreground-strong"
- : "hover:bg-secondary",
+ "flex w-full flex-col gap-1.5 rounded-md px-3 py-3 text-left transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ selected ? "jarvis-nav-active bg-secondary" : "hover:bg-secondary",
)}
>
<div className="flex items-center gap-2">
<OutcomeDot outcome={r.outcome} />
- <span className="flex-1 truncate text-body">
+ <span className="min-w-0 flex-1 truncate text-base font-medium">
{r.preview || r.session_id.slice(0, 8)}
</span>
- <span className="shrink-0 text-micro tabular-nums text-muted-foreground">
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
{new Date(r.started_ms).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</span>
</div>
- <div className="flex items-center gap-1.5 pl-4 text-micro tabular-nums text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-x-1.5 pl-4 text-sm tabular-nums text-muted-foreground">
<span>{r.turn_count} turns</span>
{r.duration_s !== null && <span>· {r.duration_s.toFixed(1)}s</span>}
{slow && <span className="text-warning">· slow</span>}
+ {r.error_count > 0 && (
+ <span className="text-destructive">· {r.error_count} errors</span>
+ )}
</div>
{r.feature_tags.length > 0 && (
<div className="pl-4">
diff --git a/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx b/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
index 6b9b510780..e46ad59119 100644
--- a/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/RunTurnCard.tsx
@@ -9,16 +9,18 @@
* "show me the events for THIS turn", not "scroll past four panels".
*
* Surfaces: the card is the object, everything nested inside it steps up to
- * the lift token once and stops there — the forensic panel deliberately keeps
- * NO fill so the rows inside it still have a hover to travel to.
+ * --secondary once and stops there. A tab with nothing recorded is not drawn
+ * at all — a disabled tab is a control that lies about being one.
*/
-import { useState } from "react";
+import { useMemo, useState } from "react";
import type { ReactNode } from "react";
-import { Brain, Hourglass, Mic2, Volume2, Zap } from "lucide-react";
+import { Brain, ChevronDown, ChevronRight, Hourglass, Mic2, Volume2, Zap } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
+import { TabBar } from "@/components/layout/SectionTabBar";
import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { fmtInt, fmtMs, useRunLocale } from "./format";
@@ -33,9 +35,7 @@ import { EventStream } from "./EventStream";
import type { RunTurn, TranscriptLine } from "./types";
/**
- * A trace line's role is told by its LABEL, not by a tinted box — four boxes
- * in four hues around four one-line strings was the loudest thing on the card
- * and said less than the word already printed inside each badge. Only `error`
+ * A trace line's role is told by its LABEL, not by a tinted box. Only `error`
* keeps ink, because only `error` is a status.
*/
const ROLE_INK: Record<string, string> = {
@@ -73,31 +73,39 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
// Defaulted, not assumed — a run served by an older backend must render a
// quiet empty tab, never crash the inspector (BUG-008 degrade contract).
const events = turn.events ?? [];
- const tabs: Array<{ id: TabId; label: string; count: number }> = [
- {
- id: "decisions",
- label: t("run_inspector.panel.decision"),
- count: turn.decision_path.length,
- },
- { id: "latency", label: t("run_inspector.panel.latency"), count: turn.latency.length },
- { id: "tools", label: t("run_inspector.panel.tools"), count: turn.tools.length },
- { id: "events", label: t("run_inspector.panel.events"), count: events.length },
- { id: "errors", label: t("run_inspector.panel.errors"), count: turn.errors.length },
- ];
- const hasForensics = tabs.some((x) => x.count > 0);
+
+ // Only the lanes that recorded something. An empty lane is left out rather
+ // than drawn greyed-out, so the strip states what exists in this turn.
+ const tabs = useMemo(
+ () =>
+ (
+ [
+ { id: "decisions", label: t("run_inspector.panel.decision"), count: turn.decision_path.length },
+ { id: "latency", label: t("run_inspector.panel.latency"), count: turn.latency.length },
+ { id: "tools", label: t("run_inspector.panel.tools"), count: turn.tools.length },
+ { id: "events", label: t("run_inspector.panel.events"), count: events.length },
+ { id: "errors", label: t("run_inspector.panel.errors"), count: turn.errors.length },
+ ] as Array<{ id: TabId; label: string; count: number }>
+ ).filter((x) => x.count > 0),
+ [t, turn.decision_path.length, turn.latency.length, turn.tools.length, turn.errors.length, events.length],
+ );
+ const hasForensics = tabs.length > 0;
+ // The remembered tab can be a lane this turn never recorded.
+ const activeTab = tabs.some((x) => x.id === tab) ? tab : (tabs[0]?.id ?? "events");
+ const Chevron = showForensics ? ChevronDown : ChevronRight;
return (
<Card data-testid="run-turn-card">
- <CardContent className="space-y-stack p-5">
+ <CardContent className="space-y-4 p-5 pt-5">
{/* Header: turn # + outcome + brain meta */}
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
- <span className="font-mono text-title font-semibold text-foreground-strong">
+ <h3 className="text-lg font-semibold text-foreground-strong">
Turn {turn.idx + 1}
- </span>
+ </h3>
<OutcomeBadge outcome={turn.outcome} />
</div>
- <div className="flex flex-wrap items-center gap-1.5 text-meta text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-1.5 text-sm text-muted-foreground">
{turn.tier && <Badge variant="outline">{turn.tier}</Badge>}
{(turn.model || turn.provider) && (
<Badge variant="outline" className="font-mono">
@@ -108,31 +116,27 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
printing a bare 0 for a realtime turn billed at session level
would misreport it as free. */}
{turn.usage_recorded ? (
- <>
- <span className="tabular-nums">
- {fmtInt(turn.tokens_in, locale)}+{fmtInt(turn.tokens_out, locale)} tok
- </span>
- {turn.cost_usd > 0 && (
- <span className="tabular-nums">· ${turn.cost_usd.toFixed(4)}</span>
- )}
- </>
+ <span className="tabular-nums">
+ {fmtInt(turn.tokens_in, locale)}+{fmtInt(turn.tokens_out, locale)} tok
+ {turn.cost_usd > 0 && ` · $${turn.cost_usd.toFixed(4)}`}
+ </span>
) : (
- <span className="italic">{t("run_inspector.no_usage")}</span>
+ <span>{t("run_inspector.no_usage")}</span>
)}
</div>
</div>
{/* User */}
{turn.user_text && (
- <Block icon={<Mic2 className="h-3.5 w-3.5" />} label="User">
+ <Block icon={<Mic2 aria-hidden className="h-3.5 w-3.5" />} label="User">
{turn.user_text}
</Block>
)}
{/* Triggered capabilities — the per-turn headline */}
{triggered.length > 0 && (
- <div className="flex flex-wrap items-center gap-2 text-meta">
- <Zap className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="flex flex-wrap items-center gap-2 text-sm">
+ <Zap aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="text-muted-foreground">{t("run_inspector.triggered")}</span>
<FeatureBadges tags={triggered} />
</div>
@@ -140,15 +144,15 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
{/* Assistant reply */}
{turn.jarvis_text && (
- <Block icon={<Volume2 className="h-3.5 w-3.5" />} label={assistantName}>
+ <Block icon={<Volume2 aria-hidden className="h-3.5 w-3.5" />} label={assistantName}>
{turn.jarvis_text}
</Block>
)}
{/* What happened — intermediate phrases, tool outcomes, system outputs */}
{trace.length > 0 && (
- <div className="space-y-1 border-t border-border pt-stack">
- <div className="text-meta text-muted-foreground">
+ <div className="space-y-1 border-t border-border pt-4">
+ <div className="text-sm text-muted-foreground">
{t("run_inspector.what_happened")}
</div>
{trace.map((l, i) => (
@@ -164,66 +168,50 @@ export function RunTurnCard({ turn }: { turn: RunTurn }) {
{/* Think / speak */}
{(turn.think_ms > 0 || turn.speak_ms > 0) && (
- <div className="flex flex-wrap items-center gap-3 text-meta text-muted-foreground">
- <span className="flex items-center gap-1 tabular-nums">
- <Brain className="h-3.5 w-3.5" /> {fmtMs(turn.think_ms)} thinking
+ <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
+ <span className="flex items-center gap-1.5 tabular-nums">
+ <Brain aria-hidden className="h-3.5 w-3.5" /> {fmtMs(turn.think_ms)} thinking
</span>
- <span className="flex items-center gap-1 tabular-nums">
- <Hourglass className="h-3.5 w-3.5" /> {fmtMs(turn.speak_ms)} speaking
+ <span className="flex items-center gap-1.5 tabular-nums">
+ <Hourglass aria-hidden className="h-3.5 w-3.5" /> {fmtMs(turn.speak_ms)} speaking
</span>
</div>
)}
{/* Forensics — deep, on demand */}
{hasForensics && (
- <div className="border-t border-border pt-stack">
+ <div className="border-t border-border pt-3">
<button
type="button"
data-testid="forensics-toggle"
+ aria-expanded={showForensics}
onClick={() => setShowForensics((v) => !v)}
- className="flex items-center gap-1.5 text-meta font-medium text-muted-foreground transition-colors hover:text-foreground"
+ className={cn(
+ "-ml-2 flex items-center gap-1.5 rounded-md px-2 py-1 text-sm 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",
+ )}
>
- <span>{showForensics ? "▾" : "▸"}</span>
+ <Chevron aria-hidden className="h-4 w-4" />
{t("run_inspector.forensics")}
- <span className="tabular-nums">
- · {events.length} {t("run_inspector.stream.events")}
+ <span className="tabular-nums text-foreground-faint">
+ {events.length} {t("run_inspector.stream.events")}
</span>
</button>
{showForensics && (
- <div className="mt-stack space-y-stack">
- <div className="flex flex-wrap gap-1" role="tablist">
- {tabs.map((x) => (
- <button
- key={x.id}
- type="button"
- role="tab"
- aria-selected={tab === x.id}
- data-testid={`forensic-tab-${x.id}`}
- onClick={() => setTab(x.id)}
- disabled={x.count === 0}
- className={`rounded-md px-2 py-1 text-meta font-medium transition-colors ${
- tab === x.id
- ? "bg-secondary text-foreground-strong"
- : x.count === 0
- ? "text-faint-foreground"
- : "text-muted-foreground hover:bg-secondary hover:text-foreground"
- }`}
- >
- {x.label}
- <span className="ml-1 tabular-nums text-muted-foreground">
- {x.count}
- </span>
- </button>
- ))}
- </div>
+ <div className="mt-3 space-y-4">
+ <TabBar
+ tabs={tabs}
+ active={activeTab}
+ onChange={(id) => setTab(id as TabId)}
+ />
<div>
- {tab === "decisions" && <DecisionPath steps={turn.decision_path} />}
- {tab === "latency" && <LatencyWaterfall entries={turn.latency} />}
- {tab === "tools" && <ToolTable tools={turn.tools} />}
- {tab === "events" && (
+ {activeTab === "decisions" && <DecisionPath steps={turn.decision_path} />}
+ {activeTab === "latency" && <LatencyWaterfall entries={turn.latency} />}
+ {activeTab === "tools" && <ToolTable tools={turn.tools} />}
+ {activeTab === "events" && (
<EventStream events={events} truncated={turn.events_truncated} />
)}
- {tab === "errors" && <ErrorPanel errors={turn.errors} />}
+ {activeTab === "errors" && <ErrorPanel errors={turn.errors} />}
</div>
</div>
)}
@@ -260,11 +248,11 @@ function TurnFacts({ turn }: { turn: RunTurn }) {
}
facts.push(["trace_id", turn.trace_id]);
return (
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-micro text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
{facts.map(([k, v]) => (
- <span key={k} className="inline-flex items-center gap-1">
+ <span key={k} className="inline-flex items-center gap-1.5">
<span>{k}</span>
- <span className="font-mono text-foreground">{v}</span>
+ <span className="font-mono text-foreground-secondary">{v}</span>
</span>
))}
</div>
@@ -285,14 +273,14 @@ function Block({
children: ReactNode;
}) {
return (
- <div className="space-y-1">
- <div className="flex items-center gap-1.5 text-meta text-muted-foreground">
+ <div className="space-y-1.5">
+ <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
{icon}
{label}
</div>
- <div className="rounded-md bg-secondary p-stack text-reading text-foreground">
+ <p className="rounded-md bg-secondary px-3 py-2.5 text-base text-foreground [overflow-wrap:anywhere]">
{children}
- </div>
+ </p>
</div>
);
}
@@ -300,12 +288,15 @@ function Block({
function TraceLine({ line }: { line: TranscriptLine }) {
const label = line.spoken_kind || ROLE_LABEL[line.role] || line.role;
return (
- <div className="flex items-start gap-2 rounded-md px-2 py-1.5 text-meta transition-colors hover:bg-secondary">
- <Badge variant="secondary" className="mt-px shrink-0">
+ <div className="flex items-start gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-secondary">
+ <Badge variant="secondary" className="shrink-0">
{label}
</Badge>
<span
- className={`min-w-0 flex-1 break-words ${ROLE_INK[line.role] ?? "text-foreground"}`}
+ className={cn(
+ "min-w-0 flex-1 break-words pt-0.5",
+ ROLE_INK[line.role] ?? "text-foreground-secondary",
+ )}
>
{line.text}
</span>
diff --git a/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx b/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
index ba3c888fae..56089f0ba9 100644
--- a/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
+++ b/jarvis/ui/web/frontend/src/components/runs/ToolTable.tsx
@@ -10,20 +10,21 @@
* stays a compact row.
*/
import { useState } from "react";
-import { ChevronDown, ChevronRight } from "lucide-react";
+import { Check, ChevronDown, ChevronRight } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
import type { ToolCall } from "./types";
/**
* The risk ladder, read left to right: two quiet tiers, then the two that want
- * a human. `ask` is degraded (someone has to answer), `block` is a fault. The
- * old table painted `monitor` sky and `ask` in near-white, which made the
- * second-quietest tier the loudest thing in the row.
+ * a human. `ask` is degraded (someone has to answer), `block` is a fault — and
+ * the two quiet ones stay ink, because "safe" is not a status worth a colour.
*/
-const RISK_STYLE: Record<string, string> = {
- safe: "text-faint-foreground",
+const RISK_INK: Record<string, string> = {
+ safe: "text-foreground-faint",
monitor: "text-muted-foreground",
ask: "text-warning",
block: "text-destructive",
@@ -34,9 +35,7 @@ export function ToolTable({ tools }: { tools: ToolCall[] }) {
const [open, setOpen] = useState<Set<number>>(new Set());
if (tools.length === 0) {
return (
- <span className="text-body text-muted-foreground">
- {t("run_inspector.tools.empty")}
- </span>
+ <p className="text-base text-muted-foreground">{t("run_inspector.tools.empty")}</p>
);
}
const toggle = (i: number) =>
@@ -48,49 +47,48 @@ export function ToolTable({ tools }: { tools: ToolCall[] }) {
});
return (
- <ul className="space-y-1" data-testid="tool-table">
+ <ul className="space-y-0.5" data-testid="tool-table">
{tools.map((tool, i) => {
const detail = tool.command || tool.output || tool.error_line;
const isOpen = open.has(i);
+ const Chevron = isOpen ? ChevronDown : ChevronRight;
return (
- <li
- key={`${tool.name}-${i}`}
- data-tool={tool.name}
- data-success={tool.success}
- className="overflow-hidden rounded-md"
- >
+ <li key={`${tool.name}-${i}`} data-tool={tool.name} data-success={tool.success}>
<button
type="button"
onClick={() => detail && toggle(i)}
- className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-micro transition-colors ${
- detail ? "hover:bg-secondary" : "cursor-default"
- }`}
+ aria-expanded={detail ? isOpen : undefined}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ detail ? "hover:bg-secondary" : "cursor-default",
+ )}
>
- <span className="w-3 shrink-0 text-muted-foreground">
- {detail ? (
- isOpen ? (
- <ChevronDown className="h-3 w-3" />
- ) : (
- <ChevronRight className="h-3 w-3" />
- )
- ) : null}
+ <span className="w-4 shrink-0 text-muted-foreground">
+ {detail && <Chevron aria-hidden className="h-4 w-4" />}
</span>
<span className="min-w-0 flex-1 truncate font-mono text-foreground">
{tool.name}
</span>
{tool.caller && (
- <span className="shrink-0 text-muted-foreground">{tool.caller}</span>
+ <span className="shrink-0 truncate text-muted-foreground">
+ {tool.caller}
+ </span>
)}
{tool.risk_tier && (
<span
- className={`shrink-0 ${RISK_STYLE[tool.risk_tier] ?? "text-muted-foreground"}`}
+ className={cn(
+ "shrink-0",
+ RISK_INK[tool.risk_tier] ?? "text-muted-foreground",
+ )}
>
{tool.risk_tier}
</span>
)}
{tool.approved_by && (
- <span className="shrink-0 text-muted-foreground">
- ✓ {tool.approved_by}
+ <span className="flex shrink-0 items-center gap-1 text-muted-foreground">
+ <Check aria-hidden className="h-3.5 w-3.5" />
+ {tool.approved_by}
</span>
)}
{tool.duration_ms != null && (
@@ -98,20 +96,18 @@ export function ToolTable({ tools }: { tools: ToolCall[] }) {
{tool.duration_ms}ms
</span>
)}
- <span
- className={`shrink-0 font-mono tabular-nums ${
- tool.success ? "text-success" : "text-destructive"
- }`}
- >
- {tool.exit_code != null
- ? `exit ${tool.exit_code}`
- : tool.success
- ? "ok"
- : "fail"}
- </span>
+ <Badge variant={tool.success ? "success" : "destructive"} className="shrink-0">
+ <span className="font-mono tabular-nums">
+ {tool.exit_code != null
+ ? `exit ${tool.exit_code}`
+ : tool.success
+ ? "ok"
+ : "fail"}
+ </span>
+ </Badge>
</button>
{isOpen && detail && (
- <div className="space-y-stack px-3 pb-2 pt-1.5">
+ <div className="space-y-2 py-2 pl-8 pr-2">
{tool.command && (
<Field label={t("run_inspector.tools.command")} value={tool.command} />
)}
@@ -145,11 +141,12 @@ function Field({
}) {
return (
<div>
- <div className="mb-1 text-micro text-muted-foreground">{label}</div>
+ <div className="mb-1 text-xs text-muted-foreground">{label}</div>
<pre
- className={`overflow-x-auto whitespace-pre-wrap break-words rounded-md bg-secondary px-2 py-1.5 font-mono text-micro [overflow-wrap:anywhere] ${
- tone === "error" ? "text-destructive" : "text-foreground"
- }`}
+ className={cn(
+ "max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md bg-secondary px-3 py-2 font-mono text-sm [overflow-wrap:anywhere]",
+ tone === "error" ? "text-destructive" : "text-foreground",
+ )}
>
{value}
</pre>
diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.test.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.test.tsx
new file mode 100644
index 0000000000..4551a425a1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.test.tsx
@@ -0,0 +1,120 @@
+/**
+ * The transcript detail is half of a master-detail pair. When the view is too
+ * narrow to show both columns it owns the whole width, and then it has to
+ * carry the way back to the session rail — on every state it can land in,
+ * including one that is still loading or failed.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+
+import { SessionDetail } from "./SessionDetail";
+import type { SessionDetail as SessionDetailModel } from "./types";
+
+const TRANSLATIONS: Record<string, string> = {
+ "session_detail.back_to_sessions": "Back to sessions",
+ "session_detail.title": "Voice session",
+ "session_detail.turns": "turns",
+ "session_detail.loading": "Loading session",
+ "session_detail.load_error": "Failed to load",
+ "sessions.select_one": "Pick a session",
+ "sessions.no_turns": "No turns",
+ "session_detail.no_turns_suffix": " recorded.",
+ "session_list.hangup_hotkey": "Hotkey",
+};
+
+vi.mock("@/i18n", () => ({
+ translate: (key: string) => TRANSLATIONS[key] ?? key,
+ useT: () => (key: string) => TRANSLATIONS[key] ?? key,
+ useUiLanguage: () => "en",
+}));
+
+vi.mock("@/hooks/useCapabilities", () => ({
+ useCapabilities: () => ({
+ data: { native_file_actions: false, platform: "linux" },
+ }),
+}));
+
+vi.mock("@/hooks/useOutputs", () => ({
+ useOpeners: () => ({ data: [], isLoading: false }),
+ usePreferredOpener: () => ({ data: "" }),
+ useSetPreferredOpener: () => ({ mutate: vi.fn() }),
+}));
+
+afterEach(cleanup);
+
+function detail(): SessionDetailModel {
+ return {
+ session: {
+ id: "sess-1",
+ started_ms: Date.now() - 120_000,
+ ended_ms: Date.now() - 60_000,
+ hangup_reason: "hotkey",
+ turn_count: 0,
+ total_cost_usd: 0,
+ total_tokens_in: 0,
+ total_tokens_out: 0,
+ providers_used: [],
+ language: "en",
+ wake_keyword: "Jarvis",
+ voice_mode: "pipeline",
+ },
+ turns: [],
+ events: [],
+ };
+}
+
+describe("SessionDetail stacked layout", () => {
+ it("offers the way back when the rail is off screen", () => {
+ const onBack = vi.fn();
+ render(
+ <SessionDetail
+ detail={detail()}
+ loading={false}
+ error={null}
+ onBack={onBack}
+ />,
+ );
+
+ fireEvent.click(screen.getByText("Back to sessions"));
+
+ expect(onBack).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows no way back while both columns are on screen", () => {
+ render(<SessionDetail detail={detail()} loading={false} error={null} />);
+
+ expect(screen.queryByText("Back to sessions")).toBeNull();
+ });
+
+ it.each([
+ [
+ "still loading",
+ { detail: undefined, loading: true, error: null },
+ "Loading session",
+ ],
+ [
+ "failed to load",
+ { detail: undefined, loading: false, error: new Error("boom") },
+ "Failed to load",
+ ],
+ [
+ "showing nothing yet",
+ { detail: undefined, loading: false, error: null },
+ "Pick a session",
+ ],
+ ])("is no dead end while %s", (_name, props, marker) => {
+ // Without this the narrow layout traps the reader: a session that never
+ // loads would leave no rail and no way back to it.
+ render(
+ <SessionDetail
+ detail={props.detail}
+ loading={props.loading}
+ error={props.error}
+ onBack={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText(marker)).toBeTruthy();
+ expect(screen.getByText("Back to sessions")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
index ed83f44863..04092f6189 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx
@@ -1,4 +1,5 @@
import {
+ ArrowLeft,
ChevronDown,
Code2,
Copy,
@@ -51,6 +52,11 @@ interface Props {
detail: SessionDetailModel | undefined;
loading: boolean;
error: Error | null;
+ /**
+ * Set only when the view is stacked (narrow): the detail then owns the whole
+ * width and the session rail is off screen, so it has to offer the way back.
+ */
+ onBack?: () => void;
}
/**
@@ -58,10 +64,11 @@ interface Props {
*
* The header is a title row (name, mode badge, when) with one muted line of
* facts and a single Export menu — nine icon buttons in a column were a
- * toolbar nobody asked for. The turns below are a chat timeline capped at
- * the reading measure: no card around each turn, no box around each line.
+ * toolbar nobody asked for. The turns below are a left-aligned transcript
+ * capped at the reading measure: no card around each turn, no box around each
+ * line.
*/
-export function SessionDetail({ detail, loading, error }: Props) {
+export function SessionDetail({ detail, loading, error, onBack }: Props) {
const t = useT();
const uiLanguage = useUiLanguage();
const locale =
@@ -232,21 +239,41 @@ export function SessionDetail({ detail, loading, error }: Props) {
return actions;
}, [t, copyAs, downloadAsFormat, openInEditor]);
+ // The way back to the rail, on every state the stacked layout can land in —
+ // a session that is still loading or failed to load must not be a dead end.
+ const backButton = onBack ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onBack}
+ className="-ml-2 text-muted-foreground"
+ >
+ <ArrowLeft />
+ {t("session_detail.back_to_sessions")}
+ </Button>
+ ) : null;
+
if (loading) {
return (
- <div className="flex h-full items-center justify-center gap-2 text-base text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" />
- {t("session_detail.loading")}
+ <div className="flex h-full min-h-0 flex-col">
+ {backButton && <div className="shrink-0 px-8 pt-5">{backButton}</div>}
+ <div className="flex flex-1 items-center justify-center gap-2 text-base text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("session_detail.loading")}
+ </div>
</div>
);
}
if (error) {
return (
- <div className="flex h-full items-center justify-center p-6">
- <div className="max-w-md rounded-lg border border-destructive/20 bg-destructive/[0.08] p-4 text-base">
- <div className="font-medium text-destructive">{t("session_detail.load_error")}</div>
- <div className="mt-1 text-muted-foreground">{error.message}</div>
+ <div className="flex h-full min-h-0 flex-col">
+ {backButton && <div className="shrink-0 px-8 pt-5">{backButton}</div>}
+ <div className="flex flex-1 items-center justify-center p-6">
+ <div className="max-w-md rounded-lg border border-destructive/20 bg-destructive/[0.08] p-4 text-base">
+ <div className="font-medium text-destructive">{t("session_detail.load_error")}</div>
+ <div className="mt-1 text-muted-foreground">{error.message}</div>
+ </div>
</div>
</div>
);
@@ -254,8 +281,11 @@ export function SessionDetail({ detail, loading, error }: Props) {
if (!detail) {
return (
- <div className="flex h-full items-center justify-center p-6">
- <EmptyState icon={<MessagesSquare />} title={t("sessions.select_one")} />
+ <div className="flex h-full min-h-0 flex-col">
+ {backButton && <div className="shrink-0 px-8 pt-5">{backButton}</div>}
+ <div className="flex flex-1 items-center justify-center p-6">
+ <EmptyState icon={<MessagesSquare />} title={t("sessions.select_one")} />
+ </div>
</div>
);
}
@@ -277,7 +307,8 @@ export function SessionDetail({ detail, loading, error }: Props) {
return (
<div className="flex h-full min-h-0 flex-col">
<div className="shrink-0 border-b border-border px-8 pb-4 pt-5">
- <div className="flex items-start justify-between gap-4">
+ {backButton && <div className="mb-2">{backButton}</div>}
+ <div className="flex flex-wrap items-start justify-between gap-4">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-3">
<h2 className="text-xl font-semibold text-foreground-strong">
diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
index c94a5ad2b8..20bb5cc88c 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx
@@ -172,6 +172,26 @@ describe("TurnCard spoken track", () => {
}
});
+ it("reads as one left-aligned column, not a two-sided chat", () => {
+ // The maintainer's complaint: the user's own words sat in a right-aligned
+ // bubble, so the transcript had two reading edges instead of one. User and
+ // assistant now start at the same left edge and use the same measure.
+ render(
+ <TurnCard
+ turn={turn({ user_text: "Wie spät ist es?", jarvis_text: "Drei Uhr." })} // i18n-allow: German voice fixture
+ />,
+ );
+
+ const userBlock = screen.getByText("Wie spät ist es?");
+ const assistantBlock = screen.getByText("Drei Uhr.");
+ for (const block of [userBlock, assistantBlock]) {
+ expect(block.className).toContain("w-full");
+ expect(block.className).not.toContain("max-w-[85%]");
+ expect(block.parentElement?.className).toContain("items-start");
+ expect(block.parentElement?.className).not.toContain("items-end");
+ }
+ });
+
it("does NOT surface the technical detail in the transcript", () => {
// The technical diagnostic (exit code + raw harness reason) is still recorded
// on the SpeechSpoken event so the Run Inspector can show it, but it must NOT
@@ -229,14 +249,14 @@ describe("TurnCard spoken track", () => {
// Attributed label, not the generic "Background result" — branded with the
// configured assistant name.
expect(screen.getByText("Athena-Agent / Output")).toBeTruthy();
- // The line block is tinted violet (agent) — visibly distinct from the sky
- // tint used by every other spoken kind.
+ // The line block carries the agent tone — visibly distinct from the neutral
+ // tone every other spoken kind uses.
const line = container.querySelector('[data-spoken-kind="subagent"]');
expect(line).not.toBeNull();
expect(line?.getAttribute("data-spoken-tone")).toBe("agent");
});
- it("keeps a generic completion readback on the sky-tinted track", () => {
+ it("keeps a generic completion readback on the neutral status track", () => {
const { container } = render(
<TurnCard
turn={turn()}
diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
index a44a1874bb..6f78252c2f 100644
--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx
@@ -46,11 +46,16 @@ interface Props {
const PROSE = "min-w-0 whitespace-pre-wrap break-words text-base leading-7 [overflow-wrap:anywhere]";
/**
- * One turn of a voice session, drawn like a chat: a quiet turn line (number,
- * time, latency, copy), the user's words as a bubble on the lift surface, the
- * assistant's reply on the card surface, and the facts of the exchange —
- * brain, tokens, cost, tools, how long it thought and spoke — as ONE muted
- * line underneath. No box inside a box.
+ * One turn of a voice session, drawn as a left-aligned document rather than a
+ * two-sided chat: a quiet turn line (number, time, latency, copy), the user's
+ * words in a block on the lift surface, the assistant's reply below it on the
+ * card surface, and the facts of the exchange — brain, tokens, cost, tools,
+ * how long it thought and spoke — as ONE muted line underneath.
+ *
+ * Everything sits in the SAME column and starts at the same left edge, so the
+ * transcript reads top to bottom like a page. Right-aligned user bubbles were
+ * the old shape; they broke the reading line and wasted the measure. No box
+ * inside a box.
*/
export function TurnCard({ turn, displayNumber, spoken = [] }: Props) {
const t = useT();
@@ -161,12 +166,15 @@ export function TurnCard({ turn, displayNumber, spoken = [] }: Props) {
</div>
<div className="space-y-3">
- {/* The user: a bubble on the lift surface, right-aligned like a chat. */}
+ {/* The person speaking: a block on the lift surface, left-aligned and
+ full measure — the same column the reply below it uses. */}
{turn.user_text && (
- <div className="flex flex-col items-end gap-1">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <div className="flex flex-col items-start gap-1">
+ <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<Mic aria-hidden className="h-3.5 w-3.5" />
- <span>User</span>
+ <span className="font-medium text-foreground">
+ {t("session_detail.you")}
+ </span>
<span className="text-foreground-faint">{turn.user_lang}</span>
{polished && (
<Badge variant="secondary" data-testid="turn-polished-badge">
@@ -174,7 +182,7 @@ export function TurnCard({ turn, displayNumber, spoken = [] }: Props) {
</Badge>
)}
</div>
- <div className={cn(PROSE, "max-w-[85%] rounded-lg bg-secondary px-4 py-3 text-foreground")}>
+ <div className={cn(PROSE, "w-full rounded-lg bg-secondary px-4 py-3 text-foreground")}>
{polished ?? turn.user_text}
</div>
{polished && (
@@ -191,7 +199,7 @@ export function TurnCard({ turn, displayNumber, spoken = [] }: Props) {
)}
{polished && showRaw && (
<div
- className={cn(PROSE, "max-w-[85%] rounded-lg border border-dashed border-border px-4 py-3 text-muted-foreground")}
+ className={cn(PROSE, "w-full rounded-lg border border-dashed border-border px-4 py-3 text-muted-foreground")}
data-testid="turn-raw-text"
>
{turn.user_text}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx
new file mode 100644
index 0000000000..6dc6910a83
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx
@@ -0,0 +1,107 @@
+/**
+ * The preview is a placeholder, not a fake Chrome. These pin the honest
+ * states and that Set up hits the existing install route.
+ */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { AgentBrowserPreview } from "@/components/society/card/AgentBrowserPreview";
+import type { SocietyAgent } from "@/components/society/data";
+
+function agent(over: Partial<SocietyAgent> = {}): SocietyAgent {
+ return {
+ agentId: "gamil-agent",
+ name: "Gamil agent",
+ title: "Specialist",
+ description: "",
+ tier: "specialist",
+ provider: "",
+ providerLabel: "",
+ model: "",
+ effort: "",
+ figure: null,
+ palette: { primary: "#2f6f4f", secondary: "#8a5a3b", accent: "#ffd166" },
+ grantMode: "all",
+ toolGrants: [],
+ focus: [],
+ denies: [],
+ approvalRules: { requireApproval: [], alwaysAllow: [] },
+ permissionCeiling: "safe",
+ dailyBudgetUsd: 0,
+ checkpoint: "idle",
+ state: "idle",
+ lifecycle: "active",
+ createdMs: 0,
+ chatSessionId: null,
+ routines: [],
+ stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },
+ ...over,
+ } as SocietyAgent;
+}
+
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchInterval: false } },
+ });
+ return render(
+ <QueryClientProvider client={client}>
+ <AgentBrowserPreview agent={agent()} />
+ </QueryClientProvider>,
+ );
+}
+
+function json(body: unknown, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ } as Response;
+}
+
+let fetchMock: ReturnType<typeof vi.fn>;
+
+describe("AgentBrowserPreview", () => {
+ beforeEach(() => {
+ fetchMock = vi.fn(async (url: string) => {
+ const path = String(url);
+ if (path.includes("/browser/status")) {
+ return json({ installed: false, phase: "idle", percent: 0, detail: "", error: "", running: false });
+ }
+ if (path.includes("/browser/install")) {
+ return json({ started: true, installed: false, phase: "preflight", percent: 0 });
+ }
+ if (path.includes("/browser")) {
+ return json({ installed: false, mode: "own", logged_in_profile: false, running: false });
+ }
+ return json({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ test("names the agent and says the browser is not set up", async () => {
+ mount();
+ await waitFor(() => expect(screen.getByTestId("agent-browser-preview").textContent).toContain("Gamil agent"));
+ expect(screen.getByTestId("agent-browser-preview").textContent).toMatch(/not set up/i);
+ expect(screen.getByTestId("agent-browser-setup")).toBeTruthy();
+ expect(screen.queryByRole("img")).toBeNull();
+ expect(document.querySelector("video")).toBeNull();
+ });
+
+ test("Set up posts the existing install route", async () => {
+ mount();
+ fireEvent.click(await screen.findByTestId("agent-browser-setup"));
+ await waitFor(() => {
+ expect(
+ fetchMock.mock.calls.some(
+ (c) => String(c[0]).includes("/api/society/browser/install") && (c[1] as RequestInit | undefined)?.method === "POST",
+ ),
+ ).toBe(true);
+ });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx
new file mode 100644
index 0000000000..3fb019e1d2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx
@@ -0,0 +1,138 @@
+/**
+ * The agent's browser, as a small screen on the chat-face Options rail.
+ *
+ * There is no live Chrome frame yet (runs are headless; the runner emits
+ * step URLs, not pixels). This box is honest about that: not set up, idle,
+ * signing in (a real OS window), or connecting while a run is in flight.
+ * The 16:10 rounded well is the slot a later screencast can occupy.
+ */
+import { useState } from "react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+import {
+ useAgentBrowser,
+ useAgentBrowserLogin,
+ useBrowserInstallStatus,
+ useStartBrowserInstall,
+} from "../cardData";
+import type { SocietyAgent } from "../data";
+
+import "./agentCard.css";
+
+export interface AgentBrowserPreviewProps {
+ agent: SocietyAgent;
+}
+
+function PreviewFace({ className }: { className?: string }) {
+ return (
+ <svg viewBox="0 0 64 64" className={cn("h-12 w-12", className)} aria-hidden>
+ <circle cx="24" cy="26" r="4.2" fill="currentColor" />
+ <circle cx="40" cy="26" r="4.2" fill="currentColor" />
+ <path
+ d="M22 40c3.6 6.2 16.4 6.2 20 0"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="3.2"
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
+
+export function AgentBrowserPreview({ agent }: AgentBrowserPreviewProps) {
+ const t = useT();
+ const browser = useAgentBrowser(agent.agentId);
+ const install = useBrowserInstallStatus();
+ const startInstall = useStartBrowserInstall();
+ const login = useAgentBrowserLogin();
+ const [busy, setBusy] = useState<"install" | "login" | null>(null);
+ const [error, setError] = useState("");
+
+ const installed = Boolean(browser.data?.installed || install.data?.installed);
+ const running = Boolean(browser.data?.running);
+ const loggedIn = Boolean(browser.data?.loggedIn);
+ const installing = Boolean(install.data && (install.data.running || (install.data.phase !== "idle" && install.data.phase !== "done" && install.data.phase !== "error" && !install.data.installed)));
+ const percent = install.data?.percent ?? 0;
+ const installError = install.data?.error ?? "";
+
+ const status = installing
+ ? t("society.card.browser_setting_up")
+ : running
+ ? t("society.card.browser_connecting")
+ : !installed
+ ? t("society.card.browser_not_setup")
+ : t("society.card.browser_idle");
+
+ const onSetup = async () => {
+ setBusy("install");
+ setError("");
+ try {
+ await startInstall();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t("society.card.browser_error"));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const onSignIn = () => {
+ setBusy("login");
+ setError("");
+ login(agent.agentId);
+ setBusy(null);
+ };
+
+ return (
+ <div className="shrink-0" data-testid="agent-browser-preview">
+ <div
+ className="or-screen flex flex-col items-center justify-center gap-2 px-4"
+ data-busy={running || installing ? "1" : undefined}
+ >
+ <PreviewFace className="or-screen-mark" />
+ <p className="max-w-[16rem] text-center text-[11px] leading-snug text-muted-foreground">
+ {installing && install.data?.detail ? install.data.detail : status}
+ </p>
+ {installing ? (
+ <span className="or-screen-bar" aria-hidden>
+ <span style={{ width: `${Math.max(4, Math.min(100, percent))}%` }} />
+ </span>
+ ) : null}
+ </div>
+ <p className="mt-1.5 truncate text-center text-[11px] text-muted-foreground" title={agent.name}>
+ {t("society.card.screen_of").replace("{0}", agent.name)}
+ </p>
+ <div className="mt-1.5 flex flex-col items-center gap-1">
+ {!installed && !installing ? (
+ <button
+ type="button"
+ className="text-[11px] font-medium text-foreground underline-offset-2 hover:underline disabled:opacity-50"
+ disabled={busy !== null}
+ onClick={() => void onSetup()}
+ data-testid="agent-browser-setup"
+ >
+ {busy === "install" ? t("society.card.browser_setting_up") : t("society.card.browser_setup")}
+ </button>
+ ) : null}
+ {installed && !loggedIn && !running ? (
+ <button
+ type="button"
+ className="text-[11px] font-medium text-foreground underline-offset-2 hover:underline disabled:opacity-50"
+ disabled={busy !== null}
+ title={t("society.card.browser_sign_in_hint")}
+ onClick={onSignIn}
+ data-testid="agent-browser-login"
+ >
+ {t("society.card.browser_sign_in")}
+ </button>
+ ) : null}
+ {(error || installError) && (
+ <p className="text-center text-[11px] text-destructive">{error || installError}</p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default AgentBrowserPreview;
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
index 703b195633..948d4131ca 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
@@ -13,8 +13,8 @@
* which made the thing you actually talk to the smallest pane on screen. Now
* the chat owns the middle six eighths, the roster rail from the island moves
* in on the left so you can switch agents without closing the card, and the
- * right eighth holds the agent's own controls. The first of them is Retire:
- * it archives the row AND has the island play the execution
+ * right rail holds the agent's screen, its routines, and a tucked-away Retire
+ * (⋯). Retire archives the row AND has the island play the execution
* (`world/retirement.ts`), which is why the card closes on its way out.
*
* Clicking the agent's identity in the header (or "Profile") turns the card
@@ -30,13 +30,13 @@
* session (M2). A sample row carries none, and the column says so instead
* of inventing a transcript.
*/
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import { MessageSquare, User, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { useT } from "@/i18n";
+import { useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { AgentSwatch } from "../AgentSwatch";
@@ -44,8 +44,9 @@ import type { SocietyAgent } from "../data";
import { AgentChatPanel } from "../chat/AgentChatPanel";
import { AgentFigureViewer } from "../figures/AgentFigureViewer";
import { RosterRail } from "../roster/RosterRail";
-import { AgentSpecSheet } from "./AgentSpecSheet";
-import { RetireButton } from "./RetireButton";
+import { AgentStudio } from "./AgentStudio";
+import type { FigureRecipe } from "../figures/figureRecipe";
+import { OptionsRail } from "./OptionsRail";
/** Which face of the card is showing. */
type CardFace = "chat" | "profile";
@@ -75,18 +76,33 @@ export function AgentCardOverlay({
onClose,
}: AgentCardOverlayProps) {
const t = useT();
+ useLocaleChunk("society");
const open = agent !== null;
const [face, setFace] = useState<CardFace>("chat");
+ const [preview, setPreview] = useState<FigureRecipe | null>(null);
+ const [editGuard, setEditGuard] = useState({ dirty: false, busy: false });
+ const updateGuard = useCallback((dirty: boolean, busy: boolean) => setEditGuard({ dirty, busy }), []);
+ const leaveEditor = (action: () => void) => {
+ if (editGuard.busy) return;
+ if (editGuard.dirty && !window.confirm(t("society.studio.leave"))) return;
+ setEditGuard({ dirty: false, busy: false });
+ setPreview(null);
+ action();
+ };
// Every opening starts on the chat. The face survives a switch between
// agents inside the card — comparing two profiles is a real thing to do —
// but never leaks from one opening of the card to the next.
useEffect(() => {
- if (!open) setFace("chat");
+ if (!open) {
+ setFace("chat");
+ setPreview(null);
+ setEditGuard({ dirty: false, busy: false });
+ }
}, [open]);
return (
- <Dialog.Root open={open} onOpenChange={(next) => (next ? undefined : onClose())}>
+ <Dialog.Root open={open} onOpenChange={(next) => (next ? undefined : leaveEditor(onClose))}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-40 bg-scrim/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" />
<Dialog.Content
@@ -126,7 +142,7 @@ export function AgentCardOverlay({
size="sm"
variant={face === "profile" ? "secondary" : "outline"}
className="gap-1.5"
- onClick={() => setFace(face === "chat" ? "profile" : "chat")}
+ onClick={() => leaveEditor(() => setFace(face === "chat" ? "profile" : "chat"))}
data-testid="agent-card-face-toggle"
>
{face === "chat" ? (
@@ -146,10 +162,10 @@ export function AgentCardOverlay({
</header>
<div
className={cn(
- "grid min-h-0 flex-1",
+ "agent-card-layout grid min-h-0 flex-1",
face === "chat"
- ? "grid-cols-[minmax(220px,1fr)_minmax(0,6fr)_minmax(190px,1fr)]"
- : "grid-cols-[minmax(220px,1fr)_minmax(300px,3fr)_minmax(320px,4fr)]",
+ ? "grid-cols-[minmax(220px,1fr)_minmax(0,5fr)_minmax(300px,320px)]"
+ : "grid-cols-[minmax(180px,1fr)_minmax(440px,3.5fr)_minmax(260px,3.5fr)]",
)}
>
<RosterRail
@@ -157,8 +173,8 @@ export function AgentCardOverlay({
loading={rosterLoading}
sample={sample}
activeAgentId={agent.agentId}
- onOpen={(id) => onSelectAgent?.(id)}
- onCreate={() => onCreate?.()}
+ onOpen={(id) => { if (id !== agent.agentId) leaveEditor(() => onSelectAgent?.(id)); }}
+ onCreate={() => leaveEditor(() => onCreate?.())}
side="left"
className="w-full"
/>
@@ -171,7 +187,7 @@ export function AgentCardOverlay({
>
<AgentChatPanel agent={agent} roster={roster} />
</section>
- <OptionsRail agent={agent} onRetired={onClose} />
+ <OptionsRail agent={agent} onRetired={onClose} sample={sample} />
</>
) : (
<>
@@ -183,14 +199,16 @@ export function AgentCardOverlay({
aria-label={t("society.card.specs")}
data-testid="agent-card-specs"
>
- <AgentSpecSheet agent={agent} onOpenChat={() => setFace("chat")} onRetired={onClose} />
+ <AgentStudio key={agent.agentId} agent={agent} sample={sample}
+ onOpenChat={() => leaveEditor(() => setFace("chat"))} onRetired={onClose}
+ onPreview={setPreview} onGuardChange={updateGuard} />
</section>
<section
className="society-figure-column relative min-h-0"
aria-label={t("society.card.figure")}
data-testid="agent-card-figure"
>
- <AgentFigureViewer recipe={agent.figure} />
+ <AgentFigureViewer recipe={preview ?? agent.figure} />
</section>
</>
)}
@@ -202,31 +220,3 @@ export function AgentCardOverlay({
</Dialog.Root>
);
}
-
-/**
- * The right eighth: what you can DO to this agent, as opposed to what you can
- * say to it. Retirement is the only entry so far, and it sits at the bottom
- * away from everything else — it is not a control anyone should reach for by
- * accident. The same button is in the profile face's action bar; both go
- * through `RetireButton`.
- */
-function OptionsRail({ agent, onRetired }: { agent: SocietyAgent; onRetired: () => void }) {
- const t = useT();
- return (
- <aside
- className="flex h-full min-h-0 flex-col border-l border-border bg-sidebar"
- aria-label={t("society.card.options")}
- data-testid="agent-card-options"
- >
- <div className="px-3 pt-3">
- <h2 className="font-display text-sm font-semibold tracking-tight text-foreground">
- {t("society.card.options")}
- </h2>
- </div>
- <p className="px-3 pt-2 text-xs text-muted-foreground">{t("society.card.options_hint")}</p>
- <div className="mt-auto p-3">
- <RetireButton agent={agent} onRetired={onRetired} variant="rail" />
- </div>
- </aside>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx
new file mode 100644
index 0000000000..c867bfd795
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.test.tsx
@@ -0,0 +1,96 @@
+/**
+ * The per-agent routines list: titles drop the scheduler prefix, + posts
+ * through the society route, and a new row appears after save.
+ */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { AgentRoutinesList } from "@/components/society/card/AgentRoutinesList";
+
+function mount(agentId = "mailbox") {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchInterval: false } },
+ });
+ return render(
+ <QueryClientProvider client={client}>
+ <AgentRoutinesList agentId={agentId} />
+ </QueryClientProvider>,
+ );
+}
+
+function json(body: unknown, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ } as Response;
+}
+
+let routines: { id: string; title: string; state: string; trigger: unknown }[];
+let fetchMock: ReturnType<typeof vi.fn>;
+
+describe("AgentRoutinesList", () => {
+ beforeEach(() => {
+ routines = [
+ {
+ id: "r1",
+ title: "[agent:Mailbox] Morning inbox",
+ state: "scheduled",
+ trigger: { kind: "every", interval_seconds: 3_600 },
+ },
+ ];
+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ const path = String(url);
+ const method = init?.method ?? "GET";
+ if (path.includes("/routines") && method === "POST") {
+ const body = JSON.parse(String(init?.body ?? "{}")) as { title?: string; prompt?: string };
+ routines = [
+ ...routines,
+ {
+ id: "r2",
+ title: `[agent:Mailbox] ${body.title ?? "new"}`,
+ state: "scheduled",
+ trigger: { kind: "every", interval_seconds: 18_000 },
+ },
+ ];
+ return json({ id: "r2", title: `[agent:Mailbox] ${body.title ?? "new"}` });
+ }
+ if (path.includes("/routines")) return json({ routines });
+ return json({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ test("strips the [agent:Name] prefix the scheduler stores", async () => {
+ mount();
+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Morning inbox"));
+ expect(screen.getByTestId("agent-routines").textContent).not.toContain("[agent:Mailbox]");
+ });
+
+ test("adding a routine posts to this agent and shows the new row", async () => {
+ mount();
+ fireEvent.click(await screen.findByTestId("agent-routines-add"));
+ fireEvent.change(screen.getByPlaceholderText("Title"), { target: { value: "X marketing" } });
+ fireEvent.change(screen.getByPlaceholderText("What to do"), { target: { value: "Draft the post." } });
+ fireEvent.click(screen.getByText("Add"));
+
+ await waitFor(() => {
+ const post = fetchMock.mock.calls.find(
+ (c) => String(c[0]).includes("/api/society/agents/mailbox/routines") && (c[1] as RequestInit | undefined)?.method === "POST",
+ );
+ expect(post).toBeTruthy();
+ const body = JSON.parse(String(post?.[1]?.body));
+ expect(body.title).toBe("X marketing");
+ expect(body.prompt).toBe("Draft the post.");
+ expect(body.schedule.kind).toBe("every");
+ });
+
+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("X marketing"));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
new file mode 100644
index 0000000000..15121b6f52
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutinesList.tsx
@@ -0,0 +1,288 @@
+/**
+ * One agent's routines: the Grok-shaped list with a + that opens an inline
+ * composer. Shared by the chat-face Options rail and the profile spec sheet
+ * so the two faces cannot drift.
+ *
+ * A routine is a tagged Automations task (`POST /api/society/agents/{id}/routines`).
+ * The composer stays inside the rail — the card is already a dialog.
+ */
+import { useMemo, useState } from "react";
+import { Clock, Plus, X } from "lucide-react";
+
+import { BrandedSelect } from "@/components/ui/select";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+import {
+ displayRoutineTitle,
+ routineScheduleLine,
+ useAgentRoutines,
+ useCreateAgentRoutine,
+ type LiveRoutine,
+} from "../cardData";
+import type { AgentRoutine } from "../data";
+
+type Kind = "every" | "daily" | "on_event";
+type Unit = "hours" | "minutes";
+
+export interface AgentRoutinesListProps {
+ agentId: string;
+ /** Sample-roster fallback when the live store is not there. */
+ sampleRoutines?: AgentRoutine[];
+ /** `rail` is the Grok list; `sheet` keeps the spec card's section heading. */
+ variant?: "rail" | "sheet";
+ className?: string;
+}
+
+function sampleToLive(rows: AgentRoutine[]): LiveRoutine[] {
+ return rows.map((row) => ({
+ id: row.id,
+ title: row.label,
+ state: "scheduled",
+ trigger: null,
+ schedule: row.schedule,
+ dueMs: row.nextFire ? Date.parse(row.nextFire) : null,
+ lastRunMs: null,
+ }));
+}
+
+function buildSchedule(kind: Kind, amount: number, unit: Unit, time: string, eventName: string): Record<string, unknown> {
+ if (kind === "on_event") {
+ return { kind: "on_event", event_name: eventName.trim() };
+ }
+ if (kind === "daily") {
+ const [hours, minutes] = time.split(":").map((part) => Number(part));
+ const start = new Date();
+ start.setHours(Number.isFinite(hours) ? hours : 8, Number.isFinite(minutes) ? minutes : 0, 0, 0);
+ return { kind: "every", interval_seconds: 86_400, start_at: start.toISOString() };
+ }
+ const n = Math.max(1, amount);
+ const seconds = unit === "minutes" ? n * 60 : n * 3_600;
+ return { kind: "every", interval_seconds: seconds };
+}
+
+function isActive(state: string): boolean {
+ const s = state.toLowerCase();
+ return s === "scheduled" || s === "active" || s === "enabled" || s === "";
+}
+
+export function AgentRoutinesList({
+ agentId,
+ sampleRoutines,
+ variant = "rail",
+ className,
+}: AgentRoutinesListProps) {
+ const t = useT();
+ const live = useAgentRoutines(agentId);
+ const create = useCreateAgentRoutine();
+ const [open, setOpen] = useState(false);
+ const [title, setTitle] = useState("");
+ const [prompt, setPrompt] = useState("");
+ const [kind, setKind] = useState<Kind>("every");
+ const [amount, setAmount] = useState("5");
+ const [unit, setUnit] = useState<Unit>("hours");
+ const [time, setTime] = useState("08:00");
+ const [eventName, setEventName] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+
+ const sample = useMemo(() => sampleToLive(sampleRoutines ?? []), [sampleRoutines]);
+ const rows: LiveRoutine[] =
+ live.data && live.data.length > 0 ? live.data : sampleRoutines && sampleRoutines.length > 0 && !live.data?.length ? sample : (live.data ?? []);
+
+ const kindOptions = [
+ { value: "every", label: t("society.card.routines_every") },
+ { value: "daily", label: t("society.card.routines_daily") },
+ { value: "on_event", label: t("society.card.routines_on_event") },
+ ];
+ const unitOptions = [
+ { value: "hours", label: t("society.card.routines_hours") },
+ { value: "minutes", label: t("society.card.routines_minutes") },
+ ];
+
+ const valid =
+ title.trim().length > 0 &&
+ prompt.trim().length > 0 &&
+ (kind !== "on_event" || eventName.trim().length > 0) &&
+ (kind !== "every" || Number.parseInt(amount, 10) > 0) &&
+ (kind !== "daily" || /^\d{2}:\d{2}$/.test(time));
+
+ const reset = () => {
+ setTitle("");
+ setPrompt("");
+ setKind("every");
+ setAmount("5");
+ setUnit("hours");
+ setTime("08:00");
+ setEventName("");
+ setError("");
+ };
+
+ const submit = async () => {
+ if (!valid) return;
+ setSaving(true);
+ setError("");
+ try {
+ await create(agentId, {
+ title: title.trim(),
+ prompt: prompt.trim(),
+ schedule: buildSchedule(kind, Number.parseInt(amount, 10) || 1, unit, time, eventName),
+ });
+ reset();
+ setOpen(false);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const fieldCls =
+ "w-full rounded-md border border-border bg-background px-2 py-1.5 text-[12px] text-foreground placeholder:text-muted-foreground outline-none focus:border-border-strong";
+
+ return (
+ <section className={cn("flex min-h-0 flex-col", className)} data-testid="agent-routines">
+ <div className="mb-1.5 flex shrink-0 items-center justify-between gap-2">
+ {variant === "sheet" ? (
+ <h3 className="ac-head">{t("society.card.routines")}</h3>
+ ) : (
+ <h3 className="font-display text-[13px] font-semibold tracking-tight text-foreground">
+ {t("society.card.routines")}
+ {rows.length > 0 ? <span className="ml-1.5 tabular-nums text-muted-foreground">{rows.length}</span> : null}
+ </h3>
+ )}
+ <button
+ type="button"
+ className="rounded p-0.5 text-muted-foreground hover:bg-secondary hover:text-foreground"
+ aria-label={t("society.card.routines_add")}
+ title={t("society.card.routines_add")}
+ aria-expanded={open}
+ onClick={() => {
+ setOpen((v) => !v);
+ setError("");
+ }}
+ data-testid="agent-routines-add"
+ >
+ {open ? <X size={14} aria-hidden /> : <Plus size={14} aria-hidden />}
+ </button>
+ </div>
+
+ {open ? (
+ <form
+ className="mb-2 flex shrink-0 flex-col gap-1.5 rounded-md border border-border bg-background/60 p-2"
+ data-testid="agent-routines-composer"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submit();
+ }}
+ >
+ <label className="sr-only" htmlFor={`routine-title-${agentId}`}>
+ {t("society.card.routines_title")}
+ </label>
+ <input
+ id={`routine-title-${agentId}`}
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ placeholder={t("society.card.routines_title")}
+ className={fieldCls}
+ autoComplete="off"
+ />
+ <label className="sr-only" htmlFor={`routine-prompt-${agentId}`}>
+ {t("society.card.routines_prompt")}
+ </label>
+ <textarea
+ id={`routine-prompt-${agentId}`}
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder={t("society.card.routines_prompt")}
+ rows={3}
+ className={cn(fieldCls, "resize-none")}
+ />
+ <BrandedSelect
+ value={kind}
+ onValueChange={(v) => setKind(v as Kind)}
+ options={kindOptions}
+ ariaLabel={t("society.card.routines_kind")}
+ testId="agent-routines-kind"
+ />
+ {kind === "every" ? (
+ <div className="flex gap-1.5">
+ <input
+ type="number"
+ min={1}
+ step={1}
+ inputMode="numeric"
+ value={amount}
+ onChange={(e) => setAmount(e.target.value)}
+ aria-label={t("society.card.routines_hours")}
+ className={cn(fieldCls, "w-16")}
+ />
+ <div className="min-w-0 flex-1">
+ <BrandedSelect
+ value={unit}
+ onValueChange={(v) => setUnit(v as Unit)}
+ options={unitOptions}
+ ariaLabel={t("society.card.routines_unit")}
+ />
+ </div>
+ </div>
+ ) : null}
+ {kind === "daily" ? (
+ <input
+ type="time"
+ value={time}
+ onChange={(e) => setTime(e.target.value)}
+ aria-label={t("society.card.routines_daily")}
+ className={fieldCls}
+ />
+ ) : null}
+ {kind === "on_event" ? (
+ <input
+ value={eventName}
+ onChange={(e) => setEventName(e.target.value)}
+ placeholder={t("society.card.routines_event_name")}
+ className={fieldCls}
+ autoComplete="off"
+ />
+ ) : null}
+ <button
+ type="submit"
+ disabled={!valid || saving}
+ className="rounded-md bg-primary px-2.5 py-1 text-[12px] font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
+ >
+ {saving ? t("society.card.saving") : t("society.card.routines_save")}
+ </button>
+ {error ? <p className="text-[11px] text-destructive">{error}</p> : null}
+ </form>
+ ) : null}
+
+ <ul className="min-h-0 flex-1 overflow-y-auto">
+ {rows.length === 0 ? (
+ <li className="text-[12px] text-muted-foreground">{t("society.card.no_routines")}</li>
+ ) : (
+ rows.map((routine) => (
+ <li key={routine.id}>
+ <div className="flex items-start gap-2 rounded-md px-0.5 py-1.5 hover:bg-secondary/60">
+ <Clock
+ size={16}
+ aria-hidden
+ className={cn("mt-0.5 shrink-0", isActive(routine.state) ? "text-success" : "text-muted-foreground")}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium leading-tight text-foreground">
+ {displayRoutineTitle(routine.title)}
+ </span>
+ <span className="block truncate text-[11px] leading-tight text-muted-foreground">
+ {routineScheduleLine(routine, t)}
+ </span>
+ </span>
+ </div>
+ </li>
+ ))
+ )}
+ </ul>
+ </section>
+ );
+}
+
+export default AgentRoutinesList;
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
index dafb298f33..f034d21522 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
@@ -39,9 +39,10 @@ import { Switch } from "@/components/ui/switch";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
+import { AgentRoutinesList } from "./AgentRoutinesList";
import { RetireButton } from "./RetireButton";
import { CapabilityChip } from "../CapabilityChip";
-import { useAgentActivity, useAgentRoutines, useAgentSkills, type AgentActivity } from "../cardData";
+import { useAgentActivity, useAgentSkills, type AgentActivity } from "../cardData";
import { PERMISSION_CEILINGS } from "@/lib/societyApi";
import {
@@ -212,7 +213,6 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
const capabilities = useSocietyCapabilities();
const activity = useAgentActivity(agent.agentId);
const skills = useAgentSkills(agent.agentId);
- const routines = useAgentRoutines(agent.agentId);
const setPaused = useSetAgentPaused();
const [busy, setBusy] = useState(false);
const byId = useMemo(() => {
@@ -251,7 +251,6 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
const log = (activity.data?.events ?? []).slice(0, LOG_ROWS);
const activeRuns = activity.data?.activeRuns ?? 0;
const learned = skills.data ?? [];
- const schedule = routines.data ?? [];
const togglePause = async () => {
setBusy(true);
@@ -401,24 +400,11 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
</section>
) : null}
- <section>
- <h3 className="ac-head mb-2">{t("society.card.routines")}</h3>
- {schedule.length === 0 ? (
- <p className="ac-prose text-xs text-muted-foreground">{t("society.card.no_routines")}</p>
- ) : (
- <ul className="ac-prose flex flex-col gap-1.5">
- {schedule.map((routine) => (
- <li key={routine.id} className="flex items-baseline justify-between gap-3 text-sm">
- <span className="truncate">{routine.title}</span>
- <span className="shrink-0 text-xs text-muted-foreground">
- {routine.schedule}
- {routine.dueMs ? ` · ${untilLabel(routine.dueMs, t)}` : ""}
- </span>
- </li>
- ))}
- </ul>
- )}
- </section>
+ <AgentRoutinesList
+ agentId={agent.agentId}
+ sampleRoutines={agent.routines}
+ variant="sheet"
+ />
<section>
<h3 className="ac-head mb-2">{t("society.card.recent")}</h3>
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.test.tsx
new file mode 100644
index 0000000000..c2d06488e0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.test.tsx
@@ -0,0 +1,137 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+import { loadLocaleChunk } from "@/i18n";
+import type { SocietyAgentRow } from "@/lib/societyApi";
+import { rowToAgent } from "../data";
+import { AgentStudio } from "./AgentStudio";
+import { AgentStudioModel } from "./AgentStudioModel";
+import { AgentStudioRoutines } from "./AgentStudioRoutines";
+import { studioDraft, studioPatch, validStudioLimits } from "./agentStudioData";
+
+const ROW: SocietyAgentRow = {
+ agent_id: "studio-test", name: "Test agent", title: "Specialist", description: "Keep notes.", tier: "specialist",
+ parent_agent_id: null, state: "active", avatar: { contract: 1, archetype: "biped", base: "rogue", parts: {} },
+ checkpoint: "idle", provider: "test-provider", model: "model-a", effort: "medium", account_id: "saved-seat",
+ grant_mode: "all", grants: [], focus: ["plugin:notes"], denies: ["plugin:blocked"], skills: null,
+ workspace_dir: "society/studio-test/workspace", wiki_namespace: "society/studio-test", knowledge_scope: "own",
+ permission_ceiling: "monitor", approval_rules: { require_approval: ["plugin:notes:delete"], always_allow: [] },
+ daily_budget_usd: 2, max_concurrent_runs: 1, browser_mode: "own", browser_allowed_domains: [], session_id: "society:studio-test",
+ created_ms: 1000, updated_ms: 1000, stats: { runs: 2, total_cost_usd: 0.5, last_active_ms: null },
+};
+const AGENT = rowToAgent(ROW);
+const ok = (body: object) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
+function wrap(node: React.ReactNode) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ return <QueryClientProvider client={client}>{node}</QueryClientProvider>;
+}
+function props() { return { agent: AGENT, onOpenChat: vi.fn(), onRetired: vi.fn(), onPreview: vi.fn(), onGuardChange: vi.fn() }; }
+beforeAll(async () => { await loadLocaleChunk("society"); });
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+describe("agent studio drafts", () => {
+ test("a budget edit does not overwrite instructions, tool grants or approvals", () => {
+ const base = studioDraft(AGENT);
+ expect(studioPatch(base, { ...base, dailyBudget: "0", concurrentRuns: "3" })).toEqual({ daily_budget_usd: 0, max_concurrent_runs: 3 });
+ });
+ test("rejects empty, non-finite, negative and fractional limits", () => {
+ const base = studioDraft(AGENT);
+ for (const dailyBudget of ["", " ", "-1", "Infinity", "NaN"]) expect(validStudioLimits({ ...base, dailyBudget })).toBe(false);
+ for (const concurrentRuns of ["", "0", "1.5", "Infinity"]) expect(validStudioLimits({ ...base, concurrentRuns })).toBe(false);
+ expect(validStudioLimits({ ...base, dailyBudget: "0", concurrentRuns: "2" })).toBe(true);
+ });
+ test("saves only the edited role and reports persistence", async () => {
+ const fetcher = vi.fn(async (_url: string, init?: RequestInit) => ok({ agent: { ...ROW, ...JSON.parse(String(init?.body ?? "{}")) } }));
+ vi.stubGlobal("fetch", fetcher);
+ render(wrap(<AgentStudio {...props()} />));
+ fireEvent.change(screen.getByRole("textbox", { name: "Role" }), { target: { value: "Research partner" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ await screen.findByText("Changes saved");
+ const writes = fetcher.mock.calls.filter((call) => call[1]?.method === "PATCH");
+ expect(writes).toHaveLength(1);
+ expect(JSON.parse(String(writes[0][1]?.body))).toEqual({ title: "Research partner" });
+ });
+ test("a failed save retains the draft and allows a retry", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ detail: "Save unavailable" }), { status: 503 })));
+ render(wrap(<AgentStudio {...props()} />));
+ fireEvent.change(screen.getByRole("textbox", { name: "Role" }), { target: { value: "Keep this draft" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ await screen.findByRole("alert");
+ expect((screen.getByRole("textbox", { name: "Role" }) as HTMLInputElement).value).toBe("Keep this draft");
+ expect((screen.getByRole("button", { name: "Save changes" }) as HTMLButtonElement).disabled).toBe(false);
+ });
+ test("polling cannot erase a draft, and discard restores the initial values", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => ok({})));
+ const controls = props();
+ const client = new QueryClient();
+ const tree = (agent = AGENT) => <QueryClientProvider client={client}><AgentStudio {...controls} agent={agent} /></QueryClientProvider>;
+ const view = render(tree());
+ fireEvent.change(screen.getByRole("textbox", { name: "Role" }), { target: { value: "Unsaved role" } });
+ view.rerender(tree({ ...AGENT, state: "working" }));
+ expect((screen.getByRole("textbox", { name: "Role" }) as HTMLInputElement).value).toBe("Unsaved role");
+ expect(controls.onGuardChange).toHaveBeenLastCalledWith(true, false);
+ fireEvent.click(screen.getByRole("button", { name: "Discard" }));
+ expect((screen.getByRole("textbox", { name: "Role" }) as HTMLInputElement).value).toBe("Specialist");
+ });
+ test("appearance edits preview immediately without a write; discard restores the figure", async () => {
+ const fetcher = vi.fn(async () => ok({}));
+ vi.stubGlobal("fetch", fetcher);
+ const controls = props();
+ render(wrap(<AgentStudio {...controls} />));
+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Appearance" }), { button: 0 });
+ fireEvent.click(await screen.findByRole("button", { name: "Surprise me" }));
+ await waitFor(() => expect(controls.onGuardChange).toHaveBeenLastCalledWith(true, false));
+ expect(controls.onPreview.mock.lastCall?.[0]).not.toEqual(AGENT.figure);
+ expect(fetcher).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Discard" }));
+ expect(controls.onPreview.mock.lastCall?.[0]).toEqual(AGENT.figure);
+ });
+ test("sample previews never claim to save", () => {
+ render(wrap(<AgentStudio {...props()} sample />));
+ expect((screen.getByRole("button", { name: "Save changes" }) as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByText(/sample agents cannot be saved/)).toBeTruthy();
+ });
+});
+
+test("model changes use the reseating route and preserve the saved account", async () => {
+ const provider = { id: ROW.provider, family: "test", label: "Test provider", runner: "api", models_source: "curated",
+ curated_models: [{ id: "model-a", label: "A" }, { id: "model-b", label: "B" }], default_model: "model-a", keyless: false,
+ native_resume: false, effort_levels: ["low", "medium"], default_effort: "medium", permission_modes: [], default_permission_mode: "", cli_installed: null };
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ if (init?.method === "POST") return ok({ agent: { ...ROW, ...JSON.parse(String(init.body)) } });
+ if (url.includes("/catalog")) return ok({ providers: [provider] });
+ if (url === "/api/jarvis-agent/status") return ok({ mapping: [{ jarvis: ROW.provider, key_set: true, api_key_set: true }] });
+ if (url === "/api/society/providers") return ok({ providers: [{ ...provider, subscription: false, accounts: [] }] });
+ return ok({ agent: ROW });
+ });
+ vi.stubGlobal("fetch", fetcher);
+ render(wrap(<AgentStudioModel agent={AGENT} sample={false} onGuardChange={vi.fn()} />));
+ await screen.findByRole("option", { name: "Test provider" });
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Provider" }).closest("fieldset")?.disabled).toBe(false));
+ fireEvent.change(screen.getByRole("combobox", { name: "Model" }), { target: { value: "model-b" } });
+ await waitFor(() => expect((screen.getByRole("button", { name: "Apply model" }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByRole("button", { name: "Apply model" }));
+ await screen.findByText("Changes saved");
+ const write = fetcher.mock.calls.find((call) => call[1]?.method === "POST");
+ expect(write?.[0]).toBe("/api/society/agents/studio-test/model");
+ expect(JSON.parse(String(write?.[1]?.body))).toEqual({ provider: ROW.provider, model: "model-b", effort: "medium", account_id: "saved-seat" });
+});
+
+test("routine creation sends the agent task and interval, and protects its draft", async () => {
+ const fetcher = vi.fn(async () => ok({ routines: [] }));
+ vi.stubGlobal("fetch", fetcher);
+ const guard = vi.fn();
+ render(wrap(<AgentStudioRoutines agentId={AGENT.agentId} sample={false} onGuardChange={guard} />));
+ fireEvent.click(screen.getByRole("button", { name: "Add routine" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Routine name" }), { target: { value: "Daily summary" } });
+ fireEvent.change(screen.getByRole("textbox", { name: "What should this agent do?" }), { target: { value: "Summarize the project notes." } });
+ expect(guard).toHaveBeenLastCalledWith(true, false);
+ const create = screen.getAllByRole("button", { name: "Add routine" }).find((button) => !(button as HTMLButtonElement).disabled)!;
+ fireEvent.click(create);
+ await waitFor(() => expect(screen.queryByRole("textbox", { name: "Routine name" })).toBeNull());
+ const calls = fetcher.mock.calls as unknown as [string, RequestInit | undefined][];
+ const write = calls.find((call) => call[1]?.method === "POST");
+ expect(write?.[0]).toBe("/api/society/agents/studio-test/routines");
+ expect(JSON.parse(String(write?.[1]?.body))).toEqual({ title: "Daily summary", prompt: "Summarize the project notes.", schedule: { kind: "every", interval_seconds: 86400 } });
+ expect(guard).toHaveBeenLastCalledWith(false, false);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.tsx
new file mode 100644
index 0000000000..2deec33274
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentStudio.tsx
@@ -0,0 +1,168 @@
+import { useCallback, useEffect, useId, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import * as Tabs from "@radix-ui/react-tabs";
+import { Activity, Check, Cpu, MessageSquare, Palette, Pause, Play, Save, Shield, SlidersHorizontal, UserRound } from "lucide-react";
+import { useLocaleChunk, useT } from "@/i18n";
+import { PERMISSION_CEILINGS } from "@/lib/societyApi";
+import { rowToAgent, useSetAgentPaused, type SocietyAgent } from "../data";
+import { useAgentActivity } from "../cardData";
+import type { FigureRecipe } from "../figures/figureRecipe";
+import { LeadBrain, LeadInstructions } from "./LeadSections";
+import { RetireButton } from "./RetireButton";
+import { AgentStudioRoutines } from "./AgentStudioRoutines";
+import { AgentStudioAppearance } from "./AgentStudioAppearance";
+import { AgentStudioModel } from "./AgentStudioModel";
+import { saveStudioAgent, studioDraft, studioPatch, validStudioLimits, type StudioDraft } from "./agentStudioData";
+import "./agentStudio.css";
+
+const SECTIONS = [
+ { id: "profile", icon: UserRound }, { id: "model", icon: Cpu },
+ { id: "appearance", icon: Palette }, { id: "limits", icon: Shield }, { id: "activity", icon: Activity },
+] as const;
+
+export interface AgentStudioProps {
+ agent: SocietyAgent;
+ sample?: boolean;
+ onOpenChat: () => void;
+ onRetired: () => void;
+ onPreview: (recipe: FigureRecipe | null) => void;
+ onGuardChange: (dirty: boolean, busy: boolean) => void;
+}
+
+/** A fresh editing surface; the roster and the figure share the saved identity. */
+export function AgentStudio({ agent, sample = false, onOpenChat, onRetired, onPreview, onGuardChange }: AgentStudioProps) {
+ useLocaleChunk("society");
+ const t = useT();
+ const id = useId();
+ const client = useQueryClient();
+ const setPaused = useSetAgentPaused();
+ const [base, setBase] = useState(() => studioDraft(agent));
+ const [draft, setDraft] = useState(base);
+ const [section, setSection] = useState("profile");
+ const [modelOpened, setModelOpened] = useState(false);
+ const [activityOpened, setActivityOpened] = useState(false);
+ const [modelGuard, setModelGuard] = useState({ dirty: false, busy: false });
+ const [routineGuard, setRoutineGuard] = useState({ dirty: false, busy: false });
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [saved, setSaved] = useState(false);
+ const previous = useRef(agent);
+ const dirty = JSON.stringify(base) !== JSON.stringify(draft);
+ const guard = useCallback((dirty: boolean, busy: boolean) => setModelGuard({ dirty, busy }), []);
+ const guardRoutine = useCallback((dirty: boolean, busy: boolean) => setRoutineGuard({ dirty, busy }), []);
+ useEffect(() => { onGuardChange(dirty || modelGuard.dirty || routineGuard.dirty, busy || modelGuard.busy || routineGuard.busy); }, [dirty, modelGuard, routineGuard, busy, onGuardChange]);
+ useEffect(() => { onPreview(draft.figure); }, [draft.figure, onPreview]);
+ // Background status polling may refresh the row, but never replaces an open draft.
+ useEffect(() => {
+ if (previous.current === agent) return;
+ previous.current = agent;
+ if (dirty || busy) return;
+ const next = studioDraft(agent);
+ setBase(next);
+ setDraft(next);
+ }, [agent, busy, dirty]);
+
+ const edit = <K extends keyof StudioDraft>(key: K, value: StudioDraft[K]) => {
+ setDraft((current) => ({ ...current, [key]: value })); setSaved(false); setError("");
+ };
+ const save = async () => {
+ if (busy || !dirty || !validStudioLimits(draft) || sample) return;
+ setBusy(true); setError("");
+ try {
+ const row = await saveStudioAgent(agent.agentId, studioPatch(base, draft));
+ const next = studioDraft(rowToAgent(row));
+ setBase(next); setDraft(next); setSaved(true);
+ void client.invalidateQueries({ queryKey: ["society", "roster"] });
+ } catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(false); }
+ };
+ const paused = agent.lifecycle === "paused" || agent.state === "paused";
+ const togglePaused = async () => {
+ setBusy(true); setError("");
+ try { await setPaused(agent, !paused); }
+ catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(false); }
+ };
+ const lead = agent.tier === "lead";
+ return <div className="agent-studio" data-testid="agent-studio">
+ <header className="as-header">
+ <div className="as-eyebrow"><SlidersHorizontal size={14} aria-hidden />{t("society.studio.eyebrow")}</div>
+ <h2>{t("society.studio.heading")}</h2>
+ <p>{t("society.studio.subtitle")}</p>
+ <div className="as-identity"><span>{agent.name}</span><span>{t(`society.tier.${agent.tier}`)}</span><span className="as-status">{t(`society.state.${agent.state}`)}</span></div>
+ </header>
+ <Tabs.Root value={section} onValueChange={(value) => { setSection(value); if (value === "model") setModelOpened(true); if (value === "activity") setActivityOpened(true); }} className="as-tabs">
+ <Tabs.List className="as-tab-list" aria-label={t("society.studio.sections")}>
+ {SECTIONS.map(({ id, icon: Icon }) => <Tabs.Trigger className="as-tab" value={id} key={id}><Icon size={16} aria-hidden /><span>{t(`society.studio.${id}`)}</span></Tabs.Trigger>)}
+ </Tabs.List>
+ <div className="as-scroll">
+ <Tabs.Content value="profile" className="as-panel">
+ <div className="as-section-title"><h3>{t("society.studio.profile_heading")}</h3><span>01 / 05</span></div>
+ <fieldset className="as-stack" disabled={busy || sample}>
+ <label className="as-field"><span>{t("society.studio.role")}</span><input value={draft.title} onChange={(event) => edit("title", event.target.value)} placeholder={t("society.studio.role_placeholder")} /></label>
+ {!lead ? <label className="as-field"><span>{t("society.card.description")}</span>
+ <textarea value={draft.description} onChange={(event) => edit("description", event.target.value)} rows={8} placeholder={t("society.studio.instructions_placeholder")} />
+ <small>{t("society.studio.instructions_hint")}</small>
+ </label> : <LeadInstructions />}
+ </fieldset>
+ <div className="as-note"><Shield size={16} aria-hidden /><span>{t("society.studio.tools_hint")}</span></div>
+ <button type="button" className="as-secondary as-wide" onClick={onOpenChat}><MessageSquare size={16} aria-hidden />{t("society.studio.chat_action")}</button>
+ </Tabs.Content>
+ <Tabs.Content value="model" forceMount={modelOpened ? true : undefined} className="as-panel">
+ <div className="as-section-title"><h3>{t("society.studio.model_heading")}</h3><span>02 / 05</span></div>
+ {lead ? <><LeadBrain /><button className="as-secondary" type="button" onClick={onOpenChat}>{t("society.studio.chat_action")}</button></> : modelOpened ? <AgentStudioModel agent={agent} sample={sample} onGuardChange={guard} /> : null}
+ </Tabs.Content>
+ <Tabs.Content value="appearance" className="as-panel">
+ <div className="as-section-title"><h3>{t("society.studio.appearance_heading")}</h3><span>03 / 05</span></div>
+ <fieldset disabled={busy}><AgentStudioAppearance recipe={draft.figure} lead={lead} onChange={(recipe) => edit("figure", recipe)} /></fieldset>
+ </Tabs.Content>
+ <Tabs.Content value="limits" className="as-panel">
+ <div className="as-section-title"><h3>{t("society.studio.limits_heading")}</h3><span>04 / 05</span></div>
+ <fieldset disabled={busy || sample} className="as-stack">
+ <fieldset className="as-stack"><legend className="as-label">{t("society.card.permission")}</legend>
+ <div className="as-ceilings">{PERMISSION_CEILINGS.map((ceiling) => <label key={ceiling} className="as-ceiling" data-selected={draft.ceiling === ceiling}>
+ <input type="radio" name={`${id}-ceiling`} value={ceiling} checked={draft.ceiling === ceiling} onChange={() => edit("ceiling", ceiling)} />
+ <span><strong>{t(`society.ceiling.${ceiling}`)}</strong><small>{t(`society.studio.ceiling_${ceiling}`)}</small></span>
+ </label>)}</div>
+ </fieldset>
+ <div className="as-grid">
+ <label className="as-field"><span>{t("society.studio.budget")}</span><input type="number" min="0" step="0.01" value={draft.dailyBudget} onChange={(event) => edit("dailyBudget", event.target.value)} /><small>{t("society.studio.budget_hint")}</small></label>
+ <label className="as-field"><span>{t("society.studio.concurrency")}</span><input type="number" min="1" step="1" value={draft.concurrentRuns} onChange={(event) => edit("concurrentRuns", event.target.value)} /><small>{t("society.studio.concurrency_hint")}</small></label>
+ </div>
+ {!validStudioLimits(draft) ? <p className="as-error" role="alert">{t("society.studio.invalid_limits")}</p> : null}
+ </fieldset>
+ <div className="as-note">{t("society.studio.spent_today").replace("{amount}", agent.stats.spentTodayUsd.toFixed(2))}</div>
+ </Tabs.Content>
+ <Tabs.Content value="activity" forceMount={activityOpened ? true : undefined} className="as-panel">
+ <div className="as-section-title"><h3>{t("society.studio.activity_heading")}</h3><span>05 / 05</span></div>
+ <div className="as-stats"><div><strong>{agent.stats.runs}</strong><span>{t("society.card.runs")}</span></div><div><strong>${agent.stats.totalCostUsd.toFixed(2)}</strong><span>{t("society.studio.total_spent")}</span></div></div>
+ {activityOpened ? <AgentStudioRoutines agentId={agent.agentId} sample={sample} onGuardChange={guardRoutine} /> : null}
+ <StudioActivity agentId={agent.agentId} />
+ <div className="as-paths"><label>{t("society.card.workspace")}<code>{agent.workspaceDir}</code></label><label>{t("society.studio.notes")}<code>{agent.wikiNamespace}</code></label></div>
+ <div className="as-section-title"><h3>{t("society.studio.manage")}</h3></div>
+ <div className="as-actions"><button type="button" className="as-secondary" disabled={busy || modelGuard.busy || sample} onClick={() => void togglePaused()}>
+ {paused ? <Play size={15} aria-hidden /> : <Pause size={15} aria-hidden />}{t(paused ? "society.card.resume" : "society.card.pause")}
+ </button><fieldset disabled={busy || modelGuard.busy || routineGuard.busy || dirty || modelGuard.dirty || routineGuard.dirty || sample}><RetireButton agent={agent} onRetired={onRetired} /></fieldset></div>
+ </Tabs.Content>
+ </div>
+ </Tabs.Root>
+ <footer className="as-footer">
+ {error ? <p role="alert" className="as-error">{error}</p> : null}
+ {sample ? <p className="as-note">{t("society.studio.sample")}</p> : null}
+ <div className="as-save-row"><span className="as-save-status" role="status">
+ {saved && !dirty ? <><Check size={15} aria-hidden />{t("society.studio.saved")}</> : t(dirty ? "society.studio.unsaved" : "society.studio.ready")}
+ </span><button className="as-secondary" type="button" disabled={!dirty || busy} onClick={() => { setDraft(base); setSaved(false); setError(""); }}>{t("society.studio.discard")}</button>
+ <button type="button" className="as-primary" disabled={!dirty || busy || sample || !validStudioLimits(draft)} onClick={() => void save()}><Save size={15} aria-hidden />{t(busy ? "society.card.saving" : "society.studio.save")}</button>
+ </div>
+ </footer>
+ </div>;
+}
+
+function StudioActivity({ agentId }: { agentId: string }) {
+ const t = useT();
+ const activity = useAgentActivity(agentId);
+ return <div className="as-stack"><h3 className="as-label">{t("society.studio.recent")}</h3>
+ {activity.isLoading ? <p className="as-note">{t("society.studio.loading")}</p> : activity.isError ? <p className="as-error" role="alert">{t("society.studio.load_error")}</p> : !activity.data?.events.length ? <p className="as-note">{t("society.studio.no_activity")}</p> :
+ <ul className="as-activity">{activity.data.events.slice(0, 8).map((entry) => <li key={entry.id}><span>{entry.type}</span><p>{entry.fromAgent} → {entry.toAgent ?? agentId}</p><time dateTime={new Date(entry.tsMs).toISOString()}>{new Date(entry.tsMs).toLocaleString()}</time></li>)}</ul>}
+ </div>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentStudioAppearance.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioAppearance.tsx
new file mode 100644
index 0000000000..ed2a31814e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioAppearance.tsx
@@ -0,0 +1,78 @@
+import { RotateCcw, Shuffle } from "lucide-react";
+import { useT } from "@/i18n";
+import { EDITABLE_CELLS, PALETTE_PRESETS, resolvePalette, shufflePalette, type FigureRecipe } from "../figures/figureRecipe";
+import { CATALOG, catalogBaseFor, isReservedStyle, keepablePartsFor, partsForSlot, slotsWithParts } from "../figures/figureRegistry";
+
+export function AgentStudioAppearance({ recipe, onChange, lead }: {
+ recipe: FigureRecipe;
+ onChange: (recipe: FigureRecipe) => void;
+ lead: boolean;
+}) {
+ const t = useT();
+ const palette = resolvePalette(recipe);
+ const base = catalogBaseFor(recipe);
+ const slots = recipe.model ? [] : slotsWithParts(recipe.archetype, recipe.style ?? null, base?.family ?? null, base?.fitSize ?? null);
+ return (
+ <div className="as-stack">
+ <div className="as-note">{t("society.studio.preview_hint")}</div>
+ {!lead ? <label className="as-field">
+ <span>{t("society.studio.character")}</span>
+ <select value={recipe.model ? "imported" : base?.id ?? `${recipe.archetype}/${recipe.base}`} onChange={(event) => {
+ const next = CATALOG.bases.find((entry) => entry.id === event.target.value);
+ if (!next) return;
+ onChange({ contract: 1, archetype: next.archetype, base: next.base, style: next.styles[0],
+ heightM: next.heightM, palette: { ...next.palette },
+ parts: keepablePartsFor(recipe.parts, next.archetype, next.styles[0], next.family ?? null, next.fitSize) });
+ }}>
+ {recipe.model ? <option value="imported">{t("society.studio.imported")}</option> : null}
+ {CATALOG.bases.filter((entry) => !entry.styles.some(isReservedStyle)).map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}
+ </select>
+ </label> : null}
+ <div className="as-section-title"><h3>{t("society.studio.palette")}</h3>
+ <button type="button" className="as-text-button" onClick={() => onChange({ ...recipe, palette: shufflePalette() })}>
+ <Shuffle size={14} aria-hidden />{t("society.studio.shuffle")}
+ </button>
+ </div>
+ <div className="as-presets">
+ {PALETTE_PRESETS.map((preset) => <button type="button" key={preset.id}
+ className="as-preset" onClick={() => onChange({ ...recipe, palette: { ...preset.palette } })}>
+ <span className="as-preset-colors" aria-hidden>{["primary", "secondary", "accent"].map((cell) =>
+ <span key={cell} style={{ backgroundColor: preset.palette[cell as "primary"] }} />)}</span>
+ {t(`society.presets.${preset.labelKey}`)}
+ </button>)}
+ </div>
+ <div className="as-color-grid">
+ {EDITABLE_CELLS.map((cell) => <label key={cell} className="as-color">
+ <input type="color" value={palette[cell]} onChange={(event) => {
+ const next = { ...recipe.palette, [cell]: event.target.value };
+ if (cell === "skin") delete next.skin_shade;
+ if (cell === "primary") delete next.primary_shade;
+ if (cell === "secondary") delete next.secondary_shade;
+ onChange({ ...recipe, palette: next });
+ }} />
+ <span>{t(`society.cell.${cell}`)}</span>
+ <small>{palette[cell].toUpperCase()}</small>
+ </label>)}
+ </div>
+ {slots.length ? <h3 className="as-section-title">{t("society.studio.wardrobe")}</h3> : null}
+ <div className="as-grid">
+ {slots.map((slot) => <label className="as-field" key={slot}>
+ <span>{t(`society.slot.${slot}`)}</span>
+ <select value={recipe.parts[slot] ?? ""} onChange={(event) => onChange({ ...recipe, parts: { ...recipe.parts, [slot]: event.target.value } })}>
+ <option value="">{t("society.studio.none")}</option>
+ {partsForSlot(slot, recipe.archetype, recipe.style ?? null, base?.family ?? null, base?.fitSize ?? null)
+ .map((part) => <option key={part.id} value={part.id}>{part.label}</option>)}
+ </select>
+ </label>)}
+ </div>
+ <label className="as-field"><span>{t("society.create.height")} <output>{(recipe.heightM ?? base?.heightM ?? 1.75).toFixed(2)} m</output></span>
+ <input type="range" min={recipe.model ? 0.6 : (base?.heightM ?? 1.75) * 0.75}
+ max={recipe.model ? 2.4 : (base?.heightM ?? 1.75) * 1.25} step="0.01"
+ value={recipe.heightM ?? base?.heightM ?? 1.75} onChange={(event) => onChange({ ...recipe, heightM: Number(event.target.value) })} />
+ </label>
+ <button className="as-text-button" type="button" onClick={() => onChange({ ...recipe, palette: {}, heightM: base?.heightM, parts: {} })}>
+ <RotateCcw size={14} aria-hidden />{t("society.studio.reset_look")}
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentStudioModel.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioModel.tsx
new file mode 100644
index 0000000000..a83d4b6821
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioModel.tsx
@@ -0,0 +1,142 @@
+import { useEffect, useMemo, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, Save } from "lucide-react";
+import { useT } from "@/i18n";
+import { fetchAgentChatCatalog, fetchAgentConnections, fetchProviderModels, type CuratedModel } from "@/lib/agentChatApi";
+import { fetchSocietyProviders, type SocietyAgentRow } from "@/lib/societyApi";
+import { joinProviderOptions } from "@/store/agentChat";
+import { brainSeats, effortsFor, modelsFor } from "../create/brainPicker";
+import type { SocietyAgent } from "../data";
+import { saveStudioAgent } from "./agentStudioData";
+
+export function AgentStudioModel({ agent, sample, onGuardChange }: {
+ agent: SocietyAgent;
+ sample: boolean;
+ onGuardChange: (dirty: boolean, busy: boolean) => void;
+}) {
+ const t = useT();
+ const client = useQueryClient();
+ const [selection, setSelection] = useState({ provider: agent.provider, model: agent.model, effort: agent.effort, account_id: "" });
+ const [initial, setInitial] = useState<typeof selection | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [saved, setSaved] = useState(false);
+ const catalog = useQuery({
+ queryKey: ["society", "studio-model-catalog"],
+ queryFn: async () => {
+ const [catalog, connections, providers] = await Promise.all([
+ fetchAgentChatCatalog("society"), fetchAgentConnections(), fetchSocietyProviders(),
+ ]);
+ return { catalog, connections, providers };
+ },
+ enabled: !sample, staleTime: 60_000, retry: false,
+ });
+ const current = useQuery({
+ queryKey: ["society", "studio-model", agent.agentId],
+ queryFn: async () => {
+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`);
+ if (!response.ok) throw new Error(`Agent settings ${response.status}`);
+ return (await response.json() as { agent: SocietyAgentRow }).agent;
+ },
+ enabled: !sample, retry: false,
+ });
+ useEffect(() => {
+ if (initial || !current.data) return;
+ const { provider, model, effort, account_id } = current.data;
+ const next = { provider, model, effort, account_id };
+ setInitial(next);
+ setSelection(next);
+ }, [current.data, initial]);
+
+ const liveIds = useMemo(() => (catalog.data?.catalog.providers ?? [])
+ .filter((provider) => provider.models_source === "live" && (provider.keyless || provider.id === selection.provider))
+ .map((provider) => provider.id), [catalog.data, selection.provider]);
+ const live = useQuery({
+ queryKey: ["society", "studio-live-models", liveIds],
+ queryFn: async () => Object.fromEntries(await Promise.all(liveIds.map(async (id) => [id,
+ (await fetchProviderModels(id)).map((model): CuratedModel => ({ id: model.id, label: model.label ?? model.name ?? model.id })),
+ ]))),
+ enabled: Boolean(catalog.data), retry: false, staleTime: 60_000,
+ });
+ const seats = useMemo(() => {
+ if (!catalog.data) return [];
+ const { catalog: rows, connections, providers } = catalog.data;
+ return brainSeats(joinProviderOptions(rows.providers, connections), providers, live.data ?? {}, new Set(connections.map((row) => row.jarvis)));
+ }, [catalog.data, live.data]);
+ const seat = seats.find((entry) => entry.provider.id === selection.provider) ?? null;
+ const models = modelsFor(seat);
+ const efforts = effortsFor(seat, selection.model);
+ const dirty = Boolean(initial && JSON.stringify(initial) !== JSON.stringify(selection));
+ useEffect(() => { onGuardChange(dirty, busy); }, [dirty, busy, onGuardChange]);
+ const change = (next: typeof selection) => { setSelection(next); setSaved(false); setError(""); };
+ const save = async () => {
+ if (busy || !dirty || !seat) return;
+ setBusy(true);
+ setError("");
+ try {
+ const row = await saveStudioAgent(agent.agentId, selection, true);
+ const next = { provider: row.provider, model: row.model, effort: row.effort, account_id: row.account_id };
+ setSelection(next);
+ setInitial(next);
+ setSaved(true);
+ void client.invalidateQueries({ queryKey: ["society", "roster"] });
+ void client.invalidateQueries({ queryKey: ["society", "studio-model", agent.agentId] });
+ void client.invalidateQueries({ queryKey: ["agent-chat"] });
+ } catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(false); }
+ };
+ const loading = catalog.isLoading || current.isLoading;
+ const failed = catalog.isError || current.isError || live.isError;
+ return <div className="as-stack">
+ <p className="as-note">{t("society.studio.model_hint")}</p>
+ {sample ? <p className="as-note">{t("society.studio.sample")}</p> : null}
+ {loading ? <p role="status">{t("society.chat.models_loading")}</p> : null}
+ {failed ? <div role="alert" className="as-error">{t("society.studio.load_error")}
+ <button type="button" className="as-text-button" onClick={() => { void catalog.refetch(); void current.refetch(); void live.refetch(); }}>{t("society.studio.retry")}</button>
+ </div> : null}
+ <fieldset disabled={busy || loading || sample || !initial} className="as-stack">
+ <label className="as-field"><span>{t("society.studio.provider")}</span>
+ <select value={selection.provider} onChange={(event) => {
+ const next = seats.find((entry) => entry.provider.id === event.target.value);
+ if (!next) return;
+ const model = next.provider.default_model;
+ const ladder = effortsFor(next, model);
+ change({ provider: next.provider.id, model, effort: ladder.includes(next.provider.default_effort) ? next.provider.default_effort : ladder[0] ?? "", account_id: "" });
+ }}>
+ {!seat ? <option value={selection.provider}>{selection.provider || t("society.card.default_brain")}</option> : null}
+ {seats.map((entry) => <option value={entry.provider.id} key={entry.provider.id}>{entry.provider.label}</option>)}
+ </select>
+ </label>
+ <label className="as-field"><span>{t("society.chat.model")}</span>
+ <input list={`studio-models-${agent.agentId}`} value={selection.model} onChange={(event) => {
+ const ladder = effortsFor(seat, event.target.value);
+ change({ ...selection, model: event.target.value, effort: ladder.includes(selection.effort) ? selection.effort : ladder[0] ?? "" });
+ }} placeholder={t("society.chat.model_provider_default")} />
+ <datalist id={`studio-models-${agent.agentId}`}>{models.map((model) => <option key={model.id} value={model.id}>{model.label}</option>)}</datalist>
+ </label>
+ <label className="as-field"><span>{t("society.chat.effort")}</span>
+ <select value={selection.effort} onChange={(event) => change({ ...selection, effort: event.target.value })}>
+ <option value="">{t("society.chat.effort_default")}</option>
+ {selection.effort && !efforts.includes(selection.effort) ? <option value={selection.effort}>{selection.effort}</option> : null}
+ {efforts.filter(Boolean).map((effort) => <option key={effort} value={effort}>{effort}</option>)}
+ </select>
+ </label>
+ {seat?.kind === "subscription" ? <label className="as-field"><span>{t("society.studio.account")}</span>
+ <select value={selection.account_id} onChange={(event) => change({ ...selection, account_id: event.target.value })}>
+ <option value="">{t("society.studio.active_account")}</option>
+ {selection.account_id && !seat.accounts.some((account) => account.id === selection.account_id) ? <option value={selection.account_id}>{t("society.studio.saved_account")}</option> : null}
+ {seat.accounts.map((account) => <option key={account.id} value={account.id}>{account.label}</option>)}
+ </select>
+ </label> : null}
+ </fieldset>
+ {!loading && !failed && !sample && !seat ? <p className="as-note">{t("society.studio.connect_hint")}</p> : null}
+ {error ? <p className="as-error" role="alert">{error}</p> : null}
+ <div className="as-model-actions">
+ <span role="status">{saved ? <><Check size={14} aria-hidden />{t("society.studio.saved")}</> : dirty ? t("society.studio.unsaved") : ""}</span>
+ <button type="button" className="as-secondary" disabled={!dirty || busy} onClick={() => { if (initial) change(initial); }}>{t("society.studio.discard")}</button>
+ <button type="button" className="as-primary" disabled={!dirty || busy || !seat || failed} onClick={() => void save()}>
+ <Save size={15} aria-hidden />{t(busy ? "society.card.saving" : "society.studio.save_model")}
+ </button>
+ </div>
+ </div>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentStudioRoutines.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioRoutines.tsx
new file mode 100644
index 0000000000..ab63891219
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentStudioRoutines.tsx
@@ -0,0 +1,53 @@
+import { useEffect, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Plus } from "lucide-react";
+import { useT } from "@/i18n";
+import { useAgentRoutines } from "../cardData";
+
+export function AgentStudioRoutines({ agentId, sample, onGuardChange }: {
+ agentId: string;
+ sample: boolean;
+ onGuardChange: (dirty: boolean, busy: boolean) => void;
+}) {
+ const t = useT();
+ const client = useQueryClient();
+ const routines = useAgentRoutines(sample ? null : agentId);
+ const [open, setOpen] = useState(false);
+ const [title, setTitle] = useState("");
+ const [prompt, setPrompt] = useState("");
+ const [hours, setHours] = useState("24");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const dirty = Boolean(title || prompt || hours !== "24");
+ useEffect(() => { onGuardChange(dirty, busy); }, [dirty, busy, onGuardChange]);
+ const reset = () => { setTitle(""); setPrompt(""); setHours("24"); setError(""); setOpen(false); };
+ const valid = title.trim() && prompt.trim() && Number.isFinite(Number(hours)) && Number(hours) >= 1;
+ const create = async () => {
+ if (!valid || sample || busy) return;
+ setBusy(true); setError("");
+ try {
+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/routines`, {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ title: title.trim(), prompt: prompt.trim(), schedule: { kind: "every", interval_seconds: Number(hours) * 3600 } }),
+ });
+ if (!response.ok) throw new Error(`${t("society.studio.routine_error")} (HTTP ${response.status})`);
+ reset();
+ void client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] });
+ } catch (err) { setError(err instanceof Error ? err.message : String(err)); }
+ finally { setBusy(false); }
+ };
+ return <section className="as-stack">
+ <div className="as-section-title"><h3>{t("society.card.routines")}</h3>
+ <button type="button" className="as-text-button" disabled={sample || open} onClick={() => setOpen(true)}><Plus size={15} aria-hidden />{t("society.studio.add_routine")}</button>
+ </div>
+ {open ? <fieldset disabled={busy} className="as-stack">
+ <label className="as-field"><span>{t("society.studio.routine_title")}</span><input autoFocus value={title} maxLength={200} onChange={(event) => setTitle(event.target.value)} /></label>
+ <label className="as-field"><span>{t("society.studio.routine_task")}</span><textarea rows={3} maxLength={16000} value={prompt} onChange={(event) => setPrompt(event.target.value)} /></label>
+ <label className="as-field"><span>{t("society.studio.routine_hours")}</span><input type="number" min="1" step="1" value={hours} onChange={(event) => setHours(event.target.value)} /></label>
+ <div className="as-actions"><button type="button" className="as-primary" disabled={!valid || busy} onClick={() => void create()}>{t(busy ? "society.card.saving" : "society.studio.add_routine")}</button>
+ <button type="button" className="as-secondary" onClick={reset}>{t("society.studio.discard")}</button></div>
+ {error ? <p role="alert" className="as-error">{error}</p> : null}
+ </fieldset> : null}
+ {routines.data?.length ? <ul className="as-activity">{routines.data.map((routine) => <li key={routine.id}><strong>{routine.title.replace(/^\[agent:[^\]]+\]\s*/i, "")}</strong><p>{routine.schedule}</p></li>)}</ul> : <p className="as-note">{t("society.card.no_routines")}</p>}
+ </section>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx
new file mode 100644
index 0000000000..bd9a76a759
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx
@@ -0,0 +1,148 @@
+/**
+ * The chat-face Options rail: preview + this agent's routines, Retire behind
+ * ⋯ (still two-press), and a switch of agent swaps both panes.
+ */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { OptionsRail } from "@/components/society/card/OptionsRail";
+import type { SocietyAgent } from "@/components/society/data";
+
+function agent(over: Partial<SocietyAgent> = {}): SocietyAgent {
+ return {
+ agentId: "gamil-agent",
+ name: "Gamil agent",
+ title: "Specialist",
+ description: "",
+ tier: "specialist",
+ provider: "",
+ providerLabel: "",
+ model: "",
+ effort: "",
+ figure: null,
+ palette: { primary: "#2f6f4f", secondary: "#8a5a3b", accent: "#ffd166" },
+ grantMode: "all",
+ toolGrants: [],
+ focus: [],
+ denies: [],
+ approvalRules: { requireApproval: [], alwaysAllow: [] },
+ permissionCeiling: "safe",
+ dailyBudgetUsd: 0,
+ checkpoint: "idle",
+ state: "idle",
+ lifecycle: "active",
+ createdMs: 0,
+ chatSessionId: null,
+ routines: [],
+ stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },
+ ...over,
+ } as SocietyAgent;
+}
+
+function mount(row: SocietyAgent, onRetired = vi.fn()) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchInterval: false } },
+ });
+ return {
+ onRetired,
+ client,
+ ...render(
+ <QueryClientProvider client={client}>
+ <OptionsRail agent={row} onRetired={onRetired} />
+ </QueryClientProvider>,
+ ),
+ };
+}
+
+function json(body: unknown, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ } as Response;
+}
+
+let fetchMock: ReturnType<typeof vi.fn>;
+
+describe("OptionsRail", () => {
+ beforeEach(() => {
+ fetchMock = vi.fn(async (url: string) => {
+ const path = String(url);
+ if (path.includes("/browser/status")) {
+ return json({ installed: false, phase: "idle", percent: 0, running: false });
+ }
+ if (path.includes("/gamil-agent/browser")) {
+ return json({ installed: false, mode: "own", logged_in_profile: false, running: false });
+ }
+ if (path.includes("/scout/browser")) {
+ return json({ installed: false, mode: "own", logged_in_profile: false, running: false });
+ }
+ if (path.includes("/gamil-agent/routines")) {
+ return json({
+ routines: [
+ {
+ id: "gm1",
+ title: "[agent:Gamil] Inbox sweep",
+ state: "scheduled",
+ trigger: { kind: "every", interval_seconds: 18_000 },
+ },
+ ],
+ });
+ }
+ if (path.includes("/scout/routines")) {
+ return json({
+ routines: [
+ {
+ id: "sc1",
+ title: "[agent:Scout] Dawn brief",
+ state: "scheduled",
+ trigger: { kind: "every", interval_seconds: 86_400 },
+ },
+ ],
+ });
+ }
+ if (path.includes("/api/society/agents")) return json({ agents: [] });
+ return json({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ test("shows the screen and this agent's routines, not a full-width Retire", async () => {
+ mount(agent());
+ await waitFor(() => expect(screen.getByTestId("agent-browser-preview")).toBeTruthy());
+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));
+ expect(screen.queryByTestId("agent-card-retire")).toBeNull();
+ expect(screen.getByTestId("agent-card-options-more")).toBeTruthy();
+ });
+
+ test("Retire lives behind ⋯ and still only arms on the first press", async () => {
+ const { onRetired } = mount(agent());
+ fireEvent.click(screen.getByTestId("agent-card-options-more"));
+ const retire = await screen.findByTestId("agent-card-retire");
+ fireEvent.click(retire);
+ expect(retire.dataset.armed).toBe("true");
+ expect(onRetired).not.toHaveBeenCalled();
+ expect(fetchMock.mock.calls.filter((c) => (c[1] as RequestInit | undefined)?.method === "DELETE")).toHaveLength(0);
+ });
+
+ test("switching agent swaps the caption and the routines list", async () => {
+ const { rerender, client } = mount(agent());
+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));
+
+ rerender(
+ <QueryClientProvider client={client}>
+ <OptionsRail agent={agent({ agentId: "scout", name: "Scout" })} onRetired={() => undefined} />
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Dawn brief"));
+ expect(screen.getByTestId("agent-browser-preview").textContent).toContain("Scout");
+ expect(screen.getByTestId("agent-routines").textContent).not.toContain("Inbox sweep");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
new file mode 100644
index 0000000000..fa6bcd23af
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
@@ -0,0 +1,93 @@
+/**
+ * The chat-face right column: this agent's browser screen, its routines, and
+ * a tucked-away Retire control. Extracted from AgentCardOverlay so the overlay
+ * stays the layout and this file owns what you can do to the agent.
+ */
+import { useEffect, useRef, useState } from "react";
+import { MoreHorizontal } from "lucide-react";
+
+import { useT } from "@/i18n";
+
+import type { SocietyAgent } from "../data";
+import { AgentBrowserPreview } from "./AgentBrowserPreview";
+import { AgentRoutinesList } from "./AgentRoutinesList";
+import { RetireButton } from "./RetireButton";
+
+export interface OptionsRailProps {
+ agent: SocietyAgent;
+ onRetired: () => void;
+ /** True when rows come from the sample roster rather than society.db. */
+ sample?: boolean;
+}
+
+export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailProps) {
+ const t = useT();
+ const [more, setMore] = useState(false);
+ const moreRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ setMore(false);
+ }, [agent.agentId]);
+
+ useEffect(() => {
+ if (!more) return;
+ const onDown = (e: MouseEvent) => {
+ if (!moreRef.current?.contains(e.target as Node)) setMore(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setMore(false);
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [more]);
+
+ return (
+ <aside
+ className="flex h-full min-h-0 flex-col border-l border-border bg-sidebar"
+ aria-label={t("society.card.options")}
+ data-testid="agent-card-options"
+ >
+ <header className="flex shrink-0 items-center justify-between gap-2 px-3 pb-1 pt-3">
+ <h2 className="font-display text-sm font-semibold tracking-tight text-foreground">
+ {t("society.card.options")}
+ </h2>
+ <div ref={moreRef} className="relative">
+ <button
+ type="button"
+ className="rounded-md p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"
+ aria-label={t("society.card.options_more")}
+ aria-expanded={more}
+ aria-haspopup="menu"
+ onClick={() => setMore((v) => !v)}
+ data-testid="agent-card-options-more"
+ >
+ <MoreHorizontal className="h-4 w-4" aria-hidden />
+ </button>
+ {more ? (
+ <div
+ role="menu"
+ className="absolute right-0 top-full z-10 mt-1 w-56 rounded-md border border-border bg-popover p-3 shadow-float"
+ >
+ <RetireButton agent={agent} onRetired={onRetired} variant="rail" />
+ </div>
+ ) : null}
+ </div>
+ </header>
+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-3 pb-3 pt-2">
+ <AgentBrowserPreview agent={agent} />
+ <AgentRoutinesList
+ agentId={agent.agentId}
+ sampleRoutines={sample ? agent.routines : undefined}
+ variant="rail"
+ className="min-h-0 flex-1"
+ />
+ </div>
+ </aside>
+ );
+}
+
+export default OptionsRail;
diff --git a/jarvis/ui/web/frontend/src/components/society/card/agentCard.css b/jarvis/ui/web/frontend/src/components/society/card/agentCard.css
index 1188c2e8a3..d49fd6f3d2 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/agentCard.css
+++ b/jarvis/ui/web/frontend/src/components/society/card/agentCard.css
@@ -346,6 +346,56 @@
font-size: 12px;
color: hsl(var(--destructive));
}
+/* Options-rail screen: the Grok-shaped preview, in theme tokens. */
+.or-screen {
+ position: relative;
+ aspect-ratio: 16 / 10;
+ overflow: hidden;
+ border-radius: 12px;
+ border: 1px solid hsl(var(--border));
+ background:
+ radial-gradient(120% 90% at 50% 0%, hsl(var(--secondary)) 0%, hsl(var(--background)) 62%);
+ box-shadow: inset 0 1px 0 hsl(var(--foreground) / 0.04);
+}
+.or-screen-mark {
+ color: hsl(var(--foreground));
+ opacity: 0.92;
+}
+.or-screen[data-busy] .or-screen-mark {
+ animation: or-breathe 1.8s ease-in-out infinite;
+}
+.or-screen-bar {
+ position: absolute;
+ right: 16px;
+ bottom: 14px;
+ left: 16px;
+ height: 3px;
+ overflow: hidden;
+ border-radius: 99px;
+ background: hsl(var(--foreground) / 0.08);
+}
+.or-screen-bar > span {
+ display: block;
+ height: 100%;
+ background: hsl(var(--foreground) / 0.45);
+}
+@keyframes or-breathe {
+ 0%,
+ 100% {
+ opacity: 0.55;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 1;
+ transform: scale(1.04);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .or-screen[data-busy] .or-screen-mark {
+ animation: none;
+ }
+}
+
.ac-retire-error + .ac-btn {
margin-left: 8px;
}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/agentStudio.css b/jarvis/ui/web/frontend/src/components/society/card/agentStudio.css
new file mode 100644
index 0000000000..2ee3814ceb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/agentStudio.css
@@ -0,0 +1,84 @@
+.agent-studio { height:100%; min-height:0; display:flex; flex-direction:column; color:hsl(var(--foreground)); background:hsl(var(--background)); font-family:var(--font-sans, Inter, sans-serif); }
+.as-header { padding:26px 28px 20px; border-bottom:1px solid hsl(var(--border)); background:linear-gradient(120deg,hsl(var(--primary)/.08),transparent 75%); }
+.as-eyebrow { display:flex; align-items:center; gap:8px; color:hsl(var(--muted-foreground)); font-size:11px; font-weight:650; letter-spacing:.15em; text-transform:uppercase; }
+.as-header h2 { margin:12px 0 6px; font-family:"Space Grotesk",sans-serif; font-size:clamp(23px,2vw,32px); line-height:1.2; font-weight:600; letter-spacing:-.04em; }
+.as-header > p { color:hsl(var(--muted-foreground)); font-size:13px; line-height:1.6; }
+.as-identity { display:flex; align-items:center; flex-wrap:wrap; gap:8px; margin-top:18px; font-size:12px; }
+.as-identity > span:first-child { font-weight:650; }
+.as-identity > span:not(:first-child) { padding:3px 8px; border:1px solid hsl(var(--border)); border-radius:5px; color:hsl(var(--muted-foreground)); }
+.as-identity .as-status { margin-left:auto; }
+.as-tabs { display:flex; flex:1; flex-direction:column; min-height:0; }
+.as-tab-list { display:flex; flex-shrink:0; gap:4px; padding:10px 20px 0; border-bottom:1px solid hsl(var(--border)); overflow-x:auto; }
+.as-tab { display:flex; flex:1; justify-content:center; align-items:center; gap:7px; min-height:44px; padding:8px; white-space:nowrap; border-bottom:2px solid transparent; color:hsl(var(--muted-foreground)); font-size:12px; font-weight:550; }
+.as-tab[data-state=active] { border-color:hsl(var(--primary)); color:hsl(var(--foreground)); background:hsl(var(--primary)/.07); }
+.as-scroll { overflow:auto; flex:1; min-height:0; scrollbar-gutter:stable; }
+.as-panel { padding:24px 28px 32px; display:flex; flex-direction:column; gap:22px; }
+.as-panel[data-state=inactive] { display:none; }
+.as-section-title { display:flex; align-items:center; justify-content:space-between; gap:12px; font-size:14px; font-weight:600; }
+.as-section-title > span { color:hsl(var(--muted-foreground)); font-size:10px; font-family:monospace; }
+.as-stack { display:flex; flex-direction:column; gap:16px; min-width:0; }
+.as-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; }
+.as-field { display:flex; min-width:0; flex-direction:column; gap:8px; font-size:13px; }
+.as-field > span,.as-label { font-weight:600; font-size:12px; }
+.as-field > span { display:flex; justify-content:space-between; gap:10px; }
+.as-field small,.as-note { color:hsl(var(--muted-foreground)); font-size:12px; font-weight:400; line-height:1.6; }
+.as-field input:not([type=range]),.as-field select,.as-field textarea { width:100%; min-width:0; min-height:44px; padding:10px 12px; border:1px solid hsl(var(--border)); border-radius:7px; background:hsl(var(--card)); color:hsl(var(--foreground)); font-size:13px; line-height:1.5; }
+.as-field textarea { resize:vertical; min-height:150px; }
+.as-field input[type=range] { width:100%; min-height:32px; accent-color:hsl(var(--primary)); }
+.as-note { display:flex; align-items:flex-start; gap:10px; }
+.as-note > svg { flex-shrink:0; margin-top:2px; }
+.agent-studio button { cursor:pointer; transition:background-color 150ms,color 150ms,border-color 150ms; }
+.agent-studio :is(button,input,select,textarea):focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:3px; }
+.agent-studio button:disabled,.agent-studio fieldset:disabled { opacity:.55; }
+.agent-studio button:disabled { cursor:not-allowed; }
+.as-primary,.as-secondary,.as-text-button { display:inline-flex; align-items:center; justify-content:center; gap:7px; min-height:40px; padding:8px 12px; border-radius:7px; font-size:12px; font-weight:550; }
+.as-primary { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border:1px solid hsl(var(--primary)); }
+.as-primary:hover:not(:disabled) { background:hsl(var(--primary)/.85); }
+.as-secondary { background:hsl(var(--card)); border:1px solid hsl(var(--border)); }
+.as-secondary:hover:not(:disabled),.as-preset:hover,.as-tab:hover { background:hsl(var(--secondary)); }
+.as-text-button { color:hsl(var(--muted-foreground)); padding:5px 0; justify-content:flex-start; }
+.as-text-button:hover { color:hsl(var(--foreground)); }
+.as-wide { width:100%; justify-content:flex-start; }
+.as-footer { padding:14px 20px; border-top:1px solid hsl(var(--border)); background:hsl(var(--card)); display:flex; flex-direction:column; gap:10px; }
+.as-save-row,.as-model-actions,.as-actions { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
+.as-save-status,.as-model-actions > span { display:flex; align-items:center; gap:6px; margin-right:auto; font-size:11px; color:hsl(var(--muted-foreground)); }
+.as-error { color:hsl(var(--destructive)); font-size:12px; line-height:1.5; overflow-wrap:anywhere; }
+.as-ceilings { display:flex; flex-direction:column; gap:8px; }
+.as-ceiling { display:flex; align-items:center; gap:12px; border:1px solid hsl(var(--border)); padding:13px; border-radius:7px; cursor:pointer; }
+.as-ceiling[data-selected=true] { border-color:hsl(var(--primary)); background:hsl(var(--primary)/.07); }
+.as-ceiling input { accent-color:hsl(var(--primary)); }
+.as-ceiling strong,.as-ceiling small { display:block; font-size:12px; }
+.as-ceiling small { color:hsl(var(--muted-foreground)); margin-top:4px; font-weight:400; }
+.as-presets { display:grid; grid-template-columns:repeat(auto-fit,minmax(84px,1fr)); gap:8px; }
+.as-preset { border:1px solid hsl(var(--border)); border-radius:7px; padding:9px; font-size:11px; text-align:left; }
+.as-preset-colors { display:flex; height:22px; border-radius:3px; overflow:hidden; margin-bottom:8px; }
+.as-preset-colors > span { flex:1; }
+.as-color-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
+.as-color { display:grid; grid-template-columns:38px 1fr; align-items:center; column-gap:10px; padding:8px; border:1px solid hsl(var(--border)); border-radius:7px; font-size:12px; }
+.as-color input { grid-row:span 2; width:36px; height:36px; cursor:pointer; background:none; border:0; }
+.as-color small { color:hsl(var(--muted-foreground)); font-size:10px; font-family:monospace; }
+.as-stats { display:grid; grid-template-columns:1fr 1fr; border:1px solid hsl(var(--border)); border-radius:8px; }
+.as-stats > div { display:flex; flex-direction:column; gap:4px; padding:16px; }
+.as-stats > div + div { border-left:1px solid hsl(var(--border)); }
+.as-stats strong { font-size:24px; font-family:"Space Grotesk",sans-serif; }
+.as-stats span,.as-paths { font-size:12px; color:hsl(var(--muted-foreground)); }
+.as-paths { display:flex; flex-direction:column; gap:14px; }
+.as-paths code { display:block; margin-top:4px; overflow-wrap:anywhere; color:hsl(var(--foreground)); }
+.as-activity li { border-bottom:1px solid hsl(var(--border)); padding:10px 0; font-size:12px; }
+.as-activity li > span { color:hsl(var(--muted-foreground)); font-size:10px; text-transform:uppercase; }
+.as-activity p { overflow-wrap:anywhere; margin-top:4px; }
+@media(max-width:1100px) { .as-header { padding:20px; } .as-panel { padding:20px; } .as-tab-list { padding-inline:8px; } .as-tab { flex-direction:column; gap:4px; font-size:10px; } }
+@media(prefers-reduced-motion:reduce) { .agent-studio button { transition:none; } }
+@media(max-width:1000px) {
+ [data-face=profile] .agent-card-layout { grid-template-columns:minmax(400px,1fr) minmax(0,.8fr); }
+ [data-face=profile] .agent-card-layout > :first-child { display:none; }
+}
+@media(max-width:740px) {
+ [data-face=profile] .agent-card-layout { display:flex; flex-direction:column; overflow-y:auto; }
+ [data-face=profile] [data-testid=agent-card-specs] { flex-shrink:0; height:max(620px,calc(100dvh - 110px)); }
+ [data-face=profile] [data-testid=agent-card-figure] { flex-shrink:0; height:320px; }
+ .as-header,.as-panel { padding:18px 16px; }
+ .as-grid { grid-template-columns:minmax(0,1fr); }
+ .as-field input:not([type=range]),.as-field select,.as-field textarea { font-size:16px; }
+ .as-save-status { flex-basis:100%; }
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/agentStudioData.ts b/jarvis/ui/web/frontend/src/components/society/card/agentStudioData.ts
new file mode 100644
index 0000000000..1d8ca7aea7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/agentStudioData.ts
@@ -0,0 +1,58 @@
+import type { SocietyAgentRow } from "@/lib/societyApi";
+import { defaultFigureFor, type SocietyAgent } from "../data";
+import type { FigureRecipe } from "../figures/figureRecipe";
+
+export interface StudioDraft {
+ title: string;
+ description: string;
+ dailyBudget: string;
+ concurrentRuns: string;
+ ceiling: SocietyAgent["permissionCeiling"];
+ figure: FigureRecipe;
+}
+
+export function studioDraft(agent: SocietyAgent): StudioDraft {
+ return {
+ title: agent.title,
+ description: agent.description,
+ dailyBudget: String(agent.dailyBudgetUsd),
+ concurrentRuns: String(agent.maxConcurrentRuns),
+ ceiling: agent.permissionCeiling,
+ figure: agent.figure ?? defaultFigureFor(agent.agentId, agent.tier),
+ };
+}
+
+/** Only edited fields cross the wire: unrelated saves cannot re-derive focus. */
+export function studioPatch(base: StudioDraft, draft: StudioDraft) {
+ const patch: Partial<Pick<SocietyAgentRow,
+ "title" | "description" | "daily_budget_usd" | "max_concurrent_runs" | "permission_ceiling" | "avatar"
+ >> = {};
+ if (base.title !== draft.title) patch.title = draft.title.trim();
+ if (base.description !== draft.description) patch.description = draft.description;
+ if (base.dailyBudget !== draft.dailyBudget) patch.daily_budget_usd = Number(draft.dailyBudget);
+ if (base.concurrentRuns !== draft.concurrentRuns) patch.max_concurrent_runs = Number(draft.concurrentRuns);
+ if (base.ceiling !== draft.ceiling) patch.permission_ceiling = draft.ceiling;
+ if (JSON.stringify(base.figure) !== JSON.stringify(draft.figure)) patch.avatar = { ...draft.figure };
+ return patch;
+}
+
+export function validStudioLimits(draft: StudioDraft): boolean {
+ const budget = Number(draft.dailyBudget);
+ const runs = Number(draft.concurrentRuns);
+ return draft.dailyBudget.trim() !== "" && Number.isFinite(budget) && budget >= 0
+ && draft.concurrentRuns.trim() !== "" && Number.isSafeInteger(runs) && runs >= 1;
+}
+
+export async function saveStudioAgent(agentId: string, body: object, model = false): Promise<SocietyAgentRow> {
+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}${model ? "/model" : ""}`, {
+ method: model ? "POST" : "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ const payload = await response.json() as { agent?: SocietyAgentRow; detail?: unknown };
+ if (!response.ok || !payload.agent) {
+ const detail = payload.detail;
+ throw new Error(typeof detail === "string" ? detail : `Save failed (HTTP ${response.status})`);
+ }
+ return payload.agent;
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts b/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts
new file mode 100644
index 0000000000..6d6739668a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/cardData.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ describeTrigger,
+ displayRoutineTitle,
+ routineScheduleLine,
+} from "@/components/society/cardData";
+
+const phrases: Record<string, string> = {
+ "society.card.sched_every_day": "Every day",
+ "society.card.sched_every_day_at": "Every day at {0}",
+ "society.card.sched_every_days": "Every {0} days",
+ "society.card.sched_every_hour": "Every hour",
+ "society.card.sched_every_hours": "Every {0} hours",
+ "society.card.sched_every_minute": "Every minute",
+ "society.card.sched_every_minutes": "Every {0} minutes",
+ "society.card.sched_every_seconds": "Every {0} seconds",
+ "society.card.sched_once_in": "Once, in {0}",
+ "society.card.sched_on": "On {0}",
+ "society.card.sched_at": "At {0}",
+ "society.card.sched_at_fixed": "At a fixed time",
+};
+
+const t = (key: string) => phrases[key] ?? key;
+
+describe("displayRoutineTitle", () => {
+ test("strips the scheduler's agent prefix", () => {
+ expect(displayRoutineTitle("[agent:Mailbox] Morning inbox")).toBe("Morning inbox");
+ });
+
+ test("leaves a bare title alone", () => {
+ expect(displayRoutineTitle("Morning inbox")).toBe("Morning inbox");
+ });
+});
+
+describe("describeTrigger", () => {
+ test("every five hours", () => {
+ expect(describeTrigger({ kind: "every", interval_seconds: 18_000 }, t)).toBe("Every 5 hours");
+ });
+
+ test("every hour is singular", () => {
+ expect(describeTrigger({ type: "every", interval_seconds: 3_600 }, t)).toBe("Every hour");
+ });
+
+ test("every day", () => {
+ expect(describeTrigger({ kind: "every", interval_seconds: 86_400 }, t)).toBe("Every day");
+ });
+
+ test("on an event", () => {
+ expect(describeTrigger({ kind: "on_event", event_name: "pr.merged" }, t)).toBe("On pr.merged");
+ });
+});
+
+describe("routineScheduleLine", () => {
+ test("prefers the live trigger over a leftover sample phrase", () => {
+ expect(
+ routineScheduleLine({ trigger: { kind: "every", interval_seconds: 3_600 }, schedule: "daily 07:00" }, t),
+ ).toBe("Every hour");
+ });
+
+ test("falls back to the sample phrase when there is no trigger", () => {
+ expect(routineScheduleLine({ trigger: null, schedule: "daily 07:00" }, t)).toBe("daily 07:00");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.ts
index fd7d4dae4c..e17a581fd7 100644
--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts
+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts
@@ -11,7 +11,8 @@
* every one of them returns an empty list when the backend is not there. The
* card treats them as enrichment and never blocks on them.
*/
-import { useQuery } from "@tanstack/react-query";
+import { useCallback } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
/** One line of what the agent did or was told, from the society event log. */
export interface AgentActivity {
@@ -37,13 +38,44 @@ export interface LiveRoutine {
id: string;
title: string;
state: string;
- /** Readable schedule ("every 24 h", "at 07:00"), built from the raw trigger. */
+ /** Raw TaskSpec trigger; formatted in the list so the phrase follows the UI language. */
+ trigger: unknown;
+ /**
+ * Preformatted schedule when there is no trigger (sample roster rows). The
+ * list prefers `describeTrigger(trigger)` and falls back to this.
+ */
schedule: string;
/** Next fire in epoch ms, or null when the scheduler knows none. */
dueMs: number | null;
lastRunMs: number | null;
}
+/** Per-agent browser status from `GET /api/society/agents/{id}/browser`. */
+export interface AgentBrowserStatus {
+ installed: boolean;
+ mode: string;
+ loggedIn: boolean;
+ running: boolean;
+}
+
+/** Machine-wide browser-use venv install, from `GET /api/society/browser/status`. */
+export interface BrowserInstallStatus {
+ installed: boolean;
+ phase: string;
+ percent: number;
+ detail: string;
+ error: string;
+ running: boolean;
+}
+
+const AGENT_TITLE_PREFIX = /^\[agent:[^\]]+\]\s*/i;
+
+/** The scheduler stores `[agent:Name] Title`; the list shows just the title. */
+export function displayRoutineTitle(title: string): string {
+ const stripped = title.replace(AGENT_TITLE_PREFIX, "").trim();
+ return stripped || title;
+}
+
interface EnvelopeRow {
event_id?: string;
seq?: number;
@@ -72,34 +104,66 @@ function humanEvery(seconds: number): string {
return `${Math.round(seconds)} s`;
}
+/** Clock time from an ISO timestamp, or empty when it is not a real date. */
+function clockFromIso(value: unknown): string {
+ if (typeof value !== "string") return "";
+ const at = new Date(value);
+ if (Number.isNaN(at.getTime())) return "";
+ return at.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
+}
+
/**
* The raw trigger object into one readable phrase.
*
* The scheduler stores a `TaskSpec` trigger (`jarvis/society/routines.py`),
* not a sentence, and there is no server-side rendering of it — so the shapes
* are mapped here, and an unknown kind falls back to its own name rather than
- * to an invented schedule.
+ * to an invented schedule. `t` is the locale function so the phrase follows
+ * the UI language; tests pass the identity `(k) => k` and assert on keys.
*/
-export function describeTrigger(trigger: unknown): string {
+export function describeTrigger(trigger: unknown, t: (key: string) => string = (key) => key): string {
if (!trigger || typeof trigger !== "object") return "";
- const t = trigger as Record<string, unknown>;
- const kind = String(t.kind ?? t.type ?? "");
- if (kind === "every" && typeof t.interval_seconds === "number") {
- return `every ${humanEvery(t.interval_seconds)}`;
+ const raw = trigger as Record<string, unknown>;
+ const kind = String(raw.kind ?? raw.type ?? "");
+ if (kind === "every" && typeof raw.interval_seconds === "number") {
+ const seconds = raw.interval_seconds;
+ const time = clockFromIso(raw.start_at);
+ if (seconds % 86_400 === 0) {
+ const days = seconds / 86_400;
+ if (days === 1 && time) return t("society.card.sched_every_day_at").replace("{0}", time);
+ if (days === 1) return t("society.card.sched_every_day");
+ return t("society.card.sched_every_days").replace("{0}", String(days));
+ }
+ if (seconds % 3_600 === 0) {
+ const hours = seconds / 3_600;
+ if (hours === 1) return t("society.card.sched_every_hour");
+ return t("society.card.sched_every_hours").replace("{0}", String(hours));
+ }
+ if (seconds % 60 === 0) {
+ const minutes = seconds / 60;
+ if (minutes === 1) return t("society.card.sched_every_minute");
+ return t("society.card.sched_every_minutes").replace("{0}", String(minutes));
+ }
+ return t("society.card.sched_every_seconds").replace("{0}", String(Math.round(seconds)));
+ }
+ if (kind === "at_time" && typeof raw.iso_timestamp === "string") {
+ const clock = clockFromIso(raw.iso_timestamp);
+ return clock ? t("society.card.sched_at").replace("{0}", clock) : t("society.card.sched_at_fixed");
}
- if (kind === "at_time" && typeof t.iso_timestamp === "string") {
- const at = new Date(t.iso_timestamp);
- return Number.isNaN(at.getTime())
- ? "at a fixed time"
- : `at ${at.toLocaleString(undefined, { hour: "2-digit", minute: "2-digit" })}`;
+ if (kind === "after_delay" && typeof raw.delay_seconds === "number") {
+ return t("society.card.sched_once_in").replace("{0}", humanEvery(raw.delay_seconds));
}
- if (kind === "after_delay" && typeof t.delay_seconds === "number") {
- return `once, in ${humanEvery(t.delay_seconds)}`;
+ if (kind === "on_event" && typeof raw.event_name === "string") {
+ return t("society.card.sched_on").replace("{0}", raw.event_name);
}
- if (kind === "on_event" && typeof t.event_name === "string") return `on ${t.event_name}`;
return kind;
}
+/** The line the routines list shows: live trigger, else the sample's own phrase. */
+export function routineScheduleLine(routine: Pick<LiveRoutine, "trigger" | "schedule">, t: (key: string) => string): string {
+ return describeTrigger(routine.trigger, t) || routine.schedule;
+}
+
/** Nanoseconds (what the task store stores) to epoch ms, or null. */
function nsToMs(value: unknown): number | null {
return typeof value === "number" && value > 0 ? Math.round(value / 1e6) : null;
@@ -166,7 +230,8 @@ export function useAgentRoutines(agentId: string | null) {
return useQuery({
queryKey: ["society", "agent-routines", agentId],
enabled: Boolean(agentId),
- staleTime: 30_000,
+ staleTime: 5_000,
+ refetchInterval: import.meta.env.MODE === "test" ? false : 5_000,
retry: false,
queryFn: async (): Promise<LiveRoutine[]> => {
const body = await getJson<{
@@ -183,10 +248,129 @@ export function useAgentRoutines(agentId: string | null) {
id: String(r.id ?? i),
title: String(r.title ?? ""),
state: String(r.state ?? ""),
- schedule: describeTrigger(r.trigger),
+ trigger: r.trigger ?? null,
+ schedule: "",
dueMs: nsToMs(r.due_at_ns),
lastRunMs: nsToMs(r.last_run_ns),
}));
},
});
}
+
+/** This agent's own browser profile: installed / logged-in / running. */
+export function useAgentBrowser(agentId: string | null) {
+ return useQuery({
+ queryKey: ["society", "agent-browser", agentId],
+ enabled: Boolean(agentId),
+ staleTime: 3_000,
+ refetchInterval: import.meta.env.MODE === "test" ? false : 5_000,
+ retry: false,
+ queryFn: async (): Promise<AgentBrowserStatus> => {
+ const body = await getJson<{
+ installed?: boolean;
+ mode?: string;
+ logged_in_profile?: boolean;
+ running?: boolean;
+ }>(`/api/society/agents/${encodeURIComponent(agentId ?? "")}/browser`);
+ return {
+ installed: Boolean(body?.installed),
+ mode: String(body?.mode ?? "own"),
+ loggedIn: Boolean(body?.logged_in_profile),
+ running: Boolean(body?.running),
+ };
+ },
+ });
+}
+
+function installIsBusy(row: BrowserInstallStatus | undefined): boolean {
+ if (!row) return false;
+ if (row.running) return true;
+ if (row.installed || row.phase === "idle" || row.phase === "done" || row.phase === "error") return false;
+ return row.phase.length > 0;
+}
+
+/** The one-click browser-use venv on this machine. */
+export function useBrowserInstallStatus() {
+ return useQuery({
+ queryKey: ["society", "browser-install"],
+ staleTime: 2_000,
+ refetchInterval: (query) =>
+ import.meta.env.MODE === "test" ? false : installIsBusy(query.state.data) ? 1_000 : 15_000,
+ retry: false,
+ queryFn: async (): Promise<BrowserInstallStatus> => {
+ const body = await getJson<{
+ installed?: boolean;
+ phase?: string;
+ percent?: number;
+ detail?: string;
+ error?: string;
+ running?: boolean;
+ }>("/api/society/browser/status");
+ return {
+ installed: Boolean(body?.installed),
+ phase: String(body?.phase ?? "idle"),
+ percent: Number(body?.percent ?? 0),
+ detail: String(body?.detail ?? ""),
+ error: String(body?.error ?? ""),
+ running: Boolean(body?.running),
+ };
+ },
+ });
+}
+
+export function useStartBrowserInstall() {
+ const client = useQueryClient();
+ return useCallback(async () => {
+ const res = await fetch("/api/society/browser/install", { method: "POST" });
+ if (!res.ok) throw new Error(`install ${res.status}`);
+ await client.invalidateQueries({ queryKey: ["society", "browser-install"] });
+ await client.invalidateQueries({ queryKey: ["society", "agent-browser"] });
+ }, [client]);
+}
+
+/**
+ * Opens the headed login window on this computer. The request stays open
+ * until that window closes (up to 15 minutes), so the caller must not await
+ * it as if it were a short POST — fire and let the status poll catch up.
+ */
+export function useAgentBrowserLogin() {
+ const client = useQueryClient();
+ return useCallback((agentId: string) => {
+ void fetch(`/api/society/agents/${encodeURIComponent(agentId)}/browser/login`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ start_url: "" }),
+ }).finally(() => {
+ void client.invalidateQueries({ queryKey: ["society", "agent-browser", agentId] });
+ });
+ }, [client]);
+}
+
+export function useCreateAgentRoutine() {
+ const client = useQueryClient();
+ return useCallback(
+ async (
+ agentId: string,
+ body: { title: string; prompt: string; schedule: Record<string, unknown> },
+ ): Promise<{ id: string; title: string }> => {
+ const res = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/routines`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const detail = (await res.json().catch(() => null)) as { reason?: unknown; detail?: unknown } | null;
+ const reason =
+ (detail && typeof detail.reason === "string" && detail.reason) ||
+ (detail && typeof detail.detail === "string" && detail.detail) ||
+ String(res.status);
+ throw new Error(reason);
+ }
+ const payload = (await res.json()) as { id?: string; title?: string };
+ await client.invalidateQueries({ queryKey: ["society", "agent-routines", agentId] });
+ await client.invalidateQueries({ queryKey: ["tasks"] });
+ return { id: String(payload.id ?? ""), title: String(payload.title ?? body.title) };
+ },
+ [client],
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index 51e9075af3..2ead9be71d 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -1,3 +1,4 @@
+import { InternalMessageBubble } from "@/components/agentchat/InternalMessageBubble";
/**
* The model card's chat column, kept deliberately plain (maintainer,
* 2026-09-02): bubbles, a time stamp, one pill-shaped composer with a "+"
@@ -544,13 +545,15 @@ function Transcript({
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
<div className={cn(CHAT_MEASURE, "flex flex-col gap-2")}>
{items.map((item) => {
- const ts = item.type === "user" ? item.tsMs : item.type === "turn" ? item.startedMs : 0;
+ const ts = item.type === "user" || item.type === "internal" ? item.tsMs : item.type === "turn" ? item.startedMs : 0;
const stamp = ts && ts - lastStamp > STAMP_GAP_MS ? ts : 0;
if (stamp) lastStamp = ts;
return (
<div key={item.id} className="flex flex-col gap-2">
{stamp ? <TimeStamp ms={stamp} /> : null}
- {item.type === "user" ? (
+ {item.type === "internal" ? (
+ <InternalMessageBubble item={item} />
+ ) : item.type === "user" ? (
<UserBubble item={item} />
) : item.type === "turn" ? (
<TurnBubble item={item} onDecide={onDecide} />
diff --git a/jarvis/ui/web/frontend/src/components/society/world/ConversationScene.tsx b/jarvis/ui/web/frontend/src/components/society/world/ConversationScene.tsx
index 4ef2d4c730..11ea70da5c 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/ConversationScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/ConversationScene.tsx
@@ -19,21 +19,35 @@
import { memo, useEffect, useMemo, useRef } from "react";
import { Html } from "@react-three/drei";
import { useFrame, useThree } from "@react-three/fiber";
-import type { Group, Mesh } from "three";
+import { Object3D, type Group, type InstancedMesh, type Mesh } from "three";
import { fill, useT } from "@/i18n";
import type { SocietyAgent } from "../data";
import { WORLD_HERO_SCALE } from "./WalkerFigure";
import { useKit } from "./WorldKit";
+import { useCameraStore } from "./cameraStore";
+import { ZOOM_WIDTHS_M } from "./worldCamera";
import { useBuildingPoses } from "./buildingPoses";
import {
+ ARC_BEADS,
+ CALL_MIN_S,
+ CALL_SECONDS,
MAX_CONCURRENT,
MIN_FACE_M,
ROOM_RING_R_M,
+ arcApexFor,
+ arcPoint,
+ beadAlive,
+ beadRadiusFor,
+ beadScale,
bubbleSeconds,
classify,
+ clamp01,
driftedApart,
facingBetween,
+ hangupSweep,
+ pingFade,
+ pingScale,
pipScale,
tangentFacing,
type ConvoKind,
@@ -47,6 +61,7 @@ import {
type Conversation,
} from "./conversationStore";
import { buildIsland, groundY, tileToWorld } from "./islandLayout";
+import { SIGNAL } from "./worldPalette";
import { walkerPins, type WalkerPin } from "./walkerRegistry";
/**
@@ -78,6 +93,10 @@ const LISTEN_HIDE_M = 4;
const ROOM_SIGN_Y_M = 9.5;
/** The marker ring under a figure that is in a conversation, in metres. */
const SPEAK_RING_R_M = 1.15;
+/** How wide a ping ring grows at a caller's head, in metres. */
+const PING_R_M = 1.9;
+/** Reused for every instance matrix; three.js wants an Object3D, not a matrix. */
+const DUMMY = new Object3D();
/** Head height for a figure whose recipe carries no height. */
const DEFAULT_HEAD_M = 2.0;
@@ -140,6 +159,7 @@ function stage(
// Decided once and cached on the row: a wandering figure must not flip a
// running conversation from a talk into a call mid-sentence.
const kind: ConvoKind = talk.kind ?? (other ? classify(distanceM) : "talk");
+ if (talk.kind === null && other) useConversationStore.getState().setKind(talk.key, kind);
out.push({ talk, speaker: anchor, partner: other, kind, distanceM, slot });
});
return out;
@@ -338,11 +358,15 @@ function ConversationView({
</Html>
)}
</group>
+ {talk.kind === "call" && talk.partnerId && (
+ <CallLink talk={talk} byId={byId} paused={paused} />
+ )}
{talk.partnerId && talk.line && (
<ListeningBubble
byId={byId}
partnerId={talk.partnerId}
speakerId={talk.speakerId}
+ calling={talk.kind === "call" ? speakerName : ""}
slot={slot}
/>
)}
@@ -350,16 +374,166 @@ function ConversationView({
);
}
+/**
+ * The signal between two figures the island cannot show side by side: a chain
+ * of beads on a quadratic arc from head to head, with a wave of light running
+ * from the sender to the receiver, and a ping ring at each end while it
+ * connects.
+ *
+ * One shared `<instancedMesh>` and one shared material for the whole link. The
+ * wave is animated by SCALE, never by opacity — `worldMaterials.halo()` caches
+ * a material per colour and opacity, so a per-frame opacity would grow that
+ * cache without bound.
+ */
+function CallLink({
+ talk,
+ byId,
+ paused,
+}: {
+ talk: Conversation;
+ byId: Map<string, SocietyAgent>;
+ paused: boolean;
+}) {
+ const kit = useKit();
+ const beads = useRef<InstancedMesh>(null);
+ const pingA = useRef<Mesh>(null);
+ const pingB = useRef<Mesh>(null);
+ /** When the last line ENDED, so the hang-up sweep has something to run from. */
+ const quietSince = useRef(0);
+ /** When this call first went out — its floor, so it cannot flicker. */
+ const openedAt = useRef(0);
+ const dark = useRef<InstancedMesh>(null);
+
+ useFrame(() => {
+ const mesh = beads.current;
+ if (!mesh) return;
+ const [next] = stage([talk], byId, walkerPins());
+ const partner = next?.partner ?? null;
+ if (!next || !partner) {
+ mesh.visible = false;
+ if (pingA.current) pingA.current.visible = false;
+ if (pingB.current) pingB.current.visible = false;
+ return;
+ }
+
+ // The clock is the STORE's, not a local ref: `lineStartedMs` survives a
+ // remount and is the same number in every open window, so two people
+ // watching the same call see the same signal in the same place.
+ const now = Date.now();
+ if (openedAt.current === 0) openedAt.current = now;
+ // A call holds the island for a moment even when the sentence is short.
+ const young = (now - openedAt.current) / 1000 < CALL_MIN_S;
+ const speaking = talk.line !== null || young;
+ if (speaking) quietSince.current = 0;
+ else if (quietSince.current === 0) quietSince.current = now;
+
+ const age = paused
+ ? CALL_SECONDS.dial + CALL_SECONDS.arc
+ : (now - (speaking ? talk.lineStartedMs || openedAt.current : quietSince.current)) / 1000;
+
+ // The head of the wave reaches across over `dial` + `arc`, the whole line
+ // stays lit while the sentence is up, and it runs off on hang-up.
+ const reach = CALL_SECONDS.dial + CALL_SECONDS.arc;
+ const front = speaking ? clamp01(age / reach) : 1;
+ const sweep = speaking ? 0 : hangupSweep(age);
+
+ // The sender is whoever spoke last, so an answer sends the wave back.
+ const from = next.speaker;
+ const to = partner;
+ const { map } = buildIsland();
+ const head = {
+ x: from.pin.x,
+ y: groundY(map, from.pin.x, from.pin.z) + from.headY,
+ z: from.pin.z,
+ };
+ const tail = {
+ x: to.pin.x,
+ y: groundY(map, to.pin.x, to.pin.z) + to.headY,
+ z: to.pin.z,
+ };
+ const apex = arcApexFor(next.distanceM);
+ const beadR = beadRadiusFor(ZOOM_WIDTHS_M[useCameraStore.getState().zoom]);
+
+ mesh.visible = sweep < 1;
+ let drawn = 0;
+ for (let i = 0; i < ARC_BEADS; i++) {
+ const scale = beadAlive(i, ARC_BEADS, sweep) ? beadScale(i, ARC_BEADS, front) : 0;
+ const at = arcPoint(head, tail, i / (ARC_BEADS - 1), apex);
+ DUMMY.position.set(at.x, at.y, at.z);
+ DUMMY.scale.setScalar(Math.max(0.0001, scale * beadR * 2));
+ DUMMY.updateMatrix();
+ mesh.setMatrixAt(i, DUMMY.matrix);
+ if (scale > 0) drawn += 1;
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ if (drawn === 0) mesh.visible = false;
+ // The backing: the same beads, a shade bigger and dark, so the warm core
+ // has an edge on grass, on sand, on a roof and on the sea alike.
+ const back = dark.current;
+ if (back) {
+ back.visible = mesh.visible;
+ for (let i = 0; i < ARC_BEADS; i++) {
+ const scale = beadAlive(i, ARC_BEADS, sweep) ? beadScale(i, ARC_BEADS, front) : 0;
+ const at = arcPoint(head, tail, i / (ARC_BEADS - 1), apex);
+ DUMMY.position.set(at.x, at.y, at.z);
+ DUMMY.scale.setScalar(Math.max(0.0001, scale * beadR * 2.9));
+ DUMMY.updateMatrix();
+ back.setMatrixAt(i, DUMMY.matrix);
+ }
+ back.instanceMatrix.needsUpdate = true;
+ }
+
+ // The two pings: one when the call goes out, one when it lands.
+ const ring = (node: Mesh | null, local: number, at: { x: number; y: number; z: number }) => {
+ if (!node) return;
+ const alive = local >= 0 && local <= CALL_SECONDS.dial;
+ node.visible = alive && speaking;
+ if (!alive) return;
+ node.position.set(at.x, at.y, at.z);
+ const r = Math.max(PING_R_M, beadR * 5) * (0.4 + pingScale(local));
+ node.scale.set(r, r, 0.5 + pingFade(local));
+ };
+ ring(pingA.current, age, head);
+ ring(pingB.current, age - CALL_SECONDS.dial - CALL_SECONDS.arc * 0.7, tail);
+ });
+
+ return (
+ <group>
+ {/* Solid and unlit, not additive. An additive bead is light ADDED to
+ what is behind it, and the island is a bright green field under a
+ flat, un-tonemapped pipeline — the same reason bloom is off by
+ default. Over the grass the whole arc simply vanished. */}
+ <instancedMesh
+ ref={dark}
+ args={[kit.g.sphere, kit.m.glow(SIGNAL.rim), ARC_BEADS]}
+ frustumCulled={false}
+ renderOrder={1}
+ />
+ <instancedMesh
+ ref={beads}
+ args={[kit.g.sphere, kit.m.glow(SIGNAL.bead), ARC_BEADS]}
+ frustumCulled={false}
+ renderOrder={2}
+ />
+ <mesh ref={pingA} geometry={kit.g.ring} material={kit.m.glow(SIGNAL.ping)} visible={false} />
+ <mesh ref={pingB} geometry={kit.g.ring} material={kit.m.glow(SIGNAL.ping)} visible={false} />
+ </group>
+ );
+}
+
/** The three dots over whoever is being spoken to. */
function ListeningBubble({
byId,
partnerId,
speakerId,
+ calling,
slot,
}: {
byId: Map<string, SocietyAgent>;
partnerId: string;
speakerId: string;
+ /** The caller's name when this is a call; "" for a conversation in earshot. */
+ calling: string;
slot: number;
}) {
const t = useT();
@@ -379,7 +553,9 @@ function ListeningBubble({
// bubble already names both ends, so a second one there is only noise.
const together =
speaker !== undefined && Math.hypot(speaker.x - pin.x, speaker.z - pin.z) < LISTEN_HIDE_M;
- node.visible = !together;
+ // A call is never "together" by definition, and its badge says who is on
+ // the other end — that is the whole point of drawing it.
+ node.visible = calling !== "" || !together;
node.position.set(
pin.x,
headHeight(agent) + LISTEN_LIFT_M + slot * BUBBLE_STACK_M,
@@ -391,13 +567,22 @@ function ListeningBubble({
return (
<group ref={group} visible={false}>
<Html center zIndexRange={[33, 12]} style={{ pointerEvents: "none" }}>
- <div className="sw-bubble" data-listening aria-label={t("society.world.talk_listening")}>
- <span className="sw-bubble-dots" aria-hidden>
- <i />
- <i />
- <i />
- </span>
- </div>
+ {calling ? (
+ <div className="sw-bubble" data-calling>
+ <span className="sw-bubble-kind">
+ <i className="sw-bubble-dot" style={{ background: agent.palette.accent }} />
+ {fill(t("society.world.talk_calling"), { name: calling }).replace("{0}", calling)}
+ </span>
+ </div>
+ ) : (
+ <div className="sw-bubble" data-listening aria-label={t("society.world.talk_listening")}>
+ <span className="sw-bubble-dots" aria-hidden>
+ <i />
+ <i />
+ <i />
+ </span>
+ </div>
+ )}
</Html>
</group>
);
diff --git a/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
index 4f86a120a6..aa0fc41677 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/Terrain.tsx
@@ -30,7 +30,6 @@ import {
import { ISLAND_HALF_M, LEVEL_Y, TILE_M, TileKind, buildIsland, type IslandMap } from "./islandLayout";
import { buildTerrainGeometry } from "./terrainGeometry";
-import { viewAngles } from "./viewAngles";
import { SKY, WATER } from "./worldPalette";
import { cameraOffset } from "./worldCamera";
@@ -234,7 +233,7 @@ const WATER_FRAGMENT = /* glsl */ `
uniform float time;
uniform float reachM;
uniform vec3 sunDir;
- uniform vec3 viewDir;
+ uniform vec3 viewFrom;
uniform vec3 abyss;
uniform vec3 deep;
uniform vec3 surface;
@@ -261,8 +260,18 @@ const WATER_FRAGMENT = /* glsl */ `
float ndl = max(dot(n, sunDir), 0.0);
col *= 0.72 + 0.4 * ndl;
// The glint: the sun's reflection toward the camera on the steep faces.
+ //
+ // The direction is taken PER PIXEL, from the water to the camera's stand
+ // point, even though the camera is orthographic and every pixel really
+ // shares one direction. With that one shared direction the mirror test is
+ // a switch for the entire sea at once: turn the view into the sun's
+ // reflection (pitch 50, yaw 127 with this sun) and every wave in the world
+ // lights up together. Fanning it out from a stand point turns that switch
+ // back into what it should be — a sun path lying across the water, bright
+ // where the reflection actually points at the viewer.
+ vec3 v = normalize(viewFrom - vWorld);
vec3 r = reflect(-sunDir, n);
- float spec = pow(max(dot(r, viewDir), 0.0), 90.0);
+ float spec = pow(max(dot(r, v), 0.0), 90.0);
col += glintColor * spec * 0.55;
// Caustic shimmer where the bottom is close.
@@ -332,10 +341,8 @@ const WASH_FRAGMENT = /* glsl */ `
`;
const SUN_DIR = new Vector3(SKY.sunFrom[0], SKY.sunFrom[1], SKY.sunFrom[2]).normalize();
-const VIEW_DIR = (() => {
- const [x, y, z] = cameraOffset();
- return new Vector3(x, y, z).normalize();
-})();
+/** Where the camera stands at the designed view — the first frame's glint. */
+const CAMERA_STAND = new Vector3(...cameraOffset());
export function Water({ paused }: { paused: boolean }) {
const geometry = useMemo(() => new PlaneGeometry(SEA_SIZE_M, SEA_SIZE_M, SEA_SEGMENTS, SEA_SEGMENTS), []);
@@ -353,8 +360,8 @@ export function Water({ paused }: { paused: boolean }) {
halfSize: { value: ISLAND_HALF_M },
reachM: { value: SHORE_REACH_M },
sunDir: { value: SUN_DIR },
- // Cloned: the frame loop turns this one with the orbit.
- viewDir: { value: VIEW_DIR.clone() },
+ // Where the camera stands; the frame loop keeps it on the orbit.
+ viewFrom: { value: CAMERA_STAND.clone() },
abyss: { value: new Color(WATER.abyss) },
deep: { value: new Color(WATER.deep) },
surface: { value: new Color(WATER.surface) },
@@ -396,12 +403,10 @@ export function Water({ paused }: { paused: boolean }) {
[geometry, washGeometry, material, washMaterial, shore, wash],
);
- useFrame(({ clock }) => {
- // The sun's glint is a mirror of the view direction, so it has to follow
- // the orbit even when the water itself is frozen (reduced motion).
- const { yaw, pitch } = viewAngles();
- const [vx, vy, vz] = cameraOffset(pitch, yaw);
- material.uniforms.viewDir.value.set(vx, vy, vz).normalize();
+ useFrame(({ clock, camera }) => {
+ // The glint hangs off where the camera stands, so it follows the orbit
+ // even when the water itself is frozen (reduced motion).
+ material.uniforms.viewFrom.value.copy(camera.position);
if (paused) return;
const t = clock.getElapsedTime();
material.uniforms.time.value = t;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversation.ts b/jarvis/ui/web/frontend/src/components/society/world/conversation.ts
index 3fcdf7fc7b..9cb0c6521c 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/conversation.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/conversation.ts
@@ -212,10 +212,20 @@ export function tangentFacing(placeFacing: number, side: -1 | 1): number {
export const HEAD_Y_M = 2.7;
/** How many beads make the signal. */
-export const ARC_BEADS = 16;
-/** Radius of one bead, in metres. */
+export const ARC_BEADS = 22;
+/** Radius of one bead at the closest zoom step, in metres. */
export const ARC_BEAD_R_M = 0.16;
+/**
+ * How big a bead has to be to stay visible, given how much island the frame
+ * shows. A call is the one thing on the island drawn ACROSS the map, so it is
+ * usually watched zoomed out — and at 256 m across, a 0.16 m bead is a pixel
+ * and a half. This keeps every bead about five pixels wherever the camera is.
+ */
+export function beadRadiusFor(visibleWidthM: number): number {
+ return Math.min(3.4, Math.max(0.45, visibleWidthM * 0.013));
+}
+
/**
* How high the arc rises over the straight line, in metres.
*
@@ -317,6 +327,13 @@ export const QUEUE_MAX = 3;
export const PIN_GRACE_MS = 1_500;
/** A conversation nothing has advanced in this long is closed. */
export const TALK_TIMEOUT_MS = 20_000;
+/**
+ * A call stays on screen at least this long, whatever the sentence does.
+ * A one-word answer would otherwise put a signal across the whole island and
+ * take it away again inside a second — the viewer would see a flicker and not
+ * know what it was.
+ */
+export const CALL_MIN_S = 3.2;
/** A room nobody has spoken in for this long is closed. */
export const ROOM_IDLE_MS = 45_000;
/** Radius of the ring drawn under a room at the Town Hall, in metres. */
diff --git a/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts
index 21cd727e5a..2c40ce9843 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/conversationStore.ts
@@ -126,6 +126,12 @@ interface ConvoState {
interface ConvoActions {
noteMessage: (m: IncomingMessage, known: ReadonlySet<string>) => void;
noteRoom: (r: IncomingRoom) => void;
+ /**
+ * The scene measured the distance between the two figures and decided. Taken
+ * ONCE per conversation: a wandering figure must not flip a running exchange
+ * from a quiet word into a phone call halfway through a sentence.
+ */
+ setKind: (key: string, kind: ConvoKind) => void;
/** The line on screen finished: promote the queue, or close the conversation. */
advance: (key: string) => void;
closeTalk: (key: string) => void;
@@ -277,6 +283,12 @@ export const useConversationStore = create<ConvoState & ConvoActions>((set, get)
set({ room: { ...room, settled: true, reason: r.reason, touchedMs: now } });
},
+ setKind: (key, kind) => {
+ const live = get().talks[key];
+ if (!live || live.kind !== null) return;
+ set({ talks: { ...get().talks, [key]: { ...live, kind } } });
+ },
+
advance: (key) => {
const talks = { ...get().talks };
const live = talks[key];
diff --git a/jarvis/ui/web/frontend/src/components/society/world/world.css b/jarvis/ui/web/frontend/src/components/society/world/world.css
index 4bc8bafa61..55a944acce 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/world.css
+++ b/jarvis/ui/web/frontend/src/components/society/world/world.css
@@ -192,6 +192,16 @@
border-radius: 4px;
}
+/* The far end of a call: who is on the line. Compact, because the arc itself
+ is already saying that something is happening. */
+.sw-bubble[data-calling] {
+ padding: 4px 8px 5px;
+ background: rgba(255, 252, 245, 0.9);
+}
+.sw-bubble[data-calling] .sw-bubble-kind {
+ margin-bottom: 0;
+}
+
/* The listener's end: three dots, the cheapest possible "is being spoken to". */
.sw-bubble[data-listening] {
max-width: none;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
index 4c6e12920f..231e36afe4 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/worldCamera.ts
@@ -34,13 +34,25 @@ export const CAMERA_DISTANCE_M = 640;
export const CAMERA_FAR_M = 1500;
/**
- * How far the view may be tilted. Flatter than `MIN` and the island hides
- * behind its own hills while a pointer drag pans absurdly far (the pan
- * stretches by 1 / sin(pitch)); steeper than `MAX` and the houses lose their
- * fronts and the world reads as a flat map.
+ * How far the view may be tilted: the whole quarter circle, on the
+ * maintainer's call (2026-09-03) — 0° stands on the horizon and looks along
+ * the sea, 90° is the flat map straight down. Both ends are legitimate views,
+ * not accidents, so nothing is clamped away from the viewer.
+ *
+ * Two places do have to hold at the ends, and they do it here rather than
+ * pretending the range is smaller:
+ * - the vertical pan stretches by 1 / sin(pitch), which diverges at 0°, so
+ * `PITCH_SIN_FLOOR` caps that stretch (`groundStretch`);
+ * - `lookAt` has no defined roll when the camera is exactly overhead, so the
+ * rig keeps a hair of tilt (`LOOK_LIMIT_DEG`); at 1/20 of a degree it is
+ * the same picture, and the camera does not snap to a random heading.
*/
-export const MIN_PITCH_DEG = 20;
-export const MAX_PITCH_DEG = 80;
+export const MIN_PITCH_DEG = 0;
+export const MAX_PITCH_DEG = 90;
+/** sin(4°): the flattest view still pans at a usable speed instead of diverging. */
+export const PITCH_SIN_FLOOR = 0.0698;
+/** The steepest tilt the camera itself is built at, so `lookAt` stays defined. */
+export const LOOK_LIMIT_DEG = 89.95;
/** Yaw the compass and the keyboard step in — a quarter turn per press. */
export const YAW_STEP_DEG = 45;
@@ -89,6 +101,15 @@ export function cameraOffset(
];
}
+/**
+ * How much further one screen metre reaches across the ground than across the
+ * screen, at this tilt: 1 at straight down, growing as the view flattens.
+ * Capped at `PITCH_SIN_FLOOR` so the horizon view still pans and frames.
+ */
+export function groundStretch(pitchDeg = CAMERA_PITCH_DEG): number {
+ return 1 / Math.max(PITCH_SIN_FLOOR, Math.sin(pitchDeg * DEG));
+}
+
/** Half extents of the orthographic frustum for a visible ground width. */
export function orthoHalfExtents(widthM: number, aspect: number): { halfW: number; halfH: number } {
const halfW = widthM / 2;
diff --git a/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts b/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts
index 56870a0b19..d24fe89b42 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts
+++ b/jarvis/ui/web/frontend/src/components/society/world/worldPalette.ts
@@ -159,6 +159,23 @@ export const CEREMONY = {
stain: "#4a1418",
};
+/**
+ * The signal arcing between two agents who are too far apart to talk.
+ *
+ * Deliberately NOT the sender's accent: half the roster's accents are greens
+ * and blues, and the island is a green field beside a blue sea, so a call in
+ * an agent's own colour is invisible exactly when it matters. Identity is
+ * carried by the bubbles at both ends; the arc only has to READ.
+ */
+export const SIGNAL = {
+ /** The beads: warm and near-white, the one hue nothing on the island wears. */
+ bead: "#fff1b8",
+ /** The ping at each end, a shade deeper so the two do not merge. */
+ ping: "#ffb703",
+ /** A dark backing behind each bead, so the warm core has an edge anywhere. */
+ rim: "#2a2118",
+};
+
/** In-world labels (drawn as DOM over the canvas, in the world's own type). */
export const LABEL = {
font: '"Pixelify Sans", "Inter Variable", "Inter", ui-sans-serif, sans-serif',
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 10d6b6c426..bc4cf54a44 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -602,6 +602,11 @@
"background_hint": "Die App zeichnet standardmäßig auf einer einfarbigen Fläche. Wähle unten ein Bild, um es als Hintergrund zu nutzen; „Einfarbig“ bringt die schlichte Fläche zurück."
},
"agent_chat": {
+ "internal_message": "Interne Nachricht",
+ "delivery_queued": "Eingereiht",
+ "delivery_delivered": "Zugestellt",
+ "delivery_failed": "Fehlgeschlagen",
+
"placeholder": "Frag mich alles …",
"empty_subtitle": "{name} mit Tastatur — derselbe Assistent, den das Mikrofon erreicht. Das gewählte Modell ist das, worauf {name} in diesem Chat läuft.",
"empty_subtitle_agent": "Ein Coding-Agent arbeitet an den Dateien in diesem Ordner — nicht an deinem Gedächtnis, deinem Wiki oder deinem Kalender. Modell wählen. Dann fragen.",
@@ -5321,6 +5326,40 @@
"no_tools": "Noch keine Werkzeuge freigegeben.",
"routines": "Routinen",
"no_routines": "Noch keine Routinen.",
+ "screen_of": "Bildschirm von {0}",
+ "browser_not_setup": "Der Browser ist auf diesem Rechner noch nicht eingerichtet.",
+ "browser_idle": "Bereit",
+ "browser_connecting": "Wird verbunden",
+ "browser_setup": "Einrichten",
+ "browser_setting_up": "Wird eingerichtet…",
+ "browser_sign_in": "Anmelden",
+ "browser_sign_in_hint": "Öffnet ein Chrome-Fenster auf diesem Rechner.",
+ "browser_error": "Der Browser ist nicht erreichbar.",
+ "routines_add": "Routine hinzufügen",
+ "routines_title": "Titel",
+ "routines_prompt": "Was zu tun ist",
+ "routines_kind": "Wann",
+ "routines_every": "Alle paar Stunden",
+ "routines_daily": "Jeden Tag zu einer Uhrzeit",
+ "routines_on_event": "Wenn etwas passiert",
+ "routines_hours": "Stunden",
+ "routines_minutes": "Minuten",
+ "routines_event_name": "Ereignisname",
+ "routines_save": "Hinzufügen",
+ "routines_unit": "Einheit",
+ "sched_every_day": "Jeden Tag",
+ "sched_every_day_at": "Jeden Tag um {0}",
+ "sched_every_days": "Alle {0} Tage",
+ "sched_every_hour": "Jede Stunde",
+ "sched_every_hours": "Alle {0} Stunden",
+ "sched_every_minute": "Jede Minute",
+ "sched_every_minutes": "Alle {0} Minuten",
+ "sched_every_seconds": "Alle {0} Sekunden",
+ "sched_once_in": "Einmal, in {0}",
+ "sched_on": "Bei {0}",
+ "sched_at": "Um {0}",
+ "sched_at_fixed": "Zu einer festen Zeit",
+ "options_more": "Weitere Aktionen",
"runs": "Läufe",
"cost": "Ausgegeben",
"last_active": "Zuletzt aktiv",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6966391fad..402a7e52b6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -602,6 +602,11 @@
"background_hint": "The app paints on a plain colour by default. Pick a picture below to use it as your wallpaper; “Solid colour” brings the plain ground back."
},
"agent_chat": {
+ "internal_message": "Internal message",
+ "delivery_queued": "Queued",
+ "delivery_delivered": "Delivered",
+ "delivery_failed": "Failed",
+
"placeholder": "Ask anything…",
"empty_subtitle": "{name} with a keyboard — the same assistant the microphone reaches. The model you pick is what {name} runs on for this chat.",
"empty_subtitle_agent": "A coding agent works on the files in this folder — not on your memory, your wiki or your calendar. Pick a model. Then ask.",
@@ -5354,6 +5359,40 @@
"no_tools": "No tools granted yet.",
"routines": "Routines",
"no_routines": "No routines yet.",
+ "screen_of": "Screen of {0}",
+ "browser_not_setup": "Browser not set up on this machine.",
+ "browser_idle": "Idle",
+ "browser_connecting": "Connecting",
+ "browser_setup": "Set up",
+ "browser_setting_up": "Setting up…",
+ "browser_sign_in": "Sign in",
+ "browser_sign_in_hint": "Opens a Chrome window on this computer.",
+ "browser_error": "Could not reach the browser.",
+ "routines_add": "Add a routine",
+ "routines_title": "Title",
+ "routines_prompt": "What to do",
+ "routines_kind": "When",
+ "routines_every": "Every few hours",
+ "routines_daily": "Every day at a time",
+ "routines_on_event": "When something happens",
+ "routines_hours": "Hours",
+ "routines_minutes": "Minutes",
+ "routines_event_name": "Event name",
+ "routines_save": "Add",
+ "routines_unit": "Unit",
+ "sched_every_day": "Every day",
+ "sched_every_day_at": "Every day at {0}",
+ "sched_every_days": "Every {0} days",
+ "sched_every_hour": "Every hour",
+ "sched_every_hours": "Every {0} hours",
+ "sched_every_minute": "Every minute",
+ "sched_every_minutes": "Every {0} minutes",
+ "sched_every_seconds": "Every {0} seconds",
+ "sched_once_in": "Once, in {0}",
+ "sched_on": "On {0}",
+ "sched_at": "At {0}",
+ "sched_at_fixed": "At a fixed time",
+ "options_more": "More actions",
"runs": "Runs",
"cost": "Spent",
"last_active": "Last active",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index a1b4d375d8..be9a44ce84 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -602,6 +602,11 @@
"background_hint": "La app se dibuja sobre un color liso por defecto. Elige una imagen abajo para usarla de fondo; «Color sólido» devuelve la superficie lisa."
},
"agent_chat": {
+ "internal_message": "Mensaje interno",
+ "delivery_queued": "En cola",
+ "delivery_delivered": "Entregado",
+ "delivery_failed": "Error",
+
"placeholder": "Pregunta lo que quieras…",
"empty_subtitle": "{name} con teclado: el mismo asistente que atiende el micrófono. El modelo que elijas es sobre lo que corre {name} en este chat.",
"empty_subtitle_agent": "Un agente de código trabaja en los archivos de esta carpeta, no en tu memoria, tu wiki ni tu calendario. Elige un modelo. Luego pregunta.",
@@ -5321,6 +5326,40 @@
"no_tools": "Aún no hay herramientas concedidas.",
"routines": "Rutinas",
"no_routines": "Aún no hay rutinas.",
+ "screen_of": "Pantalla de {0}",
+ "browser_not_setup": "El navegador no está configurado en este equipo.",
+ "browser_idle": "En espera",
+ "browser_connecting": "Conectando",
+ "browser_setup": "Configurar",
+ "browser_setting_up": "Configurando…",
+ "browser_sign_in": "Iniciar sesión",
+ "browser_sign_in_hint": "Abre una ventana de Chrome en este equipo.",
+ "browser_error": "No se pudo alcanzar el navegador.",
+ "routines_add": "Añadir una rutina",
+ "routines_title": "Título",
+ "routines_prompt": "Qué hacer",
+ "routines_kind": "Cuándo",
+ "routines_every": "Cada pocas horas",
+ "routines_daily": "Cada día a una hora",
+ "routines_on_event": "Cuando ocurre algo",
+ "routines_hours": "Horas",
+ "routines_minutes": "Minutos",
+ "routines_event_name": "Nombre del evento",
+ "routines_save": "Añadir",
+ "routines_unit": "Unidad",
+ "sched_every_day": "Cada día",
+ "sched_every_day_at": "Cada día a las {0}",
+ "sched_every_days": "Cada {0} días",
+ "sched_every_hour": "Cada hora",
+ "sched_every_hours": "Cada {0} horas",
+ "sched_every_minute": "Cada minuto",
+ "sched_every_minutes": "Cada {0} minutos",
+ "sched_every_seconds": "Cada {0} segundos",
+ "sched_once_in": "Una vez, en {0}",
+ "sched_on": "En {0}",
+ "sched_at": "A las {0}",
+ "sched_at_fixed": "A una hora fija",
+ "options_more": "Más acciones",
"runs": "Ejecuciones",
"cost": "Gastado",
"last_active": "Última actividad",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 746298db1f..63c7c92077 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -1,5 +1,72 @@
{
"society": {
+ "studio": {
+ "add_routine": "Routine hinzufügen",
+ "routine_title": "Name der Routine",
+ "routine_task": "Was soll dieser Agent tun?",
+ "routine_hours": "Wiederholen alle (Stunden)",
+ "routine_error": "Die Routine konnte nicht erstellt werden.",
+ "eyebrow": "Agenten-Studio",
+ "heading": "Mach diesen Agenten zu deinem.",
+ "subtitle": "Gestalte, wie er denkt, arbeitet und aussieht.",
+ "sections": "Agenten-Einstellungen",
+ "profile": "Profil",
+ "model": "Modell",
+ "appearance": "Aussehen",
+ "limits": "Grenzen",
+ "activity": "Aktivität",
+ "profile_heading": "Eine klare Rolle. Deine Anweisungen.",
+ "model_heading": "Wähle, wie er denkt.",
+ "appearance_heading": "Gib ihm einen Charakter.",
+ "limits_heading": "Lege seine Grenzen fest.",
+ "activity_heading": "Arbeit, Routinen und Aktionen.",
+ "role": "Rolle",
+ "role_placeholder": "Wofür ist dieser Agent zuständig?",
+ "instructions_placeholder": "Beschreibe seine Aufgabe, Prioritäten und wie er mit dir arbeiten soll.",
+ "instructions_hint": "Diese Anweisungen gelten für künftige Aufgaben. Bestehende Werkzeugpräferenzen und Freigaberegeln bleiben erhalten.",
+ "tools_hint": "Der Werkzeugzugriff richtet sich nach verbundenen Werkzeugen und den Berechtigungen des Agenten. Ändere seinen Fokus oder fordere neue Fähigkeiten im Chat an.",
+ "chat_action": "Agenten-Chat öffnen",
+ "preview_hint": "Änderungen erscheinen sofort an der Figur. Speichere, wenn dir das Ergebnis gefällt.",
+ "character": "Figur",
+ "imported": "Deine importierte Figur",
+ "palette": "Farbpalette",
+ "shuffle": "Überrasch mich",
+ "wardrobe": "Kleidung & Zubehör",
+ "none": "Keine",
+ "reset_look": "Farben und Zubehör zurücksetzen",
+ "provider": "Anbieter",
+ "account": "Konto",
+ "active_account": "Aktives Konto",
+ "saved_account": "Gespeichertes Konto",
+ "model_hint": "Wähle einen verbundenen Anbieter, ein Modell und die Denktiefe. Modelländerungen werden separat gespeichert; der Gesprächsverlauf bleibt erhalten.",
+ "connect_hint": "Verbinde diesen Anbieter unter Agenten oder API-Schlüssel, um hier sein Modell zu ändern.",
+ "save_model": "Modell übernehmen",
+ "budget": "Tagesbudget (USD)",
+ "budget_hint": "0 bedeutet unbegrenzt. Das Budget wird um Mitternacht UTC zurückgesetzt.",
+ "concurrency": "Parallele Aufgaben",
+ "concurrency_hint": "Maximale Anzahl gleichzeitig laufender Aufgaben.",
+ "ceiling_safe": "Nur Werkzeuge der Stufe Sicher zulassen.",
+ "ceiling_monitor": "Werkzeuge der Stufen Sicher und Überwachen zulassen.",
+ "ceiling_ask": "Auch Werkzeuge zulassen, die eine Freigabe benötigen.",
+ "invalid_limits": "Gib ein Budget ab 0 und eine ganze Anzahl von mindestens 1 Aufgabe ein.",
+ "spent_today": "Heute ausgegeben: ${amount}",
+ "total_spent": "Gesamtausgaben",
+ "notes": "Wiki-Notizen",
+ "manage": "Agent verwalten",
+ "recent": "Letzte Aktivitäten",
+ "loading": "Aktivitäten werden geladen…",
+ "no_activity": "Noch keine Aktivität. Gib diesem Agenten im Chat seine erste Aufgabe.",
+ "saved": "Änderungen gespeichert",
+ "unsaved": "Ungespeicherte Änderungen",
+ "ready": "Bereit zum Bearbeiten",
+ "save": "Änderungen speichern",
+ "discard": "Verwerfen",
+ "sample": "Nur Vorschau: Beispielagenten können nicht auf dem Server gespeichert werden.",
+ "load_error": "Diese Einstellungen konnten nicht geladen werden.",
+ "retry": "Erneut versuchen",
+ "leave": "Ungespeicherte Änderungen am Agenten verwerfen?",
+ "saving_wait": "Bitte warte, bis das Speichern abgeschlossen ist."
+ },
"world": {
"talk_kind_query": "fragt",
"talk_kind_answer": "antwortet",
@@ -23,7 +90,7 @@
"hud_active": "{count} aktiv",
"sample_badge": "Beispiel-Roster",
"reduced_motion_note": "Reduzierte Bewegung: die Insel steht still",
- "controls_hint": "Ziehen zum Schwenken · Scrollen zum Zoomen · Pfeiltasten zum Bewegen · Gebäude anklicken zum Drehen",
+ "controls_hint": "Ziehen zum Schwenken · Rechte Maustaste zum Drehen · Scrollen zum Zoomen · Pfeiltasten zum Bewegen · Gebäude anklicken zum Drehen",
"rotate_hint": "Den Knopf um das Gebäude ziehen, um es zu drehen. Mit Shift rastet es in 15°-Schritten ein.",
"rotate_reset": "Zurück zur Standard-Ausrichtung",
"rotate_reset_short": "Zurücksetzen",
@@ -32,6 +99,10 @@
"zoom_label": "Zoom",
"zoom_in": "Hineinzoomen",
"zoom_out": "Herauszoomen",
+ "compass_label": "Blickrichtung",
+ "turn_left": "Ansicht nach links drehen (Q)",
+ "turn_right": "Ansicht nach rechts drehen (E)",
+ "view_reset": "Zurück zur Standardansicht (R)",
"minimap_label": "Inselkarte – klicken, um dorthin zu springen",
"webgl_missing_title": "Die Insel braucht WebGL",
"webgl_missing_body": "Dieses Fenster kann gerade kein 3D zeichnen. Das Ledger zeigt dieselben Agenten.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index f5695a2ff7..d84cbc4336 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -1,5 +1,72 @@
{
"society": {
+ "studio": {
+ "add_routine": "Add routine",
+ "routine_title": "Routine name",
+ "routine_task": "What should this agent do?",
+ "routine_hours": "Repeat every (hours)",
+ "routine_error": "Could not create the routine.",
+ "eyebrow": "Agent studio",
+ "heading": "Make this agent yours.",
+ "subtitle": "Shape how it thinks, works and looks.",
+ "sections": "Agent settings",
+ "profile": "Profile",
+ "model": "Model",
+ "appearance": "Appearance",
+ "limits": "Limits",
+ "activity": "Activity",
+ "profile_heading": "A clear role. Your instructions.",
+ "model_heading": "Choose how it thinks.",
+ "appearance_heading": "Give it a character.",
+ "limits_heading": "Set its boundaries.",
+ "activity_heading": "Work, routines and actions.",
+ "role": "Role",
+ "role_placeholder": "What is this agent responsible for?",
+ "instructions_placeholder": "Describe its job, priorities and how it should work with you.",
+ "instructions_hint": "These instructions guide future tasks. Existing tool preferences and approval rules are preserved.",
+ "tools_hint": "Tool access follows your connected tools and this agent’s permissions. Use its chat to change its focus or request new capabilities.",
+ "chat_action": "Open agent chat",
+ "preview_hint": "Changes appear on the figure immediately. Save when you like the result.",
+ "character": "Character",
+ "imported": "Your imported character",
+ "palette": "Color palette",
+ "shuffle": "Surprise me",
+ "wardrobe": "Clothing & accessories",
+ "none": "None",
+ "reset_look": "Reset colors and accessories",
+ "provider": "Provider",
+ "account": "Account",
+ "active_account": "Active account",
+ "saved_account": "Saved account",
+ "model_hint": "Choose a connected provider, model and thinking effort. Model changes are saved separately and keep the conversation.",
+ "connect_hint": "Connect this provider in Agents or API Keys to change its model here.",
+ "save_model": "Apply model",
+ "budget": "Daily budget (USD)",
+ "budget_hint": "0 means unlimited. The budget resets at midnight UTC.",
+ "concurrency": "Parallel jobs",
+ "concurrency_hint": "Maximum tasks running at the same time.",
+ "ceiling_safe": "Allow only tools rated Safe.",
+ "ceiling_monitor": "Allow Safe and Monitor tools.",
+ "ceiling_ask": "Also allow tools that require approval.",
+ "invalid_limits": "Enter a budget of 0 or more and a whole number of jobs of at least 1.",
+ "spent_today": "Spent today: ${amount}",
+ "total_spent": "Total spent",
+ "notes": "Wiki notes",
+ "manage": "Manage agent",
+ "recent": "Recent activity",
+ "loading": "Loading activity…",
+ "no_activity": "No activity yet. Start a conversation to give this agent its first task.",
+ "saved": "Changes saved",
+ "unsaved": "Unsaved changes",
+ "ready": "Ready to edit",
+ "save": "Save changes",
+ "discard": "Discard",
+ "sample": "Preview only: sample agents cannot be saved to the server.",
+ "load_error": "Could not load these settings.",
+ "retry": "Try again",
+ "leave": "Discard unsaved agent changes?",
+ "saving_wait": "Please wait until saving has finished."
+ },
"world": {
"talk_kind_query": "asks",
"talk_kind_answer": "answers",
@@ -23,7 +90,7 @@
"hud_active": "{count} active",
"sample_badge": "Sample roster",
"reduced_motion_note": "Reduced motion: the island holds still",
- "controls_hint": "Drag to pan · Scroll to zoom · Arrow keys to move · Click a building to turn it",
+ "controls_hint": "Drag to pan · Right-drag to turn the view · Scroll to zoom · Arrow keys to move · Click a building to turn it",
"rotate_hint": "Drag the knob around the building to turn it. Shift snaps to 15° steps.",
"rotate_reset": "Back to the designed heading",
"rotate_reset_short": "Reset",
@@ -32,6 +99,10 @@
"zoom_label": "Zoom",
"zoom_in": "Zoom in",
"zoom_out": "Zoom out",
+ "compass_label": "View direction",
+ "turn_left": "Turn the view left (Q)",
+ "turn_right": "Turn the view right (E)",
+ "view_reset": "Back to the designed view (R)",
"minimap_label": "Island map — click to jump there",
"webgl_missing_title": "The island needs WebGL",
"webgl_missing_body": "This window cannot draw 3D right now. The ledger lists the same agents.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index 55d5bcb73d..5a1d4c885e 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -1,5 +1,72 @@
{
"society": {
+ "studio": {
+ "add_routine": "Añadir rutina",
+ "routine_title": "Nombre de la rutina",
+ "routine_task": "¿Qué debe hacer este agente?",
+ "routine_hours": "Repetir cada (horas)",
+ "routine_error": "No se pudo crear la rutina.",
+ "eyebrow": "Estudio de agentes",
+ "heading": "Haz tuyo este agente.",
+ "subtitle": "Define cómo piensa, trabaja y se ve.",
+ "sections": "Ajustes del agente",
+ "profile": "Perfil",
+ "model": "Modelo",
+ "appearance": "Aspecto",
+ "limits": "Límites",
+ "activity": "Actividad",
+ "profile_heading": "Un rol claro. Tus instrucciones.",
+ "model_heading": "Elige cómo piensa.",
+ "appearance_heading": "Dale un personaje.",
+ "limits_heading": "Define sus límites.",
+ "activity_heading": "Trabajo, rutinas y acciones.",
+ "role": "Rol",
+ "role_placeholder": "¿De qué se encarga este agente?",
+ "instructions_placeholder": "Describe su trabajo, prioridades y cómo debe colaborar contigo.",
+ "instructions_hint": "Estas instrucciones guían las próximas tareas. Se conservan las preferencias de herramientas y las reglas de aprobación.",
+ "tools_hint": "El acceso depende de las herramientas conectadas y los permisos del agente. Usa su chat para cambiar su enfoque o solicitar nuevas capacidades.",
+ "chat_action": "Abrir chat del agente",
+ "preview_hint": "Los cambios aparecen al instante en el personaje. Guarda cuando te guste el resultado.",
+ "character": "Personaje",
+ "imported": "Tu personaje importado",
+ "palette": "Paleta de colores",
+ "shuffle": "Sorpréndeme",
+ "wardrobe": "Ropa y accesorios",
+ "none": "Ninguno",
+ "reset_look": "Restablecer colores y accesorios",
+ "provider": "Proveedor",
+ "account": "Cuenta",
+ "active_account": "Cuenta activa",
+ "saved_account": "Cuenta guardada",
+ "model_hint": "Elige un proveedor conectado, un modelo y el esfuerzo de razonamiento. Los cambios de modelo se guardan por separado y conservan la conversación.",
+ "connect_hint": "Conecta este proveedor en Agentes o Claves API para cambiar su modelo aquí.",
+ "save_model": "Aplicar modelo",
+ "budget": "Presupuesto diario (USD)",
+ "budget_hint": "0 significa sin límite. Se restablece a medianoche UTC.",
+ "concurrency": "Tareas paralelas",
+ "concurrency_hint": "Máximo de tareas que se ejecutan a la vez.",
+ "ceiling_safe": "Permitir solo herramientas de nivel Seguro.",
+ "ceiling_monitor": "Permitir herramientas de nivel Seguro y Supervisar.",
+ "ceiling_ask": "Permitir también herramientas que requieren aprobación.",
+ "invalid_limits": "Introduce un presupuesto de 0 o más y un número entero de tareas de al menos 1.",
+ "spent_today": "Gastado hoy: ${amount}",
+ "total_spent": "Gasto total",
+ "notes": "Notas wiki",
+ "manage": "Gestionar agente",
+ "recent": "Actividad reciente",
+ "loading": "Cargando actividad…",
+ "no_activity": "Aún no hay actividad. Dale su primera tarea en el chat.",
+ "saved": "Cambios guardados",
+ "unsaved": "Cambios sin guardar",
+ "ready": "Listo para editar",
+ "save": "Guardar cambios",
+ "discard": "Descartar",
+ "sample": "Solo vista previa: los agentes de ejemplo no se guardan en el servidor.",
+ "load_error": "No se pudieron cargar estos ajustes.",
+ "retry": "Reintentar",
+ "leave": "¿Descartar los cambios del agente sin guardar?",
+ "saving_wait": "Espera hasta que termine de guardar."
+ },
"world": {
"talk_kind_query": "pregunta",
"talk_kind_answer": "responde",
@@ -23,7 +90,7 @@
"hud_active": "{count} activos",
"sample_badge": "Plantilla de ejemplo",
"reduced_motion_note": "Movimiento reducido: la isla se queda quieta",
- "controls_hint": "Arrastra para desplazar · Rueda para zoom · Flechas para moverte · Clic en un edificio para girarlo",
+ "controls_hint": "Arrastra para desplazar · Botón derecho para girar la vista · Rueda para zoom · Flechas para moverte · Clic en un edificio para girarlo",
"rotate_hint": "Arrastra el mando alrededor del edificio para girarlo. Con Mayús se ajusta en pasos de 15°.",
"rotate_reset": "Volver a la orientación de diseño",
"rotate_reset_short": "Restablecer",
@@ -32,6 +99,10 @@
"zoom_label": "Zoom",
"zoom_in": "Acercar",
"zoom_out": "Alejar",
+ "compass_label": "Dirección de la vista",
+ "turn_left": "Girar la vista a la izquierda (Q)",
+ "turn_right": "Girar la vista a la derecha (E)",
+ "view_reset": "Volver a la vista original (R)",
"minimap_label": "Mapa de la isla: haz clic para saltar allí",
"webgl_missing_title": "La isla necesita WebGL",
"webgl_missing_body": "Esta ventana no puede dibujar 3D ahora mismo. El registro muestra los mismos agentes.",
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index c40cc42921..c8ec7d60c9 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -102,6 +102,20 @@ export interface AgentChatSession {
pending_approvals?: string[];
}
+export const INTERNAL_DELIVERY_STATUSES = ["queued", "delivered", "failed"] as const;
+export interface InternalMessage {
+ message_id: string;
+ sender_id: string;
+ sender_name: string;
+ sender_kind: "jarvis" | "agent" | "user";
+ text: string;
+ prompt: string;
+ trace_id: string;
+ status: (typeof INTERNAL_DELIVERY_STATUSES)[number];
+ turn_id: string;
+ error: string;
+}
+
export interface AgentChatEvent {
seq: number;
ts_ms: number;
@@ -339,7 +353,11 @@ export async function sendAgentChatMessage(
await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ text, attachments, ...(toolChoices.length ? { tool_choices: toolChoices } : {}) }),
+ body: JSON.stringify({
+ text,
+ attachments,
+ ...(toolChoices.length ? { tool_choices: toolChoices } : {}),
+ }),
}),
"send-failed",
);
diff --git a/jarvis/ui/web/frontend/src/lib/deckRoom.test.ts b/jarvis/ui/web/frontend/src/lib/deckRoom.test.ts
new file mode 100644
index 0000000000..e15af4e15d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/deckRoom.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import {
+ CAMERA,
+ FLOOR_Y,
+ MASCOT,
+ PANEL_SCALE,
+ ROOM_PANELS,
+ cameraTarget,
+ coverFit,
+ followAlpha,
+ panelBottom,
+ wallSize,
+} from "@/lib/deckRoom";
+
+describe("deckRoom", () => {
+ it("keeps every panel on or above the floor", () => {
+ for (const p of ROOM_PANELS) {
+ expect(panelBottom(p), p.id).toBeGreaterThanOrEqual(FLOOR_Y - 0.05);
+ }
+ });
+
+ it("puts what is acted on in front and what is looked at on the wall", () => {
+ const byId = Object.fromEntries(ROOM_PANELS.map((p) => [p.id, p]));
+ for (const near of ["log", "activity", "terminals"] as const) {
+ expect(byId[near].standing).toBe(true);
+ expect(byId[near].position[2]).toBeGreaterThan(1.5);
+ }
+ for (const wall of ["response", "wiki", "capture"] as const) {
+ expect(byId[wall].standing).toBe(false);
+ expect(byId[wall].position[2]).toBeLessThan(1);
+ }
+ });
+
+ it("turns left panels toward the viewer's right and right panels the other way", () => {
+ const byId = Object.fromEntries(ROOM_PANELS.map((p) => [p.id, p]));
+ expect(byId.log.rotationY).toBeGreaterThan(0);
+ expect(byId.activity.rotationY).toBeGreaterThan(0);
+ expect(byId.terminals.rotationY).toBeLessThan(0);
+ expect(byId.wiki.rotationY).toBeLessThan(0);
+ });
+
+ it("keeps the mascot on the floor in front of the wall, and the camera in front of everything", () => {
+ expect(MASCOT.position[1]).toBe(FLOOR_Y);
+ expect(MASCOT.position[2]).toBeGreaterThan(0);
+ for (const p of ROOM_PANELS) expect(p.position[2]).toBeLessThan(CAMERA.position[2]);
+ expect(MASCOT.position[2]).toBeLessThan(CAMERA.position[2]);
+ });
+
+ it("sizes the wall to fill the view at the wall's plane, with overscan", () => {
+ const { width, height } = wallSize(16 / 9);
+ const visible = 2 * CAMERA.position[2] * Math.tan((CAMERA.fov * Math.PI) / 360);
+ expect(height).toBeGreaterThan(visible);
+ expect(width / height).toBeCloseTo(16 / 9, 2);
+ });
+
+ it("cover-fits a texture like background-size: cover", () => {
+ // a wide picture on a squarer plane: crop the sides, centred
+ const wide = coverFit(16 / 9, 1);
+ expect(wide.repeat[1]).toBe(1);
+ expect(wide.repeat[0]).toBeCloseTo(9 / 16, 3);
+ expect(wide.offset[0]).toBeCloseTo((1 - 9 / 16) / 2, 3);
+ // a tall picture on a wide plane: crop top and bottom
+ const tall = coverFit(1, 2);
+ expect(tall.repeat[0]).toBe(1);
+ expect(tall.repeat[1]).toBeCloseTo(0.5, 3);
+ expect(tall.offset[1]).toBeCloseTo(0.25, 3);
+ // same aspect: nothing cropped
+ expect(coverFit(1.5, 1.5)).toEqual({ repeat: [1, 1], offset: [0, 0] });
+ });
+
+ it("sways the camera with the pointer, clamped, and never changes its distance", () => {
+ const rest = cameraTarget(0, 0);
+ expect(rest).toEqual([CAMERA.position[0], CAMERA.position[1], CAMERA.position[2]]);
+ const right = cameraTarget(1, 0);
+ expect(right[0]).toBeCloseTo(CAMERA.position[0] + CAMERA.swayX, 3);
+ expect(cameraTarget(5, 5)).toEqual(cameraTarget(1, 1));
+ expect(cameraTarget(-1, -1)[2]).toBe(CAMERA.position[2]);
+ });
+
+ it("follows with an exponential factor between 0 and 1 that grows with dt", () => {
+ expect(followAlpha(0)).toBe(0);
+ expect(followAlpha(1 / 60)).toBeGreaterThan(0);
+ expect(followAlpha(1 / 60)).toBeLessThan(followAlpha(1 / 30));
+ expect(followAlpha(10)).toBeLessThanOrEqual(1);
+ });
+
+ it("renders panels at a readable DOM size", () => {
+ for (const p of ROOM_PANELS) {
+ expect(p.width * PANEL_SCALE).toBeGreaterThan(0.5);
+ expect(p.width).toBeLessThanOrEqual(800);
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/deckRoom.ts b/jarvis/ui/web/frontend/src/lib/deckRoom.ts
new file mode 100644
index 0000000000..15d0520b6e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/deckRoom.ts
@@ -0,0 +1,132 @@
+/**
+ * The mission deck as a ROOM — the numbers behind `components/deck/room/`.
+ *
+ * The room is a display case in real 3D (three.js): the wallpaper is the
+ * back wall, a reflecting floor runs from it toward the viewer, the mascot
+ * stands on that floor, and the instruments stand around it as upright
+ * glass panels — near the viewer what the person acts on (log, outputs,
+ * terminals), on the wall what is looked at (response, memory map,
+ * capture). The camera has a fixed standpoint and sways a little with the
+ * pointer; it never walks.
+ *
+ * Everything here is pure so `deckRoom.test.ts` can pin it: world units
+ * (1 unit ≈ 1 m in a room about 16 m wide), panel placement in those units,
+ * the DOM size each panel renders at, the camera's rest pose and sway, and
+ * the wall's cover-fit. The components only read these.
+ */
+
+/** The camera's rest pose: standing in front of the case, a little above the floor's middle. */
+export const CAMERA = {
+ fov: 40,
+ position: [0, 1.2, 14] as const,
+ lookAt: [0, 0.3, 0] as const,
+ /** How far (world units) the pointer moves the camera, edge to edge. */
+ swayX: 0.7,
+ swayY: 0.35,
+ /** How fast the camera follows the pointer (per second, for a lerp). */
+ follow: 4,
+};
+
+/** The floor's height: the bottom edge of the wall, where everything stands. */
+export const FLOOR_Y = -2.6;
+
+/** The mascot's height in world units and where it stands. */
+export const MASCOT = { height: 3.1, position: [0, FLOOR_Y, 3.4] as const };
+
+/** One CSS3D pixel is this many world units: a 420 px panel is 4.2 units wide. */
+export const PANEL_SCALE = 0.01;
+
+export type RoomPanelId = "response" | "log" | "activity" | "wiki" | "terminals" | "capture" | "headline";
+
+export interface RoomPanel {
+ id: RoomPanelId;
+ /** Centre of the panel in world units. */
+ position: [number, number, number];
+ /** Turn about the vertical axis, in radians (left panels +, right −). */
+ rotationY: number;
+ /** The DOM box the panel renders into, in px (world size = px × PANEL_SCALE). */
+ width: number;
+ height: number;
+ /** Panels on the wall are lit from the front; standing panels cast a shadow. */
+ standing: boolean;
+}
+
+/**
+ * Where the instruments stand. The near panels frame the mascot on both
+ * sides like stands in an exhibition, turned toward the viewer; the wall
+ * panels sit just in front of the picture. Heights keep every panel's
+ * bottom edge on or above the floor.
+ */
+export const ROOM_PANELS: readonly RoomPanel[] = [
+ // on the wall
+ { id: "response", position: [0, 2.5, 0.35], rotationY: 0, width: 760, height: 250, standing: false },
+ { id: "wiki", position: [6.1, 1.45, 0.55], rotationY: -0.28, width: 520, height: 440, standing: false },
+ { id: "capture", position: [0, -1.25, 0.35], rotationY: 0, width: 460, height: 220, standing: false },
+ // standing, near
+ { id: "log", position: [-6.5, 0.75, 2.2], rotationY: 0.5, width: 430, height: 400, standing: true },
+ { id: "activity", position: [-5.7, -1.5, 4.0], rotationY: 0.4, width: 470, height: 215, standing: true },
+ { id: "terminals", position: [6.2, -1.45, 3.6], rotationY: -0.46, width: 490, height: 225, standing: true },
+ // the headline at the mascot's feet
+ { id: "headline", position: [0, -2.3, 4.9], rotationY: 0, width: 560, height: 70, standing: true },
+];
+
+/** The world height of a panel's bottom edge — every panel must stand on or above the floor. */
+export function panelBottom(p: RoomPanel): number {
+ return p.position[1] - (p.height * PANEL_SCALE) / 2;
+}
+
+/**
+ * The back wall's size so it fills the camera's view at the wall's plane:
+ * the visible height at distance `d` for a vertical field of view `fov`,
+ * and that height times the viewport's aspect, with a little overscan so
+ * the sway never shows the wall's edge.
+ */
+export function wallSize(aspect: number, overscan = 1.12): { width: number; height: number } {
+ const d = CAMERA.position[2];
+ const height = 2 * d * Math.tan((CAMERA.fov * Math.PI) / 360) * overscan;
+ return { width: round(height * aspect, 3), height: round(height, 3) };
+}
+
+/**
+ * `background-size: cover` for a texture on a plane: the repeat and offset
+ * that show the picture uncropped on the longer axis and crop it centred on
+ * the other, whatever the two aspect ratios are.
+ */
+export function coverFit(
+ imageAspect: number,
+ planeAspect: number,
+): { repeat: [number, number]; offset: [number, number] } {
+ if (imageAspect <= 0 || planeAspect <= 0) return { repeat: [1, 1], offset: [0, 0] };
+ if (imageAspect > planeAspect) {
+ // picture wider than the plane: crop the sides
+ const rx = planeAspect / imageAspect;
+ return { repeat: [round(rx, 4), 1], offset: [round((1 - rx) / 2, 4), 0] };
+ }
+ // picture taller than the plane: crop top and bottom
+ const ry = imageAspect / planeAspect;
+ return { repeat: [1, round(ry, 4)], offset: [0, round((1 - ry) / 2, 4)] };
+}
+
+/**
+ * The camera's target position for a pointer at (px, py) in −1…1: it moves
+ * WITH the pointer, gently, so the case is seen a little from the side you
+ * lean to — and the planes in front slide against the wall behind them.
+ */
+export function cameraTarget(px: number, py: number): [number, number, number] {
+ const [x, y, z] = CAMERA.position;
+ return [round(x + clamp(px) * CAMERA.swayX, 3), round(y + clamp(py) * CAMERA.swayY, 3), z];
+}
+
+/** An exponential lerp factor for one frame of `dt` seconds at `CAMERA.follow`. */
+export function followAlpha(dt: number): number {
+ return 1 - Math.exp(-CAMERA.follow * Math.max(0, dt));
+}
+
+function clamp(v: number): number {
+ return Math.min(1, Math.max(-1, v));
+}
+
+function round(v: number, places: number): number {
+ const f = 10 ** places;
+ return Math.round(v * f) / f;
+}
diff --git a/jarvis/ui/web/frontend/src/views/RunInspectorView.tsx b/jarvis/ui/web/frontend/src/views/RunInspectorView.tsx
index 4570e92dcb..8cbba8672d 100644
--- a/jarvis/ui/web/frontend/src/views/RunInspectorView.tsx
+++ b/jarvis/ui/web/frontend/src/views/RunInspectorView.tsx
@@ -1,55 +1,186 @@
-import { useEffect, useState } from "react";
-import { useT } from "@/i18n";
-import { useRuns } from "@/hooks/useRuns";
-import { EmptyState } from "@/components/layout/EmptyState";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { FlaskConical, Search } from "lucide-react";
+
+import { EmptyState } from "@/components/ui/empty-state";
+import { Input } from "@/components/ui/input";
import { PanelSkeleton } from "@/components/layout/PanelSkeleton";
-import { RunList } from "@/components/runs/RunList";
import { RunDetail } from "@/components/runs/RunDetail";
+import { RunList } from "@/components/runs/RunList";
+import { useRuns } from "@/hooks/useRuns";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { ViewHeader } from "@/views/ChatsView";
+
+/**
+ * Run Inspector — master–detail over every recorded run.
+ *
+ * Left: the rail, one row per run, searchable across the utterance, the
+ * session id and the capabilities the run touched. Right: the selected run,
+ * whose own header and tabs carry the forensic material.
+ *
+ * The layout measures ITSELF, not the window: this view also runs in a solo
+ * window and beside a wide sidebar, and below ~900 px a 320 px rail plus a
+ * reading column no longer fit. There it stacks — the rail is the screen, and
+ * picking a run replaces it with the detail plus a Back control.
+ */
+
+/** Below this container width the master–detail splits into stacked screens. */
+const NARROW_PX = 900;
export function RunInspectorView() {
const t = useT();
const { data: runs, isError, isLoading } = useRuns();
const [selected, setSelected] = useState<string | null>(null);
+ const [query, setQuery] = useState("");
+ // `null` = not measured yet, so nothing auto-selects before the layout is
+ // known — on a narrow container an auto-selection hides the list outright.
+ const [narrow, setNarrow] = useState<boolean | null>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
- if (selected === null && runs && runs.length > 0) setSelected(runs[0].session_id);
- }, [runs, selected]);
+ const el = rootRef.current;
+ if (!el || typeof ResizeObserver === "undefined") {
+ setNarrow(false);
+ return;
+ }
+ const observer = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width ?? 0;
+ if (width > 0) setNarrow(width < NARROW_PX);
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ // Wide layouts open on the newest run, because the detail pane is on screen
+ // anyway and an empty one next to a full list reads as a failure to load.
+ useEffect(() => {
+ if (narrow !== false || selected !== null) return;
+ if (runs && runs.length > 0) setSelected(runs[0].session_id);
+ }, [narrow, runs, selected]);
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q || !runs) return runs ?? [];
+ return runs.filter(
+ (r) =>
+ r.preview.toLowerCase().includes(q) ||
+ r.session_id.toLowerCase().includes(q) ||
+ r.feature_tags.some((tag) => tag.toLowerCase().includes(q)),
+ );
+ }, [runs, query]);
if (isError) {
+ // The recorder is off, not broken — a designed state, with the reason.
return (
- <div className="flex h-full items-center justify-center">
- <EmptyState body={t("run_inspector.unavailable")} />
+ <div className="flex h-full flex-col">
+ <ViewHeader
+ icon={<FlaskConical />}
+ title={t("run_inspector.title")}
+ subtitle={t("run_inspector.subtitle")}
+ />
+ <div className="flex min-h-0 flex-1 items-center justify-center p-8">
+ <EmptyState
+ icon={<FlaskConical />}
+ title={t("run_inspector.unavailable")}
+ description={t("run_inspector.unavailable_body")}
+ />
+ </div>
</div>
);
}
+ const hasRuns = (runs?.length ?? 0) > 0;
+ const isNarrow = narrow === true;
+ const showList = !isNarrow || selected === null;
+ const showDetail = !isNarrow || selected !== null;
+
return (
- <div className="flex h-full">
- {/* The rail: standing chrome, so it sits one step below the page and
- never rises to --card no matter how tall it gets. */}
- <div className="w-[300px] shrink-0 overflow-y-auto border-r border-border bg-sidebar">
- <div className="px-4 py-4">
- <h2 className="text-title font-semibold text-foreground-strong">
- {t("run_inspector.title")}
- </h2>
- <p className="mt-1 text-meta text-muted-foreground">
- {t("run_inspector.subtitle")}
- </p>
- </div>
- {isLoading ? (
- <div className="px-2">
- <PanelSkeleton rows={6} rowHeight={64} label={t("run_inspector.title")} />
+ <div ref={rootRef} className="flex h-full flex-col">
+ <ViewHeader
+ icon={<FlaskConical />}
+ title={t("run_inspector.title")}
+ subtitle={t("run_inspector.subtitle")}
+ />
+
+ <div className="flex min-h-0 flex-1">
+ {showList && (
+ // A standing column the full height of the section: far too wide to
+ // earn --card, so it separates from the detail by taking the rail's
+ // own ground rather than by a rule.
+ <div
+ className={cn(
+ "flex min-h-0 shrink-0 flex-col border-r border-border bg-sidebar",
+ isNarrow ? "w-full" : "w-[320px]",
+ )}
+ >
+ {hasRuns && (
+ <div className="shrink-0 p-3">
+ <div className="relative">
+ <Search
+ aria-hidden
+ className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("run_inspector.search")}
+ aria-label={t("run_inspector.search")}
+ data-testid="run-search"
+ className="pl-9 ring-offset-sidebar"
+ />
+ </div>
+ </div>
+ )}
+ <nav
+ aria-label={t("run_inspector.title")}
+ className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis p-2"
+ >
+ {isLoading ? (
+ // Real rows at their real height, not a spinner in a void.
+ <PanelSkeleton
+ rows={7}
+ rowHeight={72}
+ label={t("run_inspector.loading")}
+ className="p-1"
+ />
+ ) : !hasRuns ? (
+ // The stage carries the empty state; the rail says nothing twice.
+ null
+ ) : filtered.length === 0 ? (
+ <p className="px-3 py-8 text-center text-base text-muted-foreground">
+ {t("run_inspector.no_matches")}
+ </p>
+ ) : (
+ <RunList items={filtered} selectedId={selected} onSelect={setSelected} />
+ )}
+ </nav>
</div>
- ) : (
- <RunList items={runs ?? []} selectedId={selected} onSelect={setSelected} />
)}
- </div>
- <div className="min-h-0 min-w-0 flex-1">
- {selected ? (
- <RunDetail sessionId={selected} />
- ) : (
- <div className="flex h-full items-center justify-center p-5">
- <EmptyState body={t("run_inspector.empty")} />
+
+ {showDetail && (
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ {selected ? (
+ <RunDetail
+ sessionId={selected}
+ onBack={isNarrow ? () => setSelected(null) : undefined}
+ />
+ ) : !hasRuns && !isLoading ? (
+ <div className="flex h-full items-center justify-center p-8">
+ <EmptyState
+ icon={<FlaskConical />}
+ title={t("run_inspector.empty_title")}
+ description={t("run_inspector.empty_body")}
+ />
+ </div>
+ ) : (
+ <div className="flex h-full items-center justify-center p-8">
+ <EmptyState
+ icon={<FlaskConical />}
+ title={t("run_inspector.empty")}
+ description={t("run_inspector.empty_hint")}
+ />
+ </div>
+ )}
</div>
)}
</div>
diff --git a/jarvis/ui/web/frontend/src/views/SessionsView.tsx b/jarvis/ui/web/frontend/src/views/SessionsView.tsx
index 61e42af907..c730fc9c14 100644
--- a/jarvis/ui/web/frontend/src/views/SessionsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SessionsView.tsx
@@ -1,5 +1,5 @@
import { AlertTriangle, Mic } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useEventStore } from "@/store/events";
import { ViewHeader } from "@/views/ChatsView";
@@ -8,16 +8,35 @@ import { SessionList } from "@/components/sessions/SessionList";
import { resolveSelectedSessionId } from "@/components/sessions/sessionSelection";
import { useSessionDetail, useSessions } from "@/hooks/useSessions";
import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+/**
+ * Below this much width the two columns stop fitting: the app's own navigation
+ * rail already takes 240 px, so an 850 px window leaves ~610 px here — a 320 px
+ * session rail beside it would push the transcript off screen.
+ */
+const NARROW_PX = 900;
/**
* Transcription: a 320 px rail of sessions on the sidebar ground, and the
* chosen session read as a conversation on the page ground.
+ *
+ * Narrow containers get the master–detail treatment instead: the rail alone,
+ * and the transcript alone once a session is picked, with the way back in its
+ * header. Width is measured on this view's own box, not the window — the view
+ * can share the window with anything else.
*/
export function SessionsView() {
const assistantName = useEventStore((s) => s.assistantName);
const t = useT();
const sessionsQuery = useSessions();
const [selectedId, setSelectedId] = useState<string | null>(null);
+ const [narrow, setNarrow] = useState(false);
+ // Stacked layout only: whether the transcript is the thing on screen. The
+ // selection itself resolves on its own (newest finished session), and that
+ // must NOT count as opening a session — a narrow view opens on the list.
+ const [detailOpen, setDetailOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const list = sessionsQuery.data;
@@ -25,6 +44,22 @@ export function SessionsView() {
setSelectedId((currentId) => resolveSelectedSessionId(list, currentId));
}, [sessionsQuery.data]);
+ useEffect(() => {
+ const el = rootRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width ?? 0;
+ setNarrow(width > 0 && width < NARROW_PX);
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ const selectSession = useCallback((id: string) => {
+ setSelectedId(id);
+ setDetailOpen(true);
+ }, []);
+
const detailQuery = useSessionDetail(selectedId);
const errorMessage = sessionsQuery.error
@@ -33,8 +68,11 @@ export function SessionsView() {
: t("sessions_view.unknown_error")
: null;
+ const showList = !narrow || !detailOpen;
+ const showDetail = !narrow || detailOpen;
+
return (
- <div className="flex h-full flex-col">
+ <div ref={rootRef} className="flex h-full flex-col">
<ViewHeader
icon={<Mic />}
title={t("sessions_view.title")}
@@ -63,22 +101,32 @@ export function SessionsView() {
</div>
)}
- <div className="grid min-h-0 flex-1 grid-cols-[320px_1fr] border-t border-border">
- <div className="min-h-0 overflow-hidden border-r border-border bg-sidebar">
- <SessionList
- sessions={sessionsQuery.data ?? []}
- selectedId={selectedId}
- onSelect={setSelectedId}
- loading={sessionsQuery.isLoading}
- />
- </div>
- <div className="flex min-h-0 min-w-0 flex-col overflow-hidden">
- <SessionDetail
- detail={detailQuery.data}
- loading={detailQuery.isLoading && selectedId !== null}
- error={detailQuery.error as Error | null}
- />
- </div>
+ <div className="flex min-h-0 flex-1 border-t border-border">
+ {showList && (
+ <div
+ className={cn(
+ "min-h-0 overflow-hidden bg-sidebar",
+ narrow ? "w-full" : "w-[320px] shrink-0 border-r border-border",
+ )}
+ >
+ <SessionList
+ sessions={sessionsQuery.data ?? []}
+ selectedId={selectedId}
+ onSelect={selectSession}
+ loading={sessionsQuery.isLoading}
+ />
+ </div>
+ )}
+ {showDetail && (
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ <SessionDetail
+ detail={detailQuery.data}
+ loading={detailQuery.isLoading && selectedId !== null}
+ error={detailQuery.error as Error | null}
+ onBack={narrow ? () => setDetailOpen(false) : undefined}
+ />
+ </div>
+ )}
</div>
</div>
);
diff --git a/pyproject.toml b/pyproject.toml
index 5d8aa3999f..0868d42972 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "personal-jarvis"
-version = "2.0.0"
+version = "2.1.0"
description = "Voice-driven meta-orchestrator that turns one spoken request into a fleet of self-checking AI agents"
requires-python = ">=3.11,<3.15"
readme = "README.md"
@@ -751,6 +751,7 @@ awareness-recall = "jarvis.plugins.tool.awareness_recall:AwarenessRecallTool"
# only (ADR-0011 amendment); never in a worker set (AP-5/AP-14).
delegate-to-agent = "jarvis.plugins.tool.delegate_to_agent:DelegateToAgentTool"
society-status = "jarvis.plugins.tool.delegate_to_agent:SocietyStatusTool"
+message-agent = "jarvis.plugins.tool.message_agent:LeadMessageAgentTool"
# Skills-Brain-Integration — Brain-callable executor for installed user skills.
run-skill = "jarvis.plugins.tool.run_skill:RunSkillTool"
# Phase B5 — long-term wiki recall (router-tier, read-only).
diff --git a/scripts/ci/silent-handlers-baseline.json b/scripts/ci/silent-handlers-baseline.json
index 9c1b1eba27..1559303704 100644
--- a/scripts/ci/silent-handlers-baseline.json
+++ b/scripts/ci/silent-handlers-baseline.json
@@ -1,23 +1,33 @@
{
"_comment": "Per-file count of exception handlers that neither log nor re-raise. Generated by scripts/ci/check_silent_exception_handlers.py --update. These numbers may go DOWN freely; an increase is a gate failure.",
- "total": 1411,
+ "total": 1571,
"files": {
"jarvis/__main__.py": 9,
"jarvis/admin/executor.py": 9,
"jarvis/admin/helper.py": 3,
"jarvis/admin/ipc.py": 4,
"jarvis/admin/launcher.py": 2,
- "jarvis/admin/transport.py": 5,
+ "jarvis/admin/transport.py": 4,
"jarvis/admin/unix_socket.py": 4,
"jarvis/agent_accounts.py": 4,
+ "jarvis/agent_chat/runner_api.py": 2,
+ "jarvis/agent_chat/runner_brain.py": 2,
+ "jarvis/agent_chat/runner_cli.py": 8,
+ "jarvis/agent_chat/service.py": 1,
+ "jarvis/agent_chat/store.py": 1,
+ "jarvis/agent_chat/tools.py": 8,
"jarvis/agent_cli_probe.py": 1,
"jarvis/agent_config_parity.py": 10,
- "jarvis/agentic_ide/agent_sessions.py": 16,
+ "jarvis/agent_screen/runner/server.py": 1,
+ "jarvis/agent_screen/session.py": 5,
+ "jarvis/agent_screen/tools.py": 1,
+ "jarvis/agentic_ide/agent_sessions.py": 30,
+ "jarvis/agentic_ide/agent_transcript.py": 2,
"jarvis/agentic_ide/code_skeleton.py": 4,
"jarvis/agentic_ide/device.py": 1,
"jarvis/agentic_ide/drops.py": 4,
"jarvis/agentic_ide/file_index.py": 4,
- "jarvis/agentic_ide/folders.py": 13,
+ "jarvis/agentic_ide/folders.py": 16,
"jarvis/agentic_ide/interrupted.py": 1,
"jarvis/agentic_ide/native_picker.py": 2,
"jarvis/agentic_ide/prompt_composer.py": 2,
@@ -27,7 +37,7 @@
"jarvis/agentic_ide/session.py": 3,
"jarvis/agentic_ide/work_split.py": 3,
"jarvis/agents/registry.py": 2,
- "jarvis/audio/capture.py": 7,
+ "jarvis/audio/capture.py": 1,
"jarvis/audio/device_probe.py": 2,
"jarvis/audio/device_select.py": 1,
"jarvis/audio/devices.py": 3,
@@ -58,24 +68,23 @@
"jarvis/brain/cache_heartbeat.py": 2,
"jarvis/brain/drop_context.py": 1,
"jarvis/brain/evidence_gate.py": 1,
- "jarvis/brain/gemini_test_brain.py": 1,
"jarvis/brain/healthcheck.py": 3,
"jarvis/brain/identity_card.py": 6,
"jarvis/brain/launcher.py": 1,
"jarvis/brain/local_action_gate.py": 1,
- "jarvis/brain/manager.py": 29,
+ "jarvis/brain/manager.py": 32,
"jarvis/brain/model_catalog.py": 2,
+ "jarvis/brain/ollama_inventory.py": 2,
+ "jarvis/brain/ollama_overview.py": 2,
+ "jarvis/brain/ollama_runtime.py": 9,
"jarvis/brain/persona_loader.py": 3,
"jarvis/brain/provider_registry.py": 1,
"jarvis/brain/provider_test.py": 8,
"jarvis/brain/streaming.py": 2,
"jarvis/brain/structured_output_parser.py": 2,
- "jarvis/brain/tool_call_recovery.py": 1,
"jarvis/brain/tool_gateway.py": 1,
- "jarvis/brain/tool_use_loop.py": 1,
"jarvis/brain/tools/self_mod_tools.py": 4,
"jarvis/brain/vision_context.py": 1,
- "jarvis/browser_voice/route.py": 4,
"jarvis/browser_voice/session.py": 1,
"jarvis/channels/discord.py": 3,
"jarvis/channels/manager.py": 2,
@@ -86,6 +95,7 @@
"jarvis/cli_ctl/client.py": 2,
"jarvis/cli_ctl/commands/auth.py": 1,
"jarvis/cli_ctl/commands/config.py": 1,
+ "jarvis/cli_ctl/commands/local_models.py": 1,
"jarvis/cli_ctl/commands/system.py": 1,
"jarvis/cli_ctl/config.py": 1,
"jarvis/cli_ctl/discovery.py": 5,
@@ -98,11 +108,11 @@
"jarvis/clis/prober.py": 6,
"jarvis/clis/tool.py": 1,
"jarvis/clis/usage_log.py": 1,
- "jarvis/codex_auth.py": 7,
+ "jarvis/codex_auth.py": 6,
"jarvis/contacts/store.py": 2,
"jarvis/control/cost.py": 3,
"jarvis/control/wiring.py": 1,
- "jarvis/core/config.py": 18,
+ "jarvis/core/config.py": 20,
"jarvis/core/config_writer.py": 2,
"jarvis/core/control_key.py": 8,
"jarvis/core/interactive_terminal.py": 1,
@@ -114,13 +124,16 @@
"jarvis/core/review/spawns.py": 2,
"jarvis/core/screenshots.py": 2,
"jarvis/core/self_mod/schema_introspect.py": 1,
- "jarvis/core/self_mod/writer.py": 4,
+ "jarvis/core/self_mod/writer.py": 3,
+ "jarvis/core/text_stream.py": 2,
+ "jarvis/costs/cli_usage_index.py": 10,
+ "jarvis/costs/sources.py": 1,
"jarvis/cu/brain_call.py": 4,
"jarvis/cu/conventions.py": 3,
"jarvis/cu/engine.py": 11,
"jarvis/cu/geometry.py": 1,
"jarvis/cu/indicator/capture_guard.py": 1,
- "jarvis/cu/indicator/controller.py": 4,
+ "jarvis/cu/indicator/controller.py": 3,
"jarvis/cu/indicator/protocol.py": 2,
"jarvis/cu/verify.py": 5,
"jarvis/diagnostics/doctor.py": 4,
@@ -128,20 +141,25 @@
"jarvis/dictation/audio.py": 6,
"jarvis/dictation/history.py": 4,
"jarvis/dictation/insert.py": 1,
+ "jarvis/dictation/local_final.py": 1,
"jarvis/dictation/polish.py": 3,
"jarvis/dictation/polish_client.py": 2,
- "jarvis/dictation/segment.py": 2,
"jarvis/dictation/stats.py": 8,
"jarvis/docs/loader.py": 4,
"jarvis/docs/registry.py": 3,
"jarvis/docs/search.py": 1,
"jarvis/documents/extract.py": 6,
"jarvis/documents/media.py": 7,
+ "jarvis/friends/activity.py": 4,
+ "jarvis/friends/peer.py": 2,
+ "jarvis/friends/profile.py": 2,
+ "jarvis/friends/pulse.py": 3,
+ "jarvis/friends/socials.py": 3,
"jarvis/friends/status_publisher.py": 1,
"jarvis/google_cli/auth_service.py": 4,
"jarvis/google_cli/pty_runner.py": 2,
"jarvis/google_cli/resolver.py": 1,
- "jarvis/hardware/detection.py": 8,
+ "jarvis/hardware/detection.py": 13,
"jarvis/harness/base.py": 9,
"jarvis/harness/computer_use_context.py": 2,
"jarvis/harness/computer_use_planner.py": 3,
@@ -150,13 +168,27 @@
"jarvis/harness/screenshot_only_loop.py": 24,
"jarvis/harness/screenshot_only_loop_june13.py": 17,
"jarvis/harness/screenshot_only_loop_stable.py": 22,
+ "jarvis/local_models/assistant_prompt.py": 1,
+ "jarvis/local_models/assistant_session.py": 1,
+ "jarvis/local_models/assistant_test.py": 4,
+ "jarvis/local_models/autostart.py": 2,
+ "jarvis/local_models/benchmarks.py": 4,
+ "jarvis/local_models/health_monitor.py": 7,
"jarvis/marketplace/auth/oauth_dcr.py": 3,
"jarvis/marketplace/auth/oauth_device.py": 1,
"jarvis/marketplace/auth/oauth_pkce_loopback.py": 3,
"jarvis/marketplace/plugin_registry.py": 1,
+ "jarvis/marketplace/publish.py": 3,
"jarvis/marketplace/refresh_scheduler.py": 1,
+ "jarvis/mcp/agents/bridge.py": 2,
+ "jarvis/mcp/agents/export.py": 1,
+ "jarvis/mcp/agents/portable.py": 1,
+ "jarvis/mcp/agents/server.py": 1,
+ "jarvis/mcp/agents/tokens.py": 1,
+ "jarvis/mcp/agents/tools.py": 4,
"jarvis/mcp/bootstrap.py": 3,
"jarvis/mcp/claude_export.py": 2,
+ "jarvis/mcp/jarvis_tools_server.py": 1,
"jarvis/mcp/server.py": 3,
"jarvis/mcp/state.py": 3,
"jarvis/memory/bootstrap_runner.py": 1,
@@ -186,12 +218,12 @@
"jarvis/memory/wiki/session_rollup.py": 1,
"jarvis/memory/wiki/vault_index.py": 2,
"jarvis/memory/wiki/vault_root.py": 1,
- "jarvis/memory/wiki/voice_bridge.py": 1,
"jarvis/memory/wiki/watcher.py": 3,
"jarvis/memory/workspace.py": 2,
"jarvis/missions/cleanup.py": 2,
"jarvis/missions/critic/reflections.py": 1,
"jarvis/missions/critic/runner.py": 14,
+ "jarvis/missions/diff_summary.py": 4,
"jarvis/missions/event_store.py": 1,
"jarvis/missions/init.py": 1,
"jarvis/missions/isolation/env.py": 1,
@@ -204,6 +236,7 @@
"jarvis/missions/safety/destructive_confirm.py": 1,
"jarvis/missions/safety/injection_scanner.py": 1,
"jarvis/missions/stream_evidence.py": 6,
+ "jarvis/missions/subagent_fanout.py": 3,
"jarvis/missions/workers/api_agent_tools.py": 10,
"jarvis/missions/workers/claude_direct_worker.py": 2,
"jarvis/missions/workers/codex_direct_worker.py": 5,
@@ -214,6 +247,7 @@
"jarvis/overlay/drop_target.py": 1,
"jarvis/overlay/linux_surface.py": 1,
"jarvis/overlay/system_cursor.py": 4,
+ "jarvis/platform/capture_exclusion.py": 2,
"jarvis/platform/macos_ax.py": 2,
"jarvis/platform/monitors.py": 4,
"jarvis/platform/open_path.py": 2,
@@ -225,14 +259,13 @@
"jarvis/plugins/brain/antigravity.py": 2,
"jarvis/plugins/brain/claude_cli.py": 1,
"jarvis/plugins/brain/codex.py": 4,
- "jarvis/plugins/brain/gemini.py": 1,
"jarvis/plugins/brain/openrouter.py": 1,
"jarvis/plugins/harness/computer_use.py": 6,
"jarvis/plugins/harness/mcp_remote.py": 3,
"jarvis/plugins/realtime/gemini_live.py": 2,
- "jarvis/plugins/realtime/openai_realtime.py": 2,
- "jarvis/plugins/stt/__init__.py": 3,
+ "jarvis/plugins/stt/__init__.py": 4,
"jarvis/plugins/stt/errors.py": 2,
+ "jarvis/plugins/stt/fwhisper.py": 2,
"jarvis/plugins/stt/groq_api.py": 3,
"jarvis/plugins/stt/openai_api.py": 1,
"jarvis/plugins/tool/app_command.py": 2,
@@ -255,11 +288,12 @@
"jarvis/plugins/tool/read_visible_ui_state.py": 1,
"jarvis/plugins/tool/remember.py": 1,
"jarvis/plugins/tool/reset_orb_position.py": 1,
- "jarvis/plugins/tool/run_shell.py": 4,
+ "jarvis/plugins/tool/run_shell.py": 3,
"jarvis/plugins/tool/run_skill.py": 3,
"jarvis/plugins/tool/screen_snapshot.py": 1,
"jarvis/plugins/tool/scroll.py": 5,
"jarvis/plugins/tool/search_web.py": 3,
+ "jarvis/plugins/tool/spawn_subagents.py": 2,
"jarvis/plugins/tool/start_preview_server.py": 1,
"jarvis/plugins/tool/switch_window.py": 2,
"jarvis/plugins/tool/type_text.py": 7,
@@ -273,14 +307,14 @@
"jarvis/plugins/tool/wiki_recall.py": 1,
"jarvis/plugins/tts/__init__.py": 4,
"jarvis/plugins/tts/elevenlabs_tts.py": 1,
- "jarvis/plugins/tts/gemini_flash_tts.py": 4,
+ "jarvis/plugins/tts/gemini_flash_tts.py": 2,
"jarvis/realtime/desktop.py": 6,
"jarvis/realtime/session.py": 18,
"jarvis/realtime/tools.py": 2,
"jarvis/runs/analyzer.py": 1,
"jarvis/runs/runs_ws.py": 2,
"jarvis/safety/approval.py": 1,
- "jarvis/safety/risk_tier.py": 1,
+ "jarvis/safety/tool_executor.py": 1,
"jarvis/sessions/store.py": 3,
"jarvis/setup/dependencies.py": 4,
"jarvis/setup/desktop_integration.py": 1,
@@ -294,10 +328,9 @@
"jarvis/skills/bootstrap.py": 3,
"jarvis/skills/cli.py": 2,
"jarvis/skills/creator_service.py": 2,
- "jarvis/skills/eval_harness.py": 1,
"jarvis/skills/finder.py": 1,
"jarvis/skills/lifecycle.py": 2,
- "jarvis/skills/loader.py": 5,
+ "jarvis/skills/loader.py": 4,
"jarvis/skills/match_eval.py": 1,
"jarvis/skills/prefs.py": 1,
"jarvis/skills/prompt_injection.py": 2,
@@ -307,17 +340,35 @@
"jarvis/skills/runner.py": 7,
"jarvis/skills/trigger_matcher.py": 5,
"jarvis/skills/validator.py": 4,
+ "jarvis/society/agent_tools.py": 4,
+ "jarvis/society/approvals.py": 1,
+ "jarvis/society/browser/install.py": 2,
+ "jarvis/society/browser/runner.py": 1,
+ "jarvis/society/browser/session.py": 2,
+ "jarvis/society/browser/tool.py": 2,
+ "jarvis/society/chat_binding.py": 1,
+ "jarvis/society/checkpoints.py": 4,
+ "jarvis/society/failure_reasons.py": 1,
+ "jarvis/society/memory.py": 2,
+ "jarvis/society/proposals.py": 1,
+ "jarvis/society/quests.py": 2,
+ "jarvis/society/roster.py": 1,
+ "jarvis/society/routines.py": 2,
+ "jarvis/society/runtime.py": 1,
+ "jarvis/society/shell.py": 2,
+ "jarvis/society/surface.py": 1,
"jarvis/speech/diagnose.py": 1,
- "jarvis/speech/pipeline.py": 68,
+ "jarvis/speech/pipeline.py": 66,
"jarvis/speech/rolling_whisper_wake.py": 3,
"jarvis/speech/stt_dictionary.py": 3,
"jarvis/speech/tts_eval/__main__.py": 1,
"jarvis/speech/voice_compare.py": 1,
"jarvis/speech/watchdog.py": 1,
+ "jarvis/state/chat_store.py": 1,
"jarvis/state/supervisor.py": 1,
"jarvis/tasks/runner.py": 5,
- "jarvis/tasks/scheduler.py": 4,
- "jarvis/tasks/store.py": 2,
+ "jarvis/tasks/scheduler.py": 5,
+ "jarvis/tasks/store.py": 3,
"jarvis/telemetry/latency_log.py": 1,
"jarvis/telephony/security.py": 1,
"jarvis/telephony/session.py": 1,
@@ -326,17 +377,20 @@
"jarvis/tools/latency_report.py": 1,
"jarvis/trigger/backends/noop.py": 1,
"jarvis/trigger/hotkey.py": 1,
+ "jarvis/ui/desktop_app.py": 5,
"jarvis/ui/icon_utils.py": 2,
"jarvis/ui/jarvisbar/interaction.py": 3,
"jarvis/ui/jarvisbar/overlay.py": 5,
"jarvis/ui/jarvisbar/qt_overlay.py": 2,
"jarvis/ui/jarvisbar/renderer.py": 3,
+ "jarvis/ui/native_dialog.py": 1,
"jarvis/ui/native_drag.py": 3,
"jarvis/ui/relauncher.py": 11,
"jarvis/ui/shell/runtime_check.py": 3,
"jarvis/ui/shell/shell.py": 1,
"jarvis/ui/shell/single_instance.py": 9,
"jarvis/ui/tray.py": 4,
+ "jarvis/ui/web/agent_chat_routes.py": 3,
"jarvis/ui/web/agentic_ide_routes.py": 4,
"jarvis/ui/web/board_routes.py": 2,
"jarvis/ui/web/claude_routes.py": 1,
@@ -345,31 +399,32 @@
"jarvis/ui/web/dictation_routes.py": 1,
"jarvis/ui/web/docs_routes.py": 1,
"jarvis/ui/web/fast_bootstrap.py": 7,
- "jarvis/ui/web/feedback_routes.py": 1,
- "jarvis/ui/web/launcher.py": 14,
+ "jarvis/ui/web/launcher.py": 16,
"jarvis/ui/web/marketplace_routes.py": 4,
"jarvis/ui/web/mcp_routes.py": 5,
"jarvis/ui/web/missions_pty_routes.py": 4,
"jarvis/ui/web/missions_ws_routes.py": 11,
"jarvis/ui/web/outputs_routes.py": 7,
"jarvis/ui/web/profile_routes.py": 7,
- "jarvis/ui/web/provider_routes.py": 9,
+ "jarvis/ui/web/provider_routes.py": 8,
"jarvis/ui/web/review_routes.py": 4,
"jarvis/ui/web/schema.py": 1,
"jarvis/ui/web/self_mod_routes.py": 1,
- "jarvis/ui/web/server.py": 24,
- "jarvis/ui/web/settings_routes.py": 5,
+ "jarvis/ui/web/server.py": 23,
+ "jarvis/ui/web/settings_routes.py": 4,
"jarvis/ui/web/setup_report_routes.py": 2,
"jarvis/ui/web/setup_routes.py": 1,
- "jarvis/ui/web/skills_routes.py": 7,
+ "jarvis/ui/web/skills_routes.py": 8,
"jarvis/ui/web/socials_routes.py": 1,
+ "jarvis/ui/web/society_figure_routes.py": 1,
+ "jarvis/ui/web/spa_build.py": 2,
"jarvis/ui/web/surface_security.py": 19,
"jarvis/ui/web/tasks_routes.py": 1,
"jarvis/ui/web/telephony_routes.py": 10,
"jarvis/ui/web/wiki_routes.py": 6,
"jarvis/ui/web/wiki_ws.py": 3,
"jarvis/ui/web/workflows_routes.py": 3,
- "jarvis/ui/web/workspace_routes.py": 4,
+ "jarvis/ui/web/workspace_routes.py": 3,
"jarvis/vision/atspi_tree.py": 14,
"jarvis/vision/ax_tree.py": 4,
"jarvis/vision/context_provider.py": 1,
@@ -378,8 +433,8 @@
"jarvis/vision/set_of_marks.py": 3,
"jarvis/vision/uia_tree.py": 5,
"jarvis/voice/number_speller.py": 1,
- "jarvis/workflows/runner.py": 4,
- "jarvis/workflows/scheduler.py": 3,
+ "jarvis/workflows/runner.py": 3,
+ "jarvis/workflows/scheduler.py": 4,
"jarvis/workflows/store.py": 1,
"jarvis/workspace/agents.py": 2,
"jarvis/workspace/trust.py": 1
diff --git a/tests/contract/test_internal_messages.py b/tests/contract/test_internal_messages.py
new file mode 100644
index 0000000000..bb939b2e75
--- /dev/null
+++ b/tests/contract/test_internal_messages.py
@@ -0,0 +1,256 @@
+"""Internal messaging contracts: durable delivery, trusted authors and replay."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from uuid import uuid4
+
+import pytest
+
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.runner_api import messages_from_events
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.plugins.tool.message_agent import LeadMessageAgentTool
+from jarvis.society.agent_tools import MessageAgentTool
+from jarvis.society.chat_binding import make_deliver_hook
+from jarvis.society.delivery import IncomingMessage, incoming_context
+from jarvis.society.runtime import SocietyRuntime
+
+
+async def world(tmp_path, monkeypatch):
+ import jarvis.agent_chat.service as service_module
+
+ seen = []
+
+ async def run(handle, prompt, **kwargs):
+ seen.append((handle.session.session_id, prompt, incoming_context.get()))
+ await handle.cancel.wait()
+ await handle.emit(
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": handle.turn_id,
+ "status": "cancelled",
+ },
+ )
+ )
+
+ monkeypatch.setattr(service_module, "run_brain_turn", run)
+ store = AgentChatStore(tmp_path / "chat.db")
+ svc = AgentChatService(store)
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))
+ rt = SocietyRuntime(tmp_path, seed_starter_team=False, chat_service=lambda: svc)
+ await rt.ensure_started()
+ await rt.roster.create(name="Gmail agent", provider="openai", model="test-model")
+ await rt.roster.create(name="Scout", provider="openai", model="test-model")
+ rt.set_deliver(
+ make_deliver_hook(
+ lambda: svc,
+ lambda: cfg,
+ resolve_name=lambda ident: "Jarvis" if ident == rt.lead_id else ident.title(),
+ )
+ )
+ try:
+ yield rt, svc, seen
+ finally:
+ await rt.close()
+ await svc.cancel_all()
+ store.close()
+
+
+CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={})
+
+
+async def drain(rt):
+ for _ in range(5):
+ await rt.scheduler.drain_deliveries()
+ await asyncio.sleep(0.01)
+
+
+async def test_lead_message_is_an_internal_chat_receipt(world):
+ rt, svc, seen = world
+ tool = LeadMessageAgentTool(runtime_resolver=lambda: rt)
+ result = await tool.execute({"target": "Gmail agent", "text": "A test message"}, CTX)
+ await drain(rt)
+ assert result.success and tool.risk_tier == "safe"
+ target = await rt.roster.resolve("Gmail agent")
+ events = svc.store.list_events(target.session_id)
+ receipt = next(e["payload"] for e in events if e["kind"] == "agent_message")
+ assert receipt["sender_name"] == "Jarvis" and receipt["sender_kind"] == "jarvis"
+ assert receipt["text"] == "A test message"
+ assert not any(e["kind"] == "user_message" for e in events)
+ assert seen[0][2].message_id == receipt["message_id"]
+ assert await rt.store.delivery_status(receipt["message_id"]) == "delivered"
+
+
+async def test_busy_recipient_keeps_fifo_receipts_then_resumes_once(world):
+ rt, svc, _ = world
+ first = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="first")
+ await drain(rt)
+ second = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="second")
+ third = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="third")
+ await drain(rt)
+ assert await rt.store.delivery_status(second.event_id) == "queued"
+ receipt = svc.store.incoming_message("society:scout", second.event_id)
+ assert receipt["status"] == "queued"
+ await svc.cancel("society:scout")
+ await drain(rt)
+ assert await rt.store.delivery_status(second.event_id) == "delivered"
+ assert await rt.store.delivery_status(third.event_id) == "queued"
+ await rt.scheduler.on_envelope(first)
+ await svc.cancel("society:scout")
+ await drain(rt)
+ events = svc.store.list_events("society:scout")
+ assert [e["payload"]["text"] for e in events if e["kind"] == "agent_message"] == [
+ "first",
+ "second",
+ "third",
+ ]
+ assert len([e for e in events if e["kind"] == "turn_started"]) == 3
+
+
+async def test_replay_after_chat_acceptance_does_not_start_another_turn(world):
+ rt, svc, _ = world
+ env = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="once")
+ await drain(rt)
+ # Simulate interruption after chat accepted the turn but before the board
+ # stored the receipt. The receiving chat is the idempotency boundary.
+ await rt.store.mark_delivery(env.event_id, "queued")
+ await svc.cancel("society:scout")
+ await drain(rt)
+ events = svc.store.list_events("society:scout")
+ assert sum(e["kind"] == "turn_started" for e in events) == 1
+ assert sum(e["kind"] == "agent_message" for e in events) == 1
+
+
+async def test_queue_survives_runtime_restart(world, tmp_path):
+ rt, svc, _ = world
+ rt.set_deliver(None)
+ env = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="recover me")
+ await rt.close()
+ await rt.ensure_started()
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))
+ rt.set_deliver(make_deliver_hook(lambda: svc, lambda: cfg))
+ await drain(rt)
+ assert await rt.store.delivery_status(env.event_id) == "delivered"
+
+
+async def test_failure_updates_a_visible_queued_message(world):
+ rt, svc, _ = world
+ await rt.say(from_agent=rt.lead_id, to_agent="scout", text="busy")
+ await drain(rt)
+ env = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="waiting")
+ await drain(rt)
+ await rt.store.set_kill_switch(True)
+ await drain(rt)
+ assert await rt.store.delivery_status(env.event_id) == "failed"
+ assert svc.store.incoming_message("society:scout", env.event_id)["status"] == "failed"
+
+
+async def test_agent_reply_keeps_conversation_and_cannot_forge_sender(world):
+ rt, _, _ = world
+ rt.set_deliver(None)
+ tool = MessageAgentTool(rt, "scout")
+ incoming = IncomingMessage(
+ message_id="parent",
+ sender_id=rt.lead_id,
+ sender_name="Jarvis",
+ sender_kind="jarvis",
+ text="hello",
+ prompt="hello",
+ trace_id="conversation",
+ )
+ token = incoming_context.set(incoming)
+ try:
+ result = await tool.execute(
+ {
+ "target": "Gmail agent",
+ "text": "reply",
+ "kind": "answer",
+ "sender": "Jarvis",
+ },
+ CTX,
+ )
+ finally:
+ incoming_context.reset(token)
+ events = await rt.store.events_for_trace(result.output["trace_id"])
+ assert events[0].from_agent == "scout"
+ assert events[0].parent_event_id == "parent"
+ assert result.output["trace_id"] == "conversation"
+ first = await tool.execute({"target": "Gmail agent", "text": "new"}, CTX)
+ second = await tool.execute({"target": "Gmail agent", "text": "another"}, CTX)
+ assert first.output["trace_id"] != second.output["trace_id"]
+
+
+async def test_concurrent_lazy_start_opens_once(tmp_path):
+ rt = SocietyRuntime(tmp_path, seed_starter_team=False)
+ try:
+ await asyncio.gather(*(rt.ensure_started() for _ in range(10)))
+ before = rt.store.bus.active_subs
+ conn = rt.store.conn
+ await rt.ensure_started()
+ assert rt.store.conn is conn
+ assert rt.store.bus.active_subs == before
+ assert len(await rt.roster.list()) == 1
+ finally:
+ await rt.close()
+
+
+def test_model_history_reads_delivered_internal_messages_once():
+ message = IncomingMessage(
+ message_id="m1",
+ sender_id="scout",
+ sender_name="Scout",
+ sender_kind="agent",
+ text="hello",
+ prompt="[say from Scout]\nhello",
+ trace_id="t",
+ ).model_dump()
+ queued = make_event("agent_message", message)
+ delivered = make_event("agent_message_status", {"message_id": "m1", "status": "delivered"})
+ assert messages_from_events([queued]) == []
+ history = messages_from_events([queued, delivered, delivered])
+ assert len(history) == 1 and history[0].content == message["prompt"]
+
+
+def test_delivery_status_parity():
+ root = Path(__file__).resolve().parents[2]
+ schema = (root / "jarvis/society/society_schema.sql").read_text(encoding="utf-8")
+ ts = (root / "jarvis/ui/web/frontend/src/lib/agentChatApi.ts").read_text(encoding="utf-8")
+ choices = IncomingMessage.model_fields["status"].annotation.__args__
+ assert choices == ("queued", "delivered", "failed")
+ assert "CHECK (status IN ('queued', 'delivered', 'failed'))" in schema
+ assert '["queued", "delivered", "failed"] as const' in ts
+
+
+async def test_internal_send_uses_executor_without_external_action_approval(world):
+ from tests.unit.safety.test_tool_executor_voice_confirm import _executor
+
+ rt, _, _ = world
+ executor, approval, _ = _executor()
+ result = await executor.execute(
+ LeadMessageAgentTool(runtime_resolver=lambda: rt),
+ args={"target": "Scout", "text": "hello"},
+ user_utterance="Send Scout a message",
+ config_snapshot={"voice_confirm": True},
+ )
+ assert result.success
+ assert approval.wait_calls == 0
+
+
+async def test_explicit_sender_deny_and_paused_recipient_are_not_bypassed(world):
+ rt, _, _ = world
+ await rt.roster.update("scout", {"denies": ["society_message_agent"]})
+ denied = await MessageAgentTool(rt, "scout").execute(
+ {"target": "Gmail agent", "text": "hello"}, CTX
+ )
+ assert not denied.success and denied.output["reason"] == "blocked_by_policy"
+ await rt.roster.update("scout", {"state": "paused"})
+ paused = await LeadMessageAgentTool(runtime_resolver=lambda: rt).execute(
+ {"target": "Scout", "text": "hello"}, CTX
+ )
+ assert not paused.success and paused.output["reason"] == "target_paused"
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 58a9c9648a..4eb787d63f 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -2001,6 +2001,7 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
# "Agent society voice tools".
"delegate-to-agent",
"society-status",
+ "message-agent",
}
)
assert ROUTER_TOOLS == expected, (
@@ -3862,3 +3863,11 @@ def test_live_tool_names_reads_both_surfaces_fresh() -> None:
assert "spawn_worker" not in manager._live_tool_names(), (
"_live_tool_names must never serve a cached snapshot"
)
+
+
+def test_internal_message_tool_is_router_only():
+ from jarvis.brain.factory import ROUTER_TOOLS
+ from jarvis.society.capabilities import NEVER_GRANTED
+
+ assert "message-agent" in ROUTER_TOOLS
+ assert "message_agent" in NEVER_GRANTED
diff --git a/tests/unit/brain/test_tool_use_loop_steer.py b/tests/unit/brain/test_tool_use_loop_steer.py
new file mode 100644
index 0000000000..4295defa87
--- /dev/null
+++ b/tests/unit/brain/test_tool_use_loop_steer.py
@@ -0,0 +1,102 @@
+"""Steering and phases: a message sent while a turn runs joins the NEXT round
+as the person's own words, and the turn says what it is doing."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+
+from jarvis.brain.loop_control import LoopControl
+from jarvis.brain.tool_use_loop import ToolUseLoop
+from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest, ToolResult
+
+
+class _Tool:
+ name = "gmail"
+ schema: dict[str, Any] = {}
+ description = "mail"
+
+
+class _Executor:
+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:
+ return ToolResult(success=True, output="two unread")
+
+
+class _ToolThenAnswer:
+ """One tool round, then an answer — the shape of a real turn."""
+
+ def __init__(self, rounds: int = 1) -> None:
+ self.requests: list[BrainRequest] = []
+ self._rounds = rounds
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) <= self._rounds:
+ yield BrainDelta(
+ tool_call={"id": f"c{len(self.requests)}", "name": "gmail", "input": {}}
+ )
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="Two unread mails.")
+ yield BrainDelta(finish_reason="stop")
+
+
+def _loop(brain: Any, control: LoopControl | None) -> ToolUseLoop:
+ return ToolUseLoop(brain, {"gmail": _Tool()}, _Executor(), loop_control=control)
+
+
+def _texts(req: BrainRequest) -> list[str]:
+ return [str(m.content) for m in req.messages if m.role == "user"]
+
+
+async def test_a_steer_message_joins_the_next_round():
+ brain = _ToolThenAnswer()
+ steer = [["and only the ones from today"], []]
+ control = LoopControl(drain_steer=lambda: steer.pop(0) if steer else [])
+ out = await _loop(brain, control).run([BrainMessage(role="user", content="check my mail")])
+ assert out.text == "Two unread mails."
+ second = brain.requests[1]
+ assert any("only the ones from today" in t for t in _texts(second))
+ # Steering continues the job: the round still carries the tools.
+ assert second.tools
+
+
+async def test_a_steer_after_the_last_round_reopens_the_loop():
+ brain = _ToolThenAnswer(rounds=0) # answers at once
+ steer = [[], ["actually, in English please"], []]
+ control = LoopControl(drain_steer=lambda: steer.pop(0) if steer else [])
+ await _loop(brain, control).run([BrainMessage(role="user", content="hi")])
+ assert len(brain.requests) == 2
+ assert any("in English please" in t for t in _texts(brain.requests[1]))
+
+
+async def test_phases_are_reported_once_per_change():
+ seen: list[tuple[str, str]] = []
+
+ async def on_phase(phase: str, detail: str) -> None:
+ seen.append((phase, detail))
+
+ brain = _ToolThenAnswer()
+ await _loop(brain, LoopControl(on_phase=on_phase)).run(
+ [BrainMessage(role="user", content="check my mail")]
+ )
+ assert seen == [("gather", "round 1"), ("act", "gmail"), ("gather", "round 2")]
+
+
+async def test_a_loop_without_a_control_behaves_exactly_as_before():
+ seen: list[Any] = []
+ brain = _ToolThenAnswer()
+ out = await _loop(brain, None).run([BrainMessage(role="user", content="check my mail")])
+ assert out.text == "Two unread mails."
+ assert len(brain.requests) == 2 and seen == []
+
+
+async def test_a_broken_steer_inbox_never_breaks_the_turn():
+ def boom() -> list[str]:
+ raise RuntimeError("inbox is gone")
+
+ brain = _ToolThenAnswer()
+ out = await _loop(brain, LoopControl(drain_steer=boom)).run(
+ [BrainMessage(role="user", content="check my mail")]
+ )
+ assert out.text == "Two unread mails."
diff --git a/tests/unit/brain/test_tool_use_loop_verify.py b/tests/unit/brain/test_tool_use_loop_verify.py
new file mode 100644
index 0000000000..fdc7b9e620
--- /dev/null
+++ b/tests/unit/brain/test_tool_use_loop_verify.py
@@ -0,0 +1,121 @@
+"""The verification pass: where the loop would finish, an answer is checked
+against what actually ran, and a revision is one more round WITH tools."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+
+from jarvis.brain.loop_control import LoopControl, VerifyOutcome, VerifyRequest
+from jarvis.brain.tool_use_loop import ToolUseLoop
+from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest, ToolResult
+
+
+class _Tool:
+ name = "gmail"
+ schema: dict[str, Any] = {}
+ description = "mail"
+
+
+class _Executor:
+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:
+ return ToolResult(success=True, output="two unread")
+
+
+class _Answers:
+ """Answers a script of texts, calling the tool once at the start."""
+
+ def __init__(self, texts: list[str], *, tool_first: bool = True) -> None:
+ self.requests: list[BrainRequest] = []
+ self._texts = list(texts)
+ self._tool_first = tool_first
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if self._tool_first and len(self.requests) == 1:
+ yield BrainDelta(tool_call={"id": "c1", "name": "gmail", "input": {}})
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ text = self._texts.pop(0) if self._texts else "(done)"
+ yield BrainDelta(content=text)
+ yield BrainDelta(finish_reason="stop")
+
+
+def _loop(brain: Any, control: LoopControl) -> ToolUseLoop:
+ return ToolUseLoop(brain, {"gmail": _Tool()}, _Executor(), loop_control=control)
+
+
+async def test_a_revise_verdict_runs_one_more_round_with_tools():
+ seen: list[VerifyRequest] = []
+
+ async def verify(req: VerifyRequest, ask: Any) -> VerifyOutcome:
+ seen.append(req)
+ if req.attempt == 0:
+ return VerifyOutcome(accepted=False, instruction="Name the senders.")
+ return VerifyOutcome(accepted=True)
+
+ brain = _Answers(["Two unread.", "Two unread, from Ana and Ben."])
+ out = await _loop(brain, LoopControl(verify=verify)).run(
+ [BrainMessage(role="user", content="check my mail")]
+ )
+ # The revision IS the answer, not draft + revision glued together.
+ assert out.text == "Two unread, from Ana and Ben."
+ assert len(brain.requests) == 3
+ assert brain.requests[2].tools # a revision may look again
+ assert any("Name the senders." in str(m.content) for m in brain.requests[2].messages)
+ # The verifier sees what really ran, not what the answer claims.
+ assert [r.name for r in seen[0].tool_log] == ["gmail"]
+ assert seen[0].tool_log[0].ok is True
+ assert seen[0].user_text == "check my mail"
+
+
+async def test_verify_stops_at_the_cap():
+ async def always_revise(req: VerifyRequest, ask: Any) -> VerifyOutcome:
+ return VerifyOutcome(accepted=False, instruction="again")
+
+ brain = _Answers(["a", "b", "c", "d", "e"])
+ control = LoopControl(verify=always_revise, max_verify=2)
+ out = await _loop(brain, control).run([BrainMessage(role="user", content="hi")])
+ # one tool round + the first answer + exactly two revisions
+ assert len(brain.requests) == 4
+ assert out.text == "c"
+
+
+async def test_the_verifier_is_asked_through_the_turns_own_brain():
+ asked: list[tuple[str, str]] = []
+
+ async def verify(req: VerifyRequest, ask: Any) -> VerifyOutcome:
+ answer = await ask("be strict", "does it hold?")
+ asked.append(("verdict", answer))
+ return VerifyOutcome(accepted=True)
+
+ brain = _Answers(["Two unread.", "yes"], tool_first=False)
+ await _loop(brain, LoopControl(verify=verify)).run(
+ [BrainMessage(role="user", content="hi")]
+ )
+ assert asked == [("verdict", "yes")]
+ # The verifier's own question carries no tools: it judges, it never acts.
+ assert brain.requests[-1].tools == ()
+ assert brain.requests[-1].system == "be strict"
+
+
+async def test_a_verifier_that_raises_accepts_the_turn():
+ async def boom(req: VerifyRequest, ask: Any) -> VerifyOutcome:
+ raise RuntimeError("verifier is down")
+
+ brain = _Answers(["Two unread."])
+ out = await _loop(brain, LoopControl(verify=boom)).run(
+ [BrainMessage(role="user", content="check my mail")]
+ )
+ assert out.text == "Two unread."
+
+
+async def test_an_accepted_verdict_ends_the_turn():
+ async def ok(req: VerifyRequest, ask: Any) -> VerifyOutcome:
+ return VerifyOutcome(accepted=True)
+
+ brain = _Answers(["Two unread."])
+ out = await _loop(brain, LoopControl(verify=ok)).run(
+ [BrainMessage(role="user", content="check my mail")]
+ )
+ assert out.text == "Two unread." and len(brain.requests) == 2
diff --git a/tests/unit/realtime/test_internal_message_regression.py b/tests/unit/realtime/test_internal_message_regression.py
new file mode 100644
index 0000000000..c5b686ecc8
--- /dev/null
+++ b/tests/unit/realtime/test_internal_message_regression.py
@@ -0,0 +1,104 @@
+"""RUB-14: internal addressees, accepted voice replies, and duplicate tool calls."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.realtime.session import RealtimeVoiceSession
+from jarvis.realtime.tools import RealtimeToolBridge
+from jarvis.society.message_routing import is_internal_message_request
+from tests.unit.realtime.test_tools import FakeExecutor, FakeTool, _bridge
+
+
+ "text",
+ [
+ "Ja, kannst du bitte den Gmail Agenten eine Nachricht schreiben? Eine Testnachricht.", # i18n-allow: German input regression
+ "Send the Gmail agent a test message.",
+ "Escribe un mensaje al Gmail agente.",
+ ],
+)
+def test_internal_addressee_is_recognized(text):
+ assert is_internal_message_request(text, ["Gmail agent"])
+
+
+ "text",
+ [
+ "Send an email to Alice using Gmail.",
+ "Read the Gmail messages.",
+ "Which agents do you have?",
+ ],
+)
+def test_external_email_and_read_requests_are_not_rewritten(text):
+ assert not is_internal_message_request(text, ["Gmail agent"])
+
+
+async def test_original_request_cannot_start_gmail_approval(monkeypatch):
+ from jarvis.society import lead_card
+
+ monkeypatch.setattr(lead_card, "society_agent_names", lambda: ("Gmail agent",))
+ executor = FakeExecutor(confirmation_required=True)
+ bridge = RealtimeToolBridge(
+ tools={"gmail": FakeTool("gmail")}, executor=executor, language="de"
+ )
+ await bridge.handle_user_transcript("Kannst du dem Gmail Agenten eine Testnachricht schreiben?") # i18n-allow: German input regression
+ _, result = await bridge.execute(wire_name="gmail", arguments={"app_name": "mail"})
+ assert result["blocked"] and "message_agent" in result["error"]
+ assert executor.execute_calls == []
+ assert not bridge.has_pending_confirmation
+
+
+async def test_concurrent_retries_of_a_confirmed_action_execute_once():
+ bridge, _, executor = _bridge(confirmation_required=True)
+ await bridge.handle_user_transcript("Open Calculator")
+ args = {"app_name": "Calculator"}
+ await bridge.execute(wire_name="open_app", arguments=args)
+ await bridge.handle_user_transcript("Yes")
+ results = await asyncio.gather(
+ *(bridge.execute(wire_name="open_app", arguments=args) for _ in range(4))
+ )
+ await bridge.handle_user_transcript("Yes")
+ duplicate = await bridge.execute(wire_name="open_app", arguments=args)
+ assert all(result == duplicate for result in results)
+ assert len(executor.execute_calls) == len(executor.confirmed_calls) == 1
+
+
+async def test_new_request_after_confirmation_can_ask_again():
+ bridge, _, executor = _bridge(confirmation_required=True)
+ await bridge.handle_user_transcript("Open Calculator")
+ await bridge.execute(wire_name="open_app", arguments={"app_name": "Calculator"})
+ await bridge.handle_user_transcript("Yes")
+ await bridge.execute(wire_name="open_app", arguments={"app_name": "Calculator"})
+ await bridge.handle_user_transcript("Yes, now open Firefox instead")
+ _, result = await bridge.execute(wire_name="open_app", arguments={"app_name": "Firefox"})
+ assert result["confirmation_required"]
+ assert len(executor.execute_calls) == 2
+
+
+ "language,text",
+ [
+ ("de", "Ja, sende sie."),
+ ("en", "Yes, send it."),
+ ("es", "Sí, envíalo."),
+ ("de", "Nein, nicht senden."), # i18n-allow: German cancellation input
+ ],
+)
+def test_acoustically_grounded_answer_is_not_discarded_as_text_echo(language, text):
+ session = object.__new__(RealtimeVoiceSession)
+ now = time.monotonic()
+ session._tool_bridge = SimpleNamespace(has_pending_confirmation=True)
+ session._language = language
+ session._echo_playback_horizon = now - 3
+ session._last_voiced_input_monotonic = now - 1
+ assert session._grounded_confirmation(text)
+ # Audio from during playback is not affirmative user evidence.
+ session._last_voiced_input_monotonic = now - 4
+ assert not session._grounded_confirmation(text)
+ session._last_voiced_input_monotonic = 0
+ assert not session._grounded_confirmation(text)
diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.py
index 7673aeb1ea..049caea47c 100644
--- a/tests/unit/society/test_chat_binding.py
+++ b/tests/unit/society/test_chat_binding.py
@@ -17,6 +17,14 @@ from jarvis.society.runtime import SocietyRuntime
class FakeService:
+ from jarvis.agent_chat.service import AgentChatService
+
+ receive_message = AgentChatService.receive_message
+ message_status = AgentChatService.message_status
+
+ async def _emit(self, session_id, event):
+ self.store.append_event(session_id, event)
+
def __init__(self, store: AgentChatStore) -> None:
self.store = store
self.sent: list[tuple[str, str]] = []
@@ -25,7 +33,7 @@ class FakeService:
def is_running(self, session_id: str) -> bool:
return session_id in self.busy
- async def send(self, session_id: str, text: str, attachments=None) -> str:
+ async def send(self, session_id: str, text: str, attachments=None, *, incoming=None) -> str:
self.sent.append((session_id, text))
return "turn-1"
@@ -152,7 +160,7 @@ async def test_scheduler_delivers_through_the_hook(world):
rt.set_deliver(make_deliver_hook(lambda: svc, lambda: cfg))
await rt.say(from_agent="scout", to_agent="archivist", text="ping")
assert [s[0] for s in svc.sent] == ["society:archivist"]
- assert svc.sent[0][1].startswith("[say from scout]")
+ assert svc.sent[0][1].startswith("[say from Scout]")
def test_unfiltered_session_list_hides_society_sessions(tmp_path: Path):
@@ -190,7 +198,7 @@ class FakeTurnService(FakeService):
def unsubscribe(self, session_id: str, q) -> None:
self.queues.get(session_id, []).remove(q)
- async def send(self, session_id: str, text: str, attachments=None) -> str:
+ async def send(self, session_id: str, text: str, attachments=None, *, incoming=None) -> str:
self.sent.append((session_id, text))
return "turn-1"