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.

Make Society agent chats reliable and permission bound (#209)

Ruben Lütkef1e00cfca1f2
diff --git a/jarvis/agent_chat/approval_bridge.py b/jarvis/agent_chat/approval_bridge.py
index a4376f778d..02c5bc0ab0 100644
--- a/jarvis/agent_chat/approval_bridge.py
+++ b/jarvis/agent_chat/approval_bridge.py
@@ -169,11 +169,9 @@ class ChatApprovalBridge:
) -> str | None:
"""The ``approved_by`` label when the stance decides without a card, else None."""
name = _bare(tool_name)
- if grant.stance == "always_ask":
+ if grant.stance == "always_ask" or grant.force_ask(name, args or {}):
return None
if grant.stance == "bypass":
- if grant.force_ask(name, args or {}):
- return None
return "chat-bypass"
if name in grant.always_allowed:
return "user"
diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.py
index fb5b7282ff..936e73b88f 100644
--- a/jarvis/agent_chat/control.py
+++ b/jarvis/agent_chat/control.py
@@ -120,6 +120,16 @@ class ChatControls:
)
origin_token = _command_origin.set(request)
try:
+ session = self.service.store.get_session(sid)
+ binder = getattr(self.service, "bind_society_session", None)
+ if (
+ request.command
+ not in {"stop", "status", "help", "clear", "history", "model", "routines", "find"}
+ and session is not None
+ and session.surface == "society"
+ and binder is not None
+ ):
+ await binder(sid)
from jarvis.memory.wiki.secret_guard import contains_secret
if contains_secret(request.arguments):
@@ -338,13 +348,12 @@ class ChatControls:
from jarvis.core.tool_read_only import set_chat_read_only
from .events import make_event
- from .permissions import ladder_key, normalize_permission
+ from .permissions import ladder_key, normalize_permission, society_mode_supported
from .service import resolve_runner
session = self.service.store.get_session(sid)
- ladder = ladder_key(
- session.surface, resolve_runner(session.provider, surface=session.surface)
- )
+ runner = resolve_runner(session.provider, surface=session.surface)
+ ladder = ladder_key(session.surface, runner)
# /plan is a chat control, not a ladder choice: the Society ladder
# (bypass / ask / always ask) has no read-only rung, and folding
# "plan" onto it would silently leave the turn able to write.
@@ -352,7 +361,20 @@ class ChatControls:
if permission in ("plan", "read-only") and folded not in ("plan", "read-only"):
folded = "plan"
permission = folded
+ if session.surface == "society" and self.service.is_running(sid):
+ raise ValueError("The agent chat is working; stop it before changing permissions")
+ if session.surface == "society" and permission not in ("plan", "read-only"):
+ if not society_mode_supported(runner, permission):
+ raise ValueError(f"{runner} cannot provide an actionable approval for {permission}")
self.service.store.update_session(sid, permission_mode=permission)
+ if session.surface == "society":
+ self.service.store.set_permission_override(sid, permission)
+ binder = getattr(self.service, "bind_society_session", None)
+ bound = await binder(sid) if binder is not None else session
+ self.service.store.set_permission_override(sid, bound.permission_mode)
+ if bound.permission_mode != permission:
+ raise ValueError("The agent's roster does not permit that chat mode")
+ permission = bound.permission_mode
state.mode = "plan" if permission in ("plan", "read-only") else "build"
set_chat_read_only(sid, state.mode == "plan")
await self.publish(state)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 2e9cf3a284..ba9f555fa0 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -677,14 +677,12 @@ def agy_model_args(
# Default model: agy accepts ``--effort`` alone.
return ["--effort", effort] if effort in _AGY_EFFORT_SUFFIXES else []
row = by_id.get(model)
+ if (row is None or not row.get("efforts")) and _is_base_gemini_id(model):
+ # A newer Gemini base id still requires --effort when discovery failed
+ # or returned a bare id without its suffixed variants.
+ level = effort if effort in _AGY_EFFORT_SUFFIXES else _AGY_DEFAULT_EFFORT
+ return ["--model", model, "--effort", level]
if row is None:
- if _is_base_gemini_id(model):
- # A Gemini release newer than the catalog Jarvis holds (live
- # 2026-09: "gemini-3.8-flash" in a routine). agy refuses a base id
- # without a level ("requires --effort"), and nobody picks efforts
- # by hand, so the chosen one or agy's own default is filled in.
- level = effort if effort in _AGY_EFFORT_SUFFIXES else _AGY_DEFAULT_EFFORT
- return ["--model", model, "--effort", level]
# A suffixed or non-Gemini unknown id: pass it through untouched.
return ["--model", model]
ladder = list(row.get("efforts") or [])
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index bab97d7a94..0e66112595 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -508,6 +508,14 @@ class AgentChatService:
),
)
+ async def bind_society_session(
+ self, session_id: str, *, routine_run: bool = False
+ ) -> AgentChatSession:
+ """Recheck the roster before a Society command or turn uses a session."""
+ from jarvis.society.chat_binding import bind_society_session
+
+ return await bind_society_session(self, session_id, routine_run=routine_run)
+
async def send(
self,
session_id: str,
@@ -523,6 +531,7 @@ class AgentChatService:
output_language: str = "",
native_goal: bool = False,
display_text: str | None = None,
+ routine_run: bool = False,
) -> str:
"""Persist the person's message and start the turn. Returns turn_id.
@@ -539,6 +548,8 @@ class AgentChatService:
session = self.store.get_session(session_id)
if session is None:
raise NoSuchSession(session_id)
+ if session.surface == "society":
+ session = await self.bind_society_session(session_id, routine_run=routine_run)
selected_runner = None
if session.surface == "jarvis":
from jarvis.core.model_selection import worker_selection
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index cf2ce5959b..0986eb4d44 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -2,7 +2,7 @@
Mirrors ``jarvis/state/chat_store.py``: one ``sqlite3`` connection in WAL
mode behind a ``threading.Lock`` (route handlers and the runner share the
-asyncio loop; the lock keeps a future worker-thread caller safe). Two tables:
+asyncio loop; the lock keeps a future worker-thread caller safe). Three tables:
``agent_chat_sessions``
One row per session — title, the provider / model / effort the composer
@@ -14,6 +14,9 @@ asyncio loop; the lock keeps a future worker-thread caller safe). Two tables:
The append-only event log (see :mod:`jarvis.agent_chat.events`), ordered
by ``seq`` per session. Transient kinds are never written.
+``agent_chat_permission_overrides``
+ A user's explicit Society chat stance, kept apart from the roster ceiling.
+
Ordering by ``seq`` (our own counter), not by wall clock: Windows ``time()``
resolution can tie two fast appends.
"""
@@ -55,6 +58,10 @@ CREATE TABLE IF NOT EXISTS agent_chat_events (
payload TEXT NOT NULL,
PRIMARY KEY (session_id, seq)
);
+CREATE TABLE IF NOT EXISTS agent_chat_permission_overrides (
+ session_id TEXT PRIMARY KEY,
+ mode TEXT NOT NULL
+);
CREATE INDEX IF NOT EXISTS idx_agent_chat_sessions_updated
ON agent_chat_sessions(updated_ms DESC);
"""
@@ -244,6 +251,24 @@ class AgentChatStore:
self._conn.commit()
return self.get_session(session_id)
+ def permission_override(self, session_id: str) -> str:
+ """The user's explicit stance, separate from a Society roster ceiling."""
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT mode FROM agent_chat_permission_overrides WHERE session_id = ?",
+ (session_id,),
+ ).fetchone()
+ return str(row[0]) if row else ""
+
+ def set_permission_override(self, session_id: str, mode: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "INSERT INTO agent_chat_permission_overrides (session_id, mode) VALUES (?, ?) "
+ "ON CONFLICT(session_id) DO UPDATE SET mode = excluded.mode",
+ (session_id, mode),
+ )
+ self._conn.commit()
+
def data_version(self) -> int:
"""How many one-shot data migrations this file has already had.
@@ -293,6 +318,9 @@ class AgentChatStore:
"DELETE FROM agent_chat_sessions WHERE session_id = ?", (session_id,)
)
self._conn.execute("DELETE FROM agent_chat_events WHERE session_id = ?", (session_id,))
+ self._conn.execute(
+ "DELETE FROM agent_chat_permission_overrides WHERE session_id = ?", (session_id,)
+ )
self._conn.commit()
return cur.rowcount > 0
@@ -381,6 +409,17 @@ class AgentChatStore:
"payload": json.loads(row["payload"]),
}
+ def turn_has_text_before(self, session_id: str, turn_id: str, before_seq: int) -> bool:
+ """Whether this exact turn wrote a nonblank answer before its terminal."""
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT 1 FROM agent_chat_events WHERE session_id = ? AND seq < ? "
+ "AND kind = 'assistant_text' AND json_extract(payload, '$.turn_id') = ? "
+ "AND trim(coalesce(json_extract(payload, '$.text'), '')) <> '' LIMIT 1",
+ (session_id, before_seq, turn_id),
+ ).fetchone()
+ return row is not None
+
def list_events(
self, session_id: str, *, after_seq: int = 0, tail: int | None = None
) -> list[dict[str, Any]]:
diff --git a/jarvis/screen_context/intent.py b/jarvis/screen_context/intent.py
index ce9f20cb38..88986159bc 100644
--- a/jarvis/screen_context/intent.py
+++ b/jarvis/screen_context/intent.py
@@ -290,7 +290,7 @@ _SCREEN_INTENT_RE: re.Pattern[str] = re.compile(
# readily as "Bildschirm" — the miss sent a live turn into a blind
# tool-loop instead of the one-shot look (voice session 2026-08-06 20:51).
# i18n-allow: German speech-input matching data
- r"|\b(?:auf|an|in)\s+(?:dem|den|meinem|meinen|deinem|deinen|diesem|diesen)" # i18n-allow: DE input
+ r"|\b(?:auf|an|in)\s+(?:dem|den|meinem|meinen|deinem|deinen|diesem|diesen)" # i18n-allow
r"\s+(?:bildschirm|monitor|screen|display)\b" # i18n-allow: DE input
r"|\bam\s+(?:bildschirm|monitor|screen|display)\b" # i18n-allow: DE input
r"|\bmein(?:en|em)?\s+(?:bildschirm|monitor|screen|display)\b" # i18n-allow
@@ -365,7 +365,7 @@ _APPSHOT_META_RE: re.Pattern[str] = re.compile(
rf"\bwhat\s+(?:is|are)\s+(?:an?\s+)?{_APPSHOT_WORD}"
rf"|\bhow\s+(?:do|does|can|to)\b[^.?!]{{0,48}}{_APPSHOT_WORD}"
# i18n-allow: German speech-input matching data
- rf"|\bwas\s+(?:ist|sind)\s+(?:ein(?:e)?\s+)?{_APPSHOT_WORD}"
+ rf"|\bwas\s+(?:ist|sind)\s+(?:ein(?:e)?\s+)?{_APPSHOT_WORD}" # i18n-allow: DE speech input
rf"|\bwie\s+(?:funktioniert|funktionieren|geht|macht\s+man)\b[^.?!]{{0,48}}{_APPSHOT_WORD}"
# i18n-allow: Spanish speech-input matching data
rf"|\bque\s+(?:es|son)\s+(?:un\s+)?{_APPSHOT_WORD}"
@@ -373,9 +373,11 @@ _APPSHOT_META_RE: re.Pattern[str] = re.compile(
# Opening the Appshots settings page is navigation, not a capture.
r"|\b(?:open|go\s+to|navigate\s+to|oeffne|geh\s+(?:zu|in|auf)" # i18n-allow: DE input
r"|wechsel\s+(?:zu|in)|abre|ve\s+a)\b[^.?!]{0,24}?"
- rf"(?:the\s+|die\s+|den\s+|los\s+)?{_APPSHOT_WORD}"
- r"(?:\s+(?:settings|page|section|einstellungen|seite|ajustes|pagina))?\s*(?:$|[.?!;:])"
- rf"|{_APPSHOT_WORD}[\s-]?(?:settings|page|section|einstellungen|seite|ajustes)\b"
+ rf"(?:the\s+|die\s+|den\s+|los\s+)?{_APPSHOT_WORD}" # i18n-allow: DE speech input
+ r"(?:\s+(?:settings|page|section|einstellungen|seite" # i18n-allow
+ r"|ajustes|pagina))?\s*(?:$|[.?!;:])"
+ rf"|{_APPSHOT_WORD}[\s-]?(?:settings|page|section"
+ r"|einstellungen|seite|ajustes)\b" # i18n-allow
r")",
re.IGNORECASE,
)
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index b7be22f302..81e5edf19c 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -645,7 +645,7 @@ class ShellTool:
verdict = decide(caller, "core:shell", tier, verb=level)
if verdict is Verdict.BLOCK:
return _failure(FailureReason.BLOCKED_BY_POLICY, "command class is blocked")
- if verdict is Verdict.QUEUE:
+ if verdict is Verdict.QUEUE and getattr(ctx, "approved_by", None) != "user":
item = await rt.approvals.enqueue(
agent_id=caller.agent_id,
trace_id=f"shell:{caller.agent_id}:{getattr(ctx, 'trace_id', '')}"[:120],
diff --git a/jarvis/society/approvals.py b/jarvis/society/approvals.py
index 2a7d4a62e9..3a00facd5c 100644
--- a/jarvis/society/approvals.py
+++ b/jarvis/society/approvals.py
@@ -60,14 +60,25 @@ def matches(pattern: str, capability_id: str, verb: str = "") -> bool:
return False
-def decide(agent: AgentRecord, capability_id: str, tool_tier: str, *, verb: str = "") -> Verdict:
- """What happens to one intended action of ``agent`` (see module doc)."""
+def decide(
+ agent: AgentRecord,
+ capability_id: str,
+ tool_tier: str,
+ *,
+ verb: str = "",
+ approval_mode: str | None = None,
+) -> Verdict:
+ """What happens to one intended action under the bound chat's mode."""
if tool_tier == "block":
return Verdict.BLOCK
rules = agent.approval_rules
if any(matches(p, capability_id, verb) for p in rules.get("require_approval", [])):
return Verdict.QUEUE
- mode = str(agent.approval_mode) if agent.approval_mode is not None else ""
+ mode = (
+ approval_mode
+ if approval_mode is not None
+ else str(agent.approval_mode) if agent.approval_mode is not None else ""
+ )
if mode == "always_ask":
return Verdict.QUEUE
if any(matches(p, capability_id, verb) for p in rules.get("always_allow", [])):
diff --git a/jarvis/society/browser/tool.py b/jarvis/society/browser/tool.py
index 671019d65e..8d3daff740 100644
--- a/jarvis/society/browser/tool.py
+++ b/jarvis/society/browser/tool.py
@@ -199,7 +199,7 @@ class BrowserTool:
if verdict is Verdict.BLOCK:
return _failure(FailureReason.BLOCKED_BY_POLICY, "browser use is blocked for you")
trace_id = f"browser:{caller.agent_id}:{getattr(ctx, 'trace_id', '')}"[:120]
- if verdict is Verdict.QUEUE:
+ if verdict is Verdict.QUEUE and getattr(ctx, "approved_by", None) != "user":
item = await rt.approvals.enqueue(
agent_id=caller.agent_id,
trace_id=trace_id,
diff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.py
index a883f157e4..057e8e6125 100644
--- a/jarvis/society/chat_binding.py
+++ b/jarvis/society/chat_binding.py
@@ -32,6 +32,7 @@ log = logging.getLogger(__name__)
__all__ = [
"SURFACE",
+ "bind_society_session",
"ensure_session",
"frame_assignment",
"frame_incoming",
@@ -83,11 +84,23 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:
ladder_key,
normalize_permission,
society_mode_supported,
+ stance_of,
)
from jarvis.agent_chat.service import resolve_runner
provider, model, effort = pair_for(cfg, agent)
runner = resolve_runner(provider, surface=SURFACE)
+ legacy_mode = ""
+ if agent.approval_mode is None:
+ legacy_mode = normalize_permission(
+ "jarvis", _CEILING_TO_MODE[str(agent.permission_ceiling)]
+ )
+ if legacy_mode not in ("plan", "read-only") and not society_mode_supported(
+ runner, "ask"
+ ):
+ raise PermissionError(
+ f"{runner} cannot provide an actionable approval for this legacy agent"
+ )
if agent.approval_mode is not None and not society_mode_supported(
runner, str(agent.approval_mode)
):
@@ -100,7 +113,7 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:
ladder = ladder_key(SURFACE, runner)
if agent.approval_mode is None:
# A pre-migration row keeps the old Jarvis ladder, including Plan.
- mode = normalize_permission("jarvis", _CEILING_TO_MODE[str(agent.permission_ceiling)])
+ mode = legacy_mode
else:
mode = normalize_permission(ladder, str(agent.approval_mode))
return svc.store.create_session(
@@ -114,22 +127,87 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:
surface=SURFACE,
account_id=agent.account_id,
)
- if existing.provider != provider or (model and existing.model != model):
- svc.store.reseat_session(session_id, provider=provider, model=model or existing.model)
+ if getattr(svc, "is_running", lambda _sid: False)(session_id):
+ # An active CLI turn still owns its provider-specific vendor session.
+ # Re-seat only after it ends so that id cannot land on another provider.
+ return existing
+ if existing.provider != provider or existing.model != model:
+ svc.store.reseat_session(session_id, provider=provider, model=model)
existing = svc.store.get_session(session_id)
+ ladder = ladder_key(SURFACE, resolve_runner(provider, surface=SURFACE))
+ if agent.approval_mode is None:
+ # Legacy roster rows encoded their chat stance in permission_ceiling.
+ mode = legacy_mode
+ else:
+ # Current rows keep chat prompts separate from the per-tool risk ceiling.
+ mode = normalize_permission(ladder, str(agent.approval_mode))
+ override = svc.store.permission_override(session_id)
+ if not override and existing.permission_mode in ("plan", "read-only"):
+ # Older sessions recorded /plan in the control state before the
+ # separate override record existed. Preserve that explicit choice.
+ control_store = getattr(getattr(svc, "controls", None), "store", None)
+ if control_store is not None:
+ control = control_store.get(session_id)
+ if control.mode == "plan" and control.previous_permission:
+ override = existing.permission_mode
+ svc.store.set_permission_override(session_id, override)
+ if override:
+ chosen = (
+ "plan" if override in ("plan", "read-only")
+ else normalize_permission(ladder, override)
+ )
+ if chosen not in ("plan", "read-only") and not society_mode_supported(runner, chosen):
+ raise PermissionError(f"{runner} cannot provide an actionable approval for {chosen}")
+ # A narrower chat choice survives rebinding. Always ask is stricter
+ # than Ask even though both share the universal ask-first stance.
+ if stance_of(chosen) < stance_of(mode) or (chosen == "always_ask" and mode == "ask"):
+ mode = chosen
updates: dict[str, str] = {}
- if agent.approval_mode is not None and existing.permission_mode != str(agent.approval_mode):
- updates["permission_mode"] = str(agent.approval_mode)
if getattr(existing, "account_id", "") != agent.account_id:
updates["account_id"] = agent.account_id
if effort and existing.effort != effort:
updates["effort"] = effort
+ if existing.permission_mode != mode:
+ updates["permission_mode"] = mode
+ if existing.title != agent.name:
+ updates["title"] = agent.name
+ workspace = _workspace(cfg, agent)
+ if existing.cwd != workspace:
+ updates["cwd"] = workspace
if updates:
svc.store.update_session(session_id, **updates)
existing = svc.store.get_session(session_id)
return existing
+async def bind_society_session(svc: Any, session_id: str, *, routine_run: bool = False) -> Any:
+ """Apply the live roster ceiling before a Society session is used."""
+ from jarvis.agent_chat.service import SessionBusy
+
+ from .runtime import current_runtime
+
+ if svc.is_running(session_id):
+ raise SessionBusy(session_id)
+ runtime = current_runtime()
+ agent_id = session_id.removeprefix("society:").split(":routine:", 1)[0]
+ agent = await runtime.roster.get(agent_id) if runtime is not None else None
+ session = svc.store.get_session(session_id)
+ if agent is None or session is None or session.surface != SURFACE:
+ raise PermissionError("Society agent is unavailable")
+ inactive = str(agent.state) != "active" or await runtime.store.kill_switch()
+ if session_id.startswith(f"{agent.session_id}:routine:"):
+ if not routine_run or inactive:
+ raise PermissionError("Routine chat requires an active scheduled run")
+ # Each scheduled run has its own explicitly pinned seat and permission
+ # contract. The internal caller has revalidated its live owner.
+ return session
+ if agent.session_id != session_id:
+ raise PermissionError("Society agent is unavailable")
+ if inactive:
+ raise PermissionError("Society agent is paused or disabled")
+ return ensure_session(svc, runtime.config(), agent)
+
+
def frame_incoming(env: SocietyEnvelope, sender_name: str) -> str:
"""How a board envelope reads inside the receiving agent's chat."""
kind = str(env.msg_type).lower()
diff --git a/jarvis/society/coding_supervision.py b/jarvis/society/coding_supervision.py
index d99eb74d9c..d4068045d0 100644
--- a/jarvis/society/coding_supervision.py
+++ b/jarvis/society/coding_supervision.py
@@ -438,7 +438,15 @@ class CodingSupervision:
if row["state"] != "running" or row["revision"] != revision:
return
incoming = IncomingMessage(**row["outbox"])
- await service.send(row["session_id"], incoming.prompt, incoming=incoming, direct_user=False)
+ routine_session = row["session_id"].startswith(f"society:{row['agent_id']}:routine:")
+ send_kwargs = {"incoming": incoming, "direct_user": False}
+ if routine_session:
+ send_kwargs["routine_run"] = True
+ await service.send(
+ row["session_id"],
+ incoming.prompt,
+ **send_kwargs,
+ )
row.update(outbox=None, turns=row["turns"] + 1)
if row["revision"] == revision and row["state"] == "running":
row["awaiting_action"] = True
diff --git a/jarvis/society/mars/ordinary.py b/jarvis/society/mars/ordinary.py
index f3af41a0eb..fb4ad10f27 100644
--- a/jarvis/society/mars/ordinary.py
+++ b/jarvis/society/mars/ordinary.py
@@ -139,7 +139,11 @@ class OrdinaryStationExecutor:
return None
status = str(terminal["payload"].get("status") or "")
if status in {"ok", "done", "completed"}:
- state = "completed"
+ state = (
+ "completed"
+ if service.store.turn_has_text_before(agent.session_id, run_id[5:], terminal["seq"])
+ else "failed"
+ )
elif status in {"canceled", "cancelled"}:
state = "canceled"
elif status in {"error", "failed", "blocked"}:
diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.py
index b9badaac19..85b1839184 100644
--- a/jarvis/society/routine_runner.py
+++ b/jarvis/society/routine_runner.py
@@ -170,7 +170,7 @@ async def run_owned_routine(
queue = service.subscribe(session.session_id)
answer = ""
try:
- turn_id = await service.send(session.session_id, task, direct_user=False)
+ turn_id = await service.send(session.session_id, task, direct_user=False, routine_run=True)
while True:
if cancel_token is not None and cancel_token.is_cancelled():
raise asyncio.CancelledError
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index 9f9491da95..29bfcdedba 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -154,6 +154,7 @@ async def _spoken_report(
_LEAD_INCOMING_TYPES: Final[frozenset[MsgType]] = frozenset(
{MsgType.SAY, MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE}
)
+_WATCH_EVENT_POLL_SECONDS: Final[float] = 2.0
_current: SocietyRuntime | None = None
@@ -910,33 +911,78 @@ class SocietyRuntime:
error = ""
tool_steps: list[str] = []
used_browser = False
+ last_seq = 0
+ read_failures = 0
quest_trace = env.trace_id.startswith("quest:")
try:
while True:
- event = await queue.get()
- kind = event.get("kind")
- payload = event.get("payload") or {}
- if payload.get("turn_id") not in (None, turn_id):
- continue
- if kind == "assistant_text":
- final_text = str(payload.get("text") or final_text)
- if quest_trace:
- await self.quests.note_progress(env.trace_id, "", live=final_text)
- elif kind == "tool_call":
- name = str(payload.get("name") or payload.get("tool") or "tool")
- summary = str(payload.get("summary") or "")[:120]
- step = f"{name}: {summary}" if summary else name
- tool_steps.append(step)
- if quest_trace:
- await self.quests.note_progress(env.trace_id, step)
- if name == "society_browser":
- used_browser = True
- elif kind == "error":
- status, error = "blocked", str(payload.get("message") or "error")
- elif kind == "turn_finished":
- if payload.get("status") not in (None, "ok", "done", "completed"):
+ try:
+ events = [
+ await asyncio.wait_for(queue.get(), timeout=_WATCH_EVENT_POLL_SECONDS)
+ ]
+ except TimeoutError:
+ # The service drops a subscriber whose queue overflows. Its
+ # events remain durable, so recover the missing terminal.
+ try:
+ events = await asyncio.to_thread(
+ svc.store.list_events, session_id, after_seq=last_seq
+ )
+ except Exception: # noqa: BLE001 - a broken chat store must release the slot
+ read_failures += 1
+ log.warning(
+ "society: durable turn recovery failed for %s (%s/3)",
+ run_id,
+ read_failures,
+ exc_info=True,
+ )
+ if read_failures < 3:
+ continue
status = "blocked"
- error = str(payload.get("error") or payload.get("status") or "")
+ error = "Agent result could not be recovered from chat history."
+ try:
+ await svc.cancel(session_id, expected_turn_id=turn_id)
+ except Exception: # noqa: BLE001 - still release the board slot
+ log.warning(
+ "society: turn %s could not be cancelled after recovery failure",
+ run_id,
+ exc_info=True,
+ )
+ break
+ read_failures = 0
+ else:
+ read_failures = 0
+ finished = False
+ for event in events:
+ seq = int(event.get("seq") or 0)
+ if seq and seq <= last_seq:
+ continue
+ last_seq = max(last_seq, seq)
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if payload.get("turn_id") not in (None, turn_id):
+ continue
+ if kind == "assistant_text":
+ final_text = str(payload.get("text") or final_text)
+ if quest_trace:
+ await self.quests.note_progress(env.trace_id, "", live=final_text)
+ elif kind == "tool_call":
+ name = str(payload.get("name") or payload.get("tool") or "tool")
+ summary = str(payload.get("summary") or "")[:120]
+ step = f"{name}: {summary}" if summary else name
+ tool_steps.append(step)
+ if quest_trace:
+ await self.quests.note_progress(env.trace_id, step)
+ if name == "society_browser":
+ used_browser = True
+ elif kind == "error":
+ status, error = "blocked", str(payload.get("message") or "error")
+ elif kind == "turn_finished":
+ if payload.get("status") not in (None, "ok", "done", "completed"):
+ status = "blocked"
+ error = str(payload.get("error") or payload.get("status") or "")
+ finished = True
+ break
+ if finished:
break
except asyncio.CancelledError: # Session cancellation is normal shutdown.
return
@@ -958,6 +1004,9 @@ class SocietyRuntime:
if reports:
status = "blocked"
error = summary = reports[-1].text
+ elif status == "done" and not final_text.strip():
+ status = "blocked"
+ error = summary = "Agent finished without a result report."
try:
await self.store.append_and_publish(
SocietyEnvelope(
@@ -1123,9 +1172,46 @@ class SocietyRuntime:
# ------------------------------------------------------------ controls
+ async def _cancel_active_society_chats(self) -> None:
+ service = self.chat_service()
+ if service is None or not callable(getattr(service, "cancel", None)):
+ return
+ # AgentChatService exposes is_running but not a public active-id list.
+ # Snapshot its live turns; a store query could miss an older active chat.
+ running = tuple(getattr(service, "_running", {}).items())
+ targets: list[str] = []
+ for session_id, run in running:
+ session = service.store.get_session(session_id)
+ if (
+ session is None
+ or session.surface != "society"
+ or not session_id.startswith("society:")
+ ):
+ continue
+ signal = getattr(service, "signal_cancel", None)
+ if callable(signal):
+ signal(session_id)
+ # The kill switch can be invoked from an agent's own turn. Signal
+ # it, but never await that turn from inside itself.
+ if getattr(run, "task", None) is asyncio.current_task():
+ continue
+ targets.append(session_id)
+ if not targets:
+ return
+ results = await asyncio.gather(
+ *(service.cancel(session_id) for session_id in targets),
+ return_exceptions=True,
+ )
+ for session_id, result in zip(targets, results, strict=True):
+ if isinstance(result, BaseException):
+ log.warning(
+ "society kill switch: chat %s did not stop", session_id, exc_info=result
+ )
+
async def engage_kill_switch(self) -> dict[str, Any]:
await self.store.set_kill_switch(True)
halted = await self.scheduler.halt_all()
+ await self._cancel_active_society_chats()
await self.browser.close()
settled = 0
for room in await self.rooms.list(state=RoomState.RUNNING):
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 9160df1127..ee63e3d704 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -25,7 +25,7 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any, Final, cast
-from jarvis.core.protocols import Tool
+from jarvis.core.protocols import Tool, ToolResult
from jarvis.core.response_style import CONVERSATIONAL_RESPONSE_STYLE, KEEP_GOING_ON_TOOL_FAILURE
from .agent_tools import (
@@ -243,6 +243,7 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | N
return None
read_only = str(agent.permission_ceiling) == "safe"
service = rt.chat_service()
+ session = None
if service is not None:
session = service.store.get_session(session_id)
if session is None:
@@ -273,7 +274,16 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | N
)
if tool.name not in picked:
return None
- return cast(Tool, _GatedTool(tool, agent, capability))
+ return cast(
+ Tool,
+ _GatedTool(
+ tool,
+ agent,
+ capability,
+ _effective_approval_mode(agent, session, _permission_override(rt, session)),
+ rt,
+ ),
+ )
async def tools_for_cli_session(
@@ -387,17 +397,27 @@ class _GatedTool:
"""A granted tool wrapped with the agent's approval rules.
The executor asks ``risk_tier_for_args`` before every call; this wrapper
- answers with ``approvals.decide`` over the roster row's rules and ceiling:
+ answers with ``approvals.decide`` over the bound chat mode, the roster
+ row's rules and ceiling:
a require-approval match or a call above the ceiling reads as ``ask`` (the
chat card appears), an always-allow match lets an ask-tier call run, a
blocked class stays ``block``. Everything else — schema, flags, execute —
is the inner tool's own.
"""
- def __init__(self, inner: Any, agent: AgentRecord, capability_id: str) -> None:
+ def __init__(
+ self,
+ inner: Any,
+ agent: AgentRecord,
+ capability_id: str,
+ approval_mode: str | None,
+ runtime: Any,
+ ) -> None:
self._inner = inner
self._agent = agent
self._capability_id = capability_id
+ self._approval_mode = approval_mode
+ self._runtime = runtime
self.name = inner.name
self.description = inner.description
self.schema = inner.schema
@@ -420,7 +440,13 @@ class _GatedTool:
if isinstance(own, str) and own:
base = own
try:
- verdict = decide(self._agent, self._capability_id, base, verb=_verb_of(args))
+ verdict = decide(
+ self._agent,
+ self._capability_id,
+ base,
+ verb=_verb_of(args),
+ approval_mode=self._approval_mode,
+ )
except Exception: # noqa: BLE001 — the static tier still gates the call
log.warning("society gate: decide failed for %s", self.name, exc_info=True)
return base
@@ -433,6 +459,15 @@ class _GatedTool:
return "monitor" if base == "ask" else base
async def execute(self, args: dict[str, Any], ctx: Any) -> Any:
+ # The catalog was selected at turn start. A pause or kill switch that
+ # arrives while the model is thinking must still stop its next call.
+ if await self._runtime.store.kill_switch():
+ return ToolResult(False, {"reason": "kill_switch"}, "the society is halted")
+ live = await self._runtime.roster.get(self._agent.agent_id)
+ if live is None or str(live.state) != "active":
+ return ToolResult(
+ False, {"reason": "blocked_by_policy"}, "caller is not an active agent"
+ )
return await self._inner.execute(args, ctx)
@@ -527,6 +562,30 @@ def _workspace_fallback(cfg: Any, agent_id: str) -> Path:
return data_dir / "society" / agent_id / "workspace"
+def _permission_override(runtime: Any, session: Any) -> str:
+ service = runtime.chat_service()
+ store = getattr(service, "store", None)
+ lookup = getattr(store, "permission_override", None)
+ session_id = getattr(session, "session_id", "")
+ return str(lookup(session_id) or "") if callable(lookup) and session_id else ""
+
+
+def _effective_approval_mode(
+ agent: AgentRecord, session: Any, override: str = ""
+) -> str | None:
+ """Use a narrower chat choice without widening the agent's roster mode."""
+ if agent.approval_mode is None:
+ # A pre-migration row keeps its ceiling policy until the person chooses
+ # a stricter stance for this chat; the bound mode alone is ambiguous.
+ return override if override in ("ask", "always_ask") else None
+ roster_mode = str(agent.approval_mode)
+ chat_mode = str(getattr(session, "permission_mode", "") or "")
+ strictness = {"bypass": 0, "ask": 1, "always_ask": 2}
+ if chat_mode in strictness and strictness[chat_mode] > strictness[roster_mode]:
+ return chat_mode
+ return roster_mode
+
+
def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]] | None:
rt = current_runtime()
agent_id = agent_id_of(getattr(session, "session_id", "") or "")
@@ -537,6 +596,7 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T
# The briefing fills the cache before the override is built. A miss
# cannot establish the agent's mode or grants, so offer no hands.
return lambda _tools: {}
+ approval_mode = _effective_approval_mode(agent, session, _permission_override(rt, session))
def _apply(tools: dict[str, Tool]) -> dict[str, Tool]:
own = {
@@ -556,17 +616,23 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T
# The gate rides on the executor's per-call tier hook, so the chat
# card and the queue stay the one approval path.
picked = {
- name: cast(Tool, _GatedTool(tool, agent, cap_id))
+ name: cast(Tool, _GatedTool(tool, agent, cap_id, approval_mode, rt))
for name, tool in picked.items()
if (cap_id := capability_id_for_tool(name)) is not None
}
ordered: dict[str, Tool] = {}
- if agent.approval_mode is not None:
+ if approval_mode is not None:
ordered.update(
{
name: cast(
Tool,
- _GatedTool(tool, agent, capability_id_for_tool(name) or "core:society"),
+ _GatedTool(
+ tool,
+ agent,
+ capability_id_for_tool(name) or "core:society",
+ approval_mode,
+ rt,
+ ),
)
for name, tool in own.items()
# Asking the user IS the person's decision; gating it
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 0a82bc8a6b..d8d4fc203a 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -62,6 +62,7 @@ from jarvis.agent_chat.permissions import (
ladder_key,
normalize_permission,
permission_modes,
+ society_mode_supported,
)
from jarvis.agent_chat.service import (
DECISIONS,
@@ -715,6 +716,10 @@ async def patch_session(
existing = svc.store.get_session(session_id)
if existing is None:
raise HTTPException(status_code=404, detail="session not found")
+ if existing.surface == "society" and ":routine:" in session_id:
+ raise HTTPException(status_code=403, detail="Routine chat is owned by its schedule")
+ if existing.surface == "society" and svc.is_running(session_id):
+ raise HTTPException(status_code=409, detail="Agent chat is working")
fields: dict[str, Any] = {}
if body.title is not None:
fields["title"] = body.title.strip()[:120]
@@ -749,6 +754,13 @@ async def patch_session(
+ ", ".join(m.id for m in permission_modes(ladder))
),
)
+ if current.surface == "society" and not society_mode_supported(
+ runner, body.permission_mode
+ ):
+ raise HTTPException(
+ status_code=422,
+ detail=f"{runner} cannot provide an actionable approval for {body.permission_mode}",
+ )
fields["permission_mode"] = body.permission_mode
elif "provider" in fields:
# A provider change folds the old mode onto the new runner's ladder
@@ -771,9 +783,21 @@ async def patch_session(
await svc.controls.pause(session_id, "Model or permission settings changed")
if "provider" in fields or "account_id" in fields:
await svc.controls._clear_saved_native(session_id)
+ if current.surface == "society" and svc.is_running(session_id):
+ raise HTTPException(status_code=409, detail="Agent chat is working")
session = svc.store.update_session(session_id, **fields)
assert session is not None
- changed = {k: v for k, v in fields.items() if k != "vendor_session"}
+ if current.surface == "society" and body.permission_mode is not None:
+ svc.store.set_permission_override(session_id, session.permission_mode)
+ if current.surface == "society":
+ binder = getattr(svc, "bind_society_session", None)
+ if binder is not None:
+ session = await binder(session_id)
+ if body.permission_mode is not None:
+ # Persist the effective choice, not a requested escalation that
+ # the roster narrowed during binding.
+ svc.store.set_permission_override(session_id, session.permission_mode)
+ changed = {key: getattr(session, key) for key in fields if key != "vendor_session"}
if changed:
await svc._emit(session_id, make_event("session_updated", changed)) # noqa: SLF001 — same package boundary
d = session.to_dict()
@@ -817,6 +841,8 @@ async def post_message(session_id: str, body: MessageBody, request: Request) ->
raise HTTPException(status_code=404, detail="session not found") from exc
except SessionBusy as exc:
raise HTTPException(status_code=409, detail="a turn is already running") from exc
+ except PermissionError as exc:
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
finally:
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx
index eca4fc4b5b..d21850f6af 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.test.tsx
@@ -179,6 +179,32 @@ describe("work trace", () => {
expect(splitConversationTurn([tool("a"), reply("done", "Ready."), failed]).after).toEqual([failed]);
});
+ it("keeps a failed tool and its outcome visible after a conversation completes", () => {
+ const failed = tool("err", { isError: true, output: "Upload failed" });
+ const { container } = render(<WorkTrace {...props} conversation blocks={[tool("a"), failed, reply("done", "I prepared a draft.")]} />);
+ expect(screen.getByText("Upload failed")).toBeTruthy();
+ expect(container.querySelector('[data-trace-tool="err"]')).toBeTruthy();
+ expect(screen.getByTestId("tool-failure-warning").textContent).toContain("A tool action failed");
+ expect(screen.getByRole("status").textContent).toContain("A tool action failed");
+ expect(screen.getAllByRole("status").at(-1)?.textContent).toContain("Done");
+ const fold = screen.getByTestId("conversation-work-fold").querySelector("button")!;
+ fireEvent.click(fold);
+ expect(screen.getAllByText("Upload failed").length).toBeGreaterThan(0);
+ });
+
+ it("keeps a failed question poll visible after a conversation completes", () => {
+ const failedPoll = tool("poll", {
+ name: "society_ask_user",
+ input: { wait_for: "closed-question" },
+ isError: true,
+ output: "The question is closed.",
+ });
+ const { container } = render(<WorkTrace {...props} conversation blocks={[tool("a"), failedPoll, reply("done", "I could not get an answer.")]} />);
+ expect(container.querySelector('[data-trace-tool="poll"]')).toBeTruthy();
+ expect(screen.getByText("The question is closed.")).toBeTruthy();
+ expect(screen.getByTestId("tool-failure-warning")).toBeTruthy();
+ });
+
it("treats a tool-only turn as work", () => {
expect(splitConversationTurn([tool("a")])).toEqual({ work: [tool("a")], answer: [], after: [] });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
index 991c3772c2..0f70eded0f 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
@@ -108,12 +108,14 @@ function isPendingApproval(block: TurnBlock): block is ToolBlock {
return (block.kind === "tool" && Boolean(block.approval && block.approval.decision === null)) || isOpenQuestion(block);
}
+function needsAttention(block: TurnBlock): block is ToolBlock {
+ return block.kind === "tool" && (block.isError || isPendingApproval(block));
+}
+
function hasFoldableWork(blocks: TurnBlock[]): boolean {
return blocks.some((block) => {
- // Only a pending approval keeps its row outside the fold — it asks the
- // person to act. Failures and interruptions fold like any other work:
- // the finished conversation shows the reply, the toggle reveals the rest.
- if (isPendingApproval(block)) return false;
+ // Decisions and failed tools remain visible after a turn completes.
+ if (needsAttention(block)) return false;
return block.kind !== "text" || Boolean(block.text.trim());
});
}
@@ -436,7 +438,7 @@ function TraceGroups({ groups, live, status, onDecide, renderText, conversation
* and draw nothing.
*/
function withoutQuestionPolls(blocks: TurnBlock[]): TurnBlock[] {
- const kept = blocks.filter((block) => !(block.kind === "tool" && isQuestionTool(block.name) && !block.question));
+ const kept = blocks.filter((block) => !(block.kind === "tool" && isQuestionTool(block.name) && !block.question && !block.isError));
return kept.length === blocks.length ? blocks : kept;
}
@@ -450,27 +452,26 @@ export function WorkTrace({ blocks: rawBlocks, status, startedMs, durationMs, er
const live = status === "running";
const elapsed = useClock(startedMs, live);
const split = useMemo(() => conversation && !live ? splitConversationTurn(blocks) : null, [blocks, conversation, live]);
- // A finished conversation turn shows the reply and nothing else. All work
- // — tools, thoughts, intermediate replies, failures, interruptions, and
- // post-reply work — folds behind the "Thought for …" toggle. Pending
- // approvals stay visible both ways: beside the toggle while it is closed
- // (they need a tap) and inside the open chain.
+ // Completed failures and pending approvals stay visible beside the fold.
+ // Other work can collapse without hiding an action that needs attention.
const fold = useMemo(() => {
if (!split) return null;
const workAll = [...split.work, ...split.after];
- if (!hasFoldableWork(workAll.filter((block) => !isPendingApproval(block)))) return null;
+ if (!hasFoldableWork(workAll)) return null;
return {
answer: split.answer,
workAll,
- approvals: workAll.filter(isPendingApproval),
+ attention: workAll.filter(needsAttention),
};
}, [split]);
const groups = useMemo(() => conversation ? groupConversationTrace(fold ? fold.workAll : blocks) : groupActivityTrace(blocks), [blocks, conversation, fold]);
const restGroups = useMemo(() => fold ? groupConversationTrace(fold.answer) : null, [fold]);
const asking = blocks.some(isOpenQuestion);
const pending = asking || blocks.some(block => block.kind === "tool" && block.approval?.decision === null);
- const outcome = asking ? "question" : pending ? "approval" : live ? "working" : status === "error" ? "failed" : status === "cancelled" ? "stopped" : "done";
- const Icon = asking ? MessageCircleQuestion : pending ? ShieldQuestion : live ? CircleDashed : status === "error" ? CircleAlert : Check;
+ const toolFailed = blocks.some(block => block.kind === "tool" && block.isError);
+ const failed = status === "error";
+ const outcome = asking ? "question" : pending ? "approval" : live ? "working" : failed ? "failed" : status === "cancelled" ? "stopped" : "done";
+ const Icon = asking ? MessageCircleQuestion : pending ? ShieldQuestion : live ? CircleDashed : failed ? CircleAlert : Check;
const groupProps = { live, status, onDecide, renderText, conversation };
// A turn-level error next to a reply folds with the work — it stays one
// tap away behind the toggle. With no reply the error IS the outcome, so
@@ -479,7 +480,7 @@ export function WorkTrace({ blocks: rawBlocks, status, startedMs, durationMs, er
const foldedError = fold && answered && error ? error : null;
const visibleError = error && !foldedError ? error : null;
return <div className={cn("min-w-0 space-y-0.5", conversation && "w-full max-w-xl self-start", className)} data-testid="work-trace" data-state={status} {...(conversation ? { "data-conversation": "" } : {})}>
- {fold ? <ConversationWorkFold durationMs={durationMs} attention={fold.approvals.map(block =>
+ {fold ? <ConversationWorkFold durationMs={durationMs} attention={fold.attention.map(block =>
<div key={block.callId} className="w-full py-1 text-xs [&_button]:text-xs">
<TraceTool block={block} status={status} onDecide={onDecide} />
</div>)}>
@@ -488,9 +489,13 @@ export function WorkTrace({ blocks: rawBlocks, status, startedMs, durationMs, er
</ConversationWorkFold> : <TraceGroups groups={groups} {...groupProps} />}
{restGroups ? <TraceGroups groups={restGroups} {...groupProps} /> : null}
{visibleError ? <p role="alert" className="py-2 text-sm text-destructive [overflow-wrap:anywhere]">{visibleError}</p> : null}
- <div role="status" aria-live="polite" className={cn("flex flex-wrap items-center gap-2 text-xs text-muted-foreground", conversation ? "px-1 pb-2 pt-1" : "border-t border-border pt-3", status === "error" && "text-destructive")}>
+ {toolFailed && !live && !failed ? <p data-testid="tool-failure-warning" className="flex items-center gap-1.5 px-1 py-1 text-xs text-destructive">
+ <CircleAlert aria-hidden className="h-3.5 w-3.5" />{t("work_trace.tool_failed")}
+ </p> : null}
+ <div role="status" aria-live="polite" className={cn("flex flex-wrap items-center gap-2 text-xs text-muted-foreground", conversation ? "px-1 pb-2 pt-1" : "border-t border-border pt-3", failed && "text-destructive")}>
<Icon aria-hidden className={cn("h-3.5 w-3.5", live && !pending && "motion-safe:animate-spin")} />
<span>{outcome === "done" && completionLabel ? completionLabel : t(`work_trace.${outcome}`)}</span>
+ {toolFailed && !live && !failed ? <span className="sr-only">{t("work_trace.tool_failed")}</span> : null}
{(live || durationMs !== null) ? <span aria-live="off" className="tabular-nums">{traceDuration(live ? elapsed : durationMs ?? 0)}</span> : null}
{receipt ? conversation ? <details className="ml-1"><summary className="cursor-pointer rounded-sm focus-visible:ring-2 focus-visible:ring-ring">{t("society.chat.activity_details")}</summary><div className="flex flex-wrap gap-2 py-1">{receipt}</div></details> : receipt : null}
</div>
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx
index de5bc5df47..206b5fb2c2 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx
@@ -14,11 +14,17 @@ import {
import { useAgentChatStore } from "@/store/agentChat";
import { useEventStore } from "@/store/events";
import type { AgentChatEvent, AgentChatSession } from "@/lib/agentChatApi";
+import type { ChatAttachment } from "@/lib/agentChatApi";
import { useHomeStore } from "@/store/home";
import { JarvisHistoryRail } from "./JarvisHistoryRail";
import { useRoutineNavigation } from "./routineNavigation";
import * as cardData from "../cardData";
+const attachmentState = vi.hoisted(() => ({
+ current: [] as ChatAttachment[],
+ clear: vi.fn(),
+}));
+
vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, fill: (text: string) => text }));
vi.mock("./AgentModelPicker", () => ({ AgentModelPicker: () => null }));
vi.mock("@/components/home/JarvisBar", () => ({ JarvisBar: () => <div data-testid="jarvis-bar" /> }));
@@ -36,11 +42,11 @@ vi.mock("@/components/agentchat/useComposerDictation", () => ({
vi.mock("@/components/agentchat/DictationButton", () => ({ DictationButton: () => null }));
vi.mock("@/components/agentchat/useChatAttachments", () => ({
useChatAttachments: () => ({
- attachments: [],
+ attachments: attachmentState.current,
analyzing: 0,
dragging: false,
dragHandlers: {},
- clear() {},
+ clear: attachmentState.clear,
remove() {},
attachFiles() {},
}),
@@ -109,6 +115,8 @@ const visual = agent({ agentId: "visual-qa", name: "Visual QA" });
const gmail = agent({ agentId: "gmail-agent", name: "Gmail Agent" });
beforeEach(() => {
+ attachmentState.current = [];
+ attachmentState.clear.mockClear();
useRoutineNavigation.getState().close();
seq = 0;
useTranscriptViewStore.setState({ boundaries: {} });
@@ -308,3 +316,55 @@ it("shows stop while the send request is in flight, before the turn stream start
expect(screen.getByTestId("composer-stop")).toBeTruthy();
expect(screen.queryByTestId("composer-send")).toBeNull();
});
+
+const screenshot: ChatAttachment = {
+ name: "screen.png", reference: "screen.png", kind: "image", detail: "A screenshot",
+ described_by: "vision", note: "",
+};
+
+it("sends an attachment without requiring text", async () => {
+ attachmentState.current = [screenshot];
+ const store = useSocietyChatStore;
+ store.getState().openSession(gmail.chatSessionId!);
+ vi.mocked(fetch).mockImplementation(async (url) =>
+ String(url).endsWith("/messages")
+ ? new Response(JSON.stringify({ turn_id: "sent" }), { status: 200 })
+ : new Response(JSON.stringify({ providers: [], sessions: [], mapping: [], events: [] }), { status: 200 }),
+ );
+ render(<AgentChatPanel agent={gmail} roster={[gmail]} />);
+ const send = screen.getByTestId("composer-send") as HTMLButtonElement;
+ expect(send.disabled).toBe(false);
+ fireEvent.click(send);
+ await waitFor(() => expect(attachmentState.clear).toHaveBeenCalledTimes(1));
+ const request = vi.mocked(fetch).mock.calls.find(([url]) => String(url).endsWith("/messages"));
+ expect(JSON.parse(String(request?.[1]?.body))).toMatchObject({ text: "", attachments: [screenshot] });
+});
+
+it("retains the exact draft and attachment when the message request fails", async () => {
+ attachmentState.current = [screenshot];
+ useSocietyChatStore.getState().openSession(gmail.chatSessionId!);
+ vi.mocked(fetch).mockImplementation(async (url) =>
+ String(url).endsWith("/messages")
+ ? new Response("failed", { status: 503 })
+ : new Response(JSON.stringify({ providers: [], sessions: [], mapping: [], events: [] }), { status: 200 }),
+ );
+ render(<AgentChatPanel agent={gmail} roster={[gmail]} />);
+ const field = screen.getByTestId("composer-chip-field");
+ field.textContent = " Please inspect this ";
+ fireEvent.input(field);
+ fireEvent.click(screen.getByTestId("composer-send"));
+ await waitFor(() => expect(useSocietyChatStore.getState().lastError).toBeTruthy());
+ await waitFor(() => expect(screen.getByTestId("composer-chip-field").textContent).toBe(" Please inspect this "));
+ expect(attachmentState.clear).not.toHaveBeenCalled();
+ expect(screen.getByText("screen.png")).toBeTruthy();
+});
+
+it("shows connecting and reconnecting states for a specialist session", () => {
+ useSocietyChatStore.getState().openSession(gmail.chatSessionId!);
+ render(<AgentChatPanel agent={gmail} roster={[gmail]} />);
+ expect(screen.getByText("society.chat.connecting")).toBeTruthy();
+ act(() => useSocietyChatStore.setState({ socketState: "closed" }));
+ expect(screen.getByText("society.chat.reconnecting")).toBeTruthy();
+ act(() => useSocietyChatStore.setState({ socketState: "open" }));
+ expect(screen.queryByText("society.chat.reconnecting")).toBeNull();
+});
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 1c9b78c024..7b543a7dc8 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -30,7 +30,7 @@ import { RoutineChatHost } from "./RoutineChatHost";
import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";
import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";
-import { AgentChatStoreProvider, useAgentChat } from "@/components/agentchat/AgentChatStoreContext";
+import { AgentChatStoreProvider, useAgentChat, useAgentChatApi } from "@/components/agentchat/AgentChatStoreContext";
import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
import { useStickToBottom } from "@/hooks/useStickToBottom";
@@ -190,6 +190,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {
const activeSessionId = useAgentChat((s) => s.activeSessionId);
const busy = useAgentChat((s) => s.busy);
const lastError = useAgentChat((s) => s.lastError);
+ const socketState = useAgentChat((s) => s.socketState);
const loadCatalog = useAgentChat((s) => s.loadCatalog);
const loadSessions = useAgentChat((s) => s.loadSessions);
const openSession = useAgentChat((s) => s.openSession);
@@ -267,6 +268,11 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {
data-session-ready={sessionReady ? "true" : "false"}
>
<Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />
+ {sessionReady && socketState !== "open" && socketState !== "idle" ? (
+ <p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
+ {t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
+ </p>
+ ) : null}
{lastError && sessionReady ? (
<p role="alert" className="px-4 pb-1 text-xs text-destructive">
{lastError}
@@ -304,6 +310,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {
const activeSessionId = useAgentChat((s) => s.activeSessionId);
const busy = useAgentChat((s) => s.busy);
const lastError = useAgentChat((s) => s.lastError);
+ const socketState = useAgentChat((s) => s.socketState);
const draft = useAgentChat((s) => s.draft);
const loadCatalog = useAgentChat((s) => s.loadCatalog);
const loadSessions = useAgentChat((s) => s.loadSessions);
@@ -402,6 +409,11 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {
<div className="flex h-full min-h-0 flex-col bg-background" data-testid="society-chat" data-mode="chat">
{header}
<Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />
+ {activeSessionId && socketState !== "open" && socketState !== "idle" ? (
+ <p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
+ {t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
+ </p>
+ ) : null}
{lastError ? (
<p role="alert" className="px-4 pb-1 text-xs text-destructive">
{lastError}
@@ -997,12 +1009,13 @@ interface ComposerProps {
provider: string;
/** Which chat surface the attachments belong to (the front page by default). */
surface?: AgentChatSurface;
- onSend: (text: string, attachments?: ReturnType<typeof useChatAttachments>["attachments"]) => Promise<void>;
+ onSend: (text: string, attachments?: ReturnType<typeof useChatAttachments>["attachments"]) => Promise<void | "sent" | "failed" | "stale">;
onCancel: () => Promise<void>;
}
export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onClear, onSend, onCancel }: ComposerProps) {
const t = useT();
+ const chatStore = useAgentChatApi();
const [modelSaving, setModelSaving] = useState(false);
const [value, setValue] = useState("");
const [plusOpen, setPlusOpen] = useState(false);
@@ -1015,6 +1028,8 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
const composerRef = useRef<HTMLDivElement>(null);
const fileInput = useRef<HTMLInputElement>(null);
const attachments = useChatAttachments({ sessionId, cwd, provider, surface }, (message) => setProblem(message));
+ const attachmentsRef = useRef(attachments.attachments);
+ attachmentsRef.current = attachments.attachments;
const commands = useChatCommands({ value, agentId: agent.agentId, onClear,
attachments: attachments.attachments, attachmentsBusy: attachments.analyzing > 0, onAttachmentsSent: attachments.clear,
setValue: (next) => { setValue(next); fieldRef.current?.setText(next); },
@@ -1097,12 +1112,14 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
const submit = async () => {
const draft = fieldRef.current?.getDraft();
- const draftText = (draft?.text ?? value).trim();
+ const fullDraft = draft?.text ?? value;
+ const draftText = fullDraft.trim();
const submittedFolder = codingFolder;
const selected = selectedTools;
+ const sentAttachments = attachments.attachments;
const text = draftText;
if (await commands.execute(text)) return;
- if (!text || (busy || live) && !commands.canSteer || modelSaving) return;
+ if ((!text && attachments.attachments.length === 0) || (busy || live) && !commands.canSteer || modelSaving || attachments.analyzing > 0) return;
const chosenIds = new Set((draft?.choices ?? []).map((row) => row.id));
const chosen = [...chosenIds].map((id) => catalog.find((item) => item.key === id));
if (chosen.some((item) => !item || !item.connected)) {
@@ -1134,19 +1151,26 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
const codingHint = codingAssignmentHint(codingSelections, codingFolder);
if (codingHint) lines.push(codingHint);
const hint = lines.join("\n");
- setValue("");
- fieldRef.current?.clear();
- setMention(null);
setProblem(null);
try {
- await onSend(hint ? `${text}\n\n${hint}` : text, attachments.attachments);
- setSelectedTools([]);
- attachments.clear();
+ const result = await onSend(hint ? `${text}\n\n${hint}` : text, sentAttachments);
+ if (result === "stale" || sessionId && chatStore.getState().activeSessionId !== sessionId) return;
+ const sendError = chatStore.getState().lastError;
+ if (result === "failed" || result === undefined && sendError) throw new Error(sendError ?? t("common.error_generic"));
+ if ((fieldRef.current?.getDraft().text ?? value) === fullDraft) {
+ setValue("");
+ fieldRef.current?.clear();
+ setMention(null);
+ setSelectedTools([]);
+ }
+ if (attachmentsRef.current === sentAttachments) attachments.clear();
+ else sentAttachments.forEach((file) => attachments.remove(file.name));
} catch (err) {
- setValue(draftText);
- fieldRef.current?.hydrate(draftText, draft?.choices ?? []);
- setSelectedTools(selected);
- setCodingFolder(submittedFolder);
+ // The input and files stay in place until the server accepts them.
+ if ((fieldRef.current?.getDraft().text ?? value) === fullDraft) {
+ setSelectedTools(selected);
+ setCodingFolder(submittedFolder);
+ }
setProblem(err instanceof Error ? err.message : String(err));
}
};
@@ -1315,7 +1339,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
<button
type="button"
onClick={() => void submit()}
- disabled={modelSaving || (!value.trim() && selectedTools.length === 0)}
+ disabled={modelSaving || attachments.analyzing > 0 || (!value.trim() && selectedTools.length === 0 && attachments.attachments.length === 0)}
aria-label={t("society.chat.send")}
data-testid="composer-send"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground disabled:opacity-40"
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx
index 24d8659168..4ef2890c8e 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx
@@ -73,14 +73,14 @@ it("keeps live and interrupted conversation tools in the left lane", () => {
expect(screen.getByTestId("work-trace").className).toMatch(/self-start/);
});
-it("folds a failure with the surrounding work, keeping only the reply out", () => {
+it("keeps a failed tool visible while folding the surrounding work", () => {
const tool: ToolBlock = { kind: "tool", callId: "a", name: "read_file", input: { path: "report.csv" }, output: "Report contents", isError: false, durationMs: 100, approval: null, startedMs: 0 };
render(<WorkTrace conversation status="done" startedMs={0} durationMs={2000} blocks={[
tool,
{ ...tool, callId: "error", isError: true, output: "Upload failed" },
{ kind: "text", id: "reply", text: "I could not finish." },
]} />);
- expect(screen.queryByText("Upload failed")).toBeNull();
+ expect(screen.getByText("Upload failed")).toBeTruthy();
expect(screen.getByText("I could not finish.")).toBeTruthy();
expect(screen.queryByText("Report contents")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Thought for 2.0s" }));
@@ -89,18 +89,17 @@ it("folds a failure with the surrounding work, keeping only the reply out", () =
expect(screen.getByText("Report contents")).toBeTruthy();
});
-it("folds failures but keeps pending approvals visible in the conversation style", () => {
+it("keeps failures and pending approvals visible in the conversation style", () => {
const base: ToolBlock = { kind: "tool", callId: "failure", name: "send_message", input: {}, output: "Delivery failed", isError: true, durationMs: 100, approval: null, startedMs: 0 };
render(<WorkTrace conversation status="done" startedMs={0} durationMs={1000} blocks={[
base,
{ ...base, callId: "approval", isError: false, output: null, approval: { approvalId: "ap", summary: "Send this message?", decision: null } },
]} onDecide={() => undefined} />);
- expect(screen.queryByText("Delivery failed")).toBeNull();
+ expect(screen.getByText("Delivery failed")).toBeTruthy();
expect(screen.getByText("Send this message?")).toBeTruthy();
expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "Thought for 1.0s" }));
- expect(screen.getAllByText("Delivery failed").length).toBeGreaterThan(0);
- // The approval card survives opening the fold — it still needs a tap.
+ // With no other work to fold, both items stay in place and need no toggle.
+ expect(screen.queryByTestId("conversation-work-fold")).toBeNull();
expect(screen.getByRole("button", { name: "Approve" })).toBeTruthy();
});
@@ -116,7 +115,7 @@ it("shows agent message direction and truthful delivery state without preview cl
expect(screen.getByRole("alert").textContent).toBe("Connection closed");
});
-it("folds successful work and post-reply errors behind one toggle without reordering the conversation", () => {
+it("folds successful work while showing post-reply errors without reordering the conversation", () => {
const tool: ToolBlock = { kind: "tool", callId: "a", name: "read_file", input: { path: "report.csv" }, output: "Report contents", isError: false, durationMs: 100, approval: null, startedMs: 0 };
const blocks = [tool, { ...tool, callId: "b", name: "write_file" }, { kind: "text" as const, id: "reply", text: "Your report is ready." }, { ...tool, callId: "error", isError: true, output: "Upload failed" }];
const { rerender } = render(<WorkTrace conversation status="running" startedMs={0} durationMs={null} blocks={blocks} />);
@@ -128,7 +127,7 @@ it("folds successful work and post-reply errors behind one toggle without reorde
expect(screen.queryByRole("button", { name: "Reading files Creating files" })).toBeNull();
expect(screen.queryByRole("button", { name: /Write file/ })).toBeNull();
expect(screen.getByText("Your report is ready.")).toBeTruthy();
- expect(screen.queryByText("Upload failed")).toBeNull();
+ expect(screen.getByText("Upload failed")).toBeTruthy();
expect(screen.queryByText("Report contents")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Thought for 1.0s" }));
// One tap opens the whole chain: the post-reply error and the tool details.
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 12aa0cc844..6497eb5861 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5691,6 +5691,7 @@
"unanswered": "Nicht beantwortet – der Durchlauf wurde beendet."
},
"work_trace": {
+ "tool_failed": "Eine Tool-Aktion ist fehlgeschlagen",
"question": "Wartet auf deine Antwort",
"integration_used": "{service} verwendet",
"activity_command": "Befehle ausgeführt",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 3b9e8b5b71..b0a98a9f04 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5724,6 +5724,7 @@
"unanswered": "Not answered — the turn ended."
},
"work_trace": {
+ "tool_failed": "A tool action failed",
"question": "Waiting for your answer",
"integration_used": "Used {service}",
"activity_command": "Ran commands",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 4f9bde542b..764ad6521f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5691,6 +5691,7 @@
"unanswered": "Sin responder: el turno terminó."
},
"work_trace": {
+ "tool_failed": "Falló una acción de herramienta",
"question": "Esperando tu respuesta",
"integration_used": "Usó {service}",
"activity_command": "Ejecutó comandos",
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 67f0f01d5e..d7a150accb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -82,6 +82,8 @@
"legacy": "Ältere Ausführung: Ergebnis vorhanden; Abschlussstatus wurde nicht aufgezeichnet."
},
"chat": {
+ "connecting": "Verbindung zu diesem Chat wird hergestellt…",
+ "reconnecting": "Verbindung zu diesem Chat wird wiederhergestellt…",
"memory_updated": "Memory aktualisiert",
"memory_changes": "Änderungen",
"memory_current": "Aktuelle Datei",
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 43651cd3e4..3b7c5bcd20 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -82,6 +82,8 @@
"legacy": "Older execution: result available; final status was not recorded."
},
"chat": {
+ "connecting": "Connecting to this chat…",
+ "reconnecting": "Reconnecting to this chat…",
"memory_updated": "Memory updated",
"memory_changes": "Changes",
"memory_current": "Current file",
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 e5469718dc..76e8fc1f76 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -82,6 +82,8 @@
"legacy": "Ejecución anterior: resultado disponible; no se registró el estado final."
},
"chat": {
+ "connecting": "Conectando con este chat…",
+ "reconnecting": "Reconectando con este chat…",
"memory_updated": "Memoria actualizada",
"memory_changes": "Cambios",
"memory_current": "Archivo actual",
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
index 54c27a3114..6fd94e0680 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -71,6 +71,37 @@ class FakeSocket {
describe("agent-chat store surfaces", () => {
+ it("reconciles a Society permission draft from a clamped PATCH response", async () => {
+ const active = { ...session("society:reader", "society"), permission_mode: "plan" };
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(active), { status: 200 })));
+ const store = createAgentChatStore("society", "reader");
+ store.setState({ activeSessionId: active.session_id, activeSession: active });
+
+ await store.getState().setDraft({ permissionMode: "bypass" });
+
+ expect(store.getState().activeSession?.permission_mode).toBe("plan");
+ expect(store.getState().draft.permissionMode).toBe("plan");
+ });
+
+ it("keeps the latest Society draft while session PATCHes complete in order", async () => {
+ const active = { ...session("society:reader", "society"), permission_mode: "plan" };
+ const pending: Array<(response: Response) => void> = [];
+ vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => pending.push(resolve))));
+ const store = createAgentChatStore("society", "reader-serial");
+ store.setState({ activeSessionId: active.session_id, activeSession: active });
+
+ const first = store.getState().setDraft({ permissionMode: "ask" });
+ const second = store.getState().setDraft({ permissionMode: "bypass" });
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ pending[0](new Response(JSON.stringify({ ...active, permission_mode: "ask" })));
+ await first;
+ expect(store.getState().draft.permissionMode).toBe("bypass");
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ pending[1](new Response(JSON.stringify({ ...active, permission_mode: "plan" })));
+ await second;
+ expect(store.getState().draft.permissionMode).toBe("plan");
+ });
+
it("snaps a stored mode the row's ladder does not know onto the row's default", async () => {
// The v1 draft was shared with the IDE and could carry a vendor word
// ("skip-permissions"); on the Jarvis ladder that must become "ask", not
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 7057290ef8..e3d8aa70a1 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -156,7 +156,7 @@ export interface AgentChatStore {
openSession: (sessionId: string) => void;
removeSession: (sessionId: string) => Promise<void>;
/** Send the sentence, with whatever files the composer is holding for it. */
- send: (text: string, attachments?: ChatAttachment[], toolChoices?: string[]) => Promise<void>;
+ send: (text: string, attachments?: ChatAttachment[], toolChoices?: string[]) => Promise<void | "sent" | "failed" | "stale">;
cancel: () => Promise<void>;
decide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
/** Answer question `index` of an agent's card in the active session; throws so the card can say why. */
@@ -279,6 +279,8 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
const DRAFT_KEY = draftKey(surface) + (draftNamespace ? `:${draftNamespace}` : "");
let catalogRequest = 0;
+ const patchQueues = new Map<string, Promise<void>>();
+ const patchRevisions = new Map<string, number>();
let socket: WebSocket | null = null;
let socketSession: string | null = null;
/** Cancels the reconnect waiting in the shared connect budget. */
@@ -576,14 +578,36 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
body.permission_mode = draft.permissionMode;
}
if (patch.cwd !== undefined) body.cwd = draft.cwd;
+ const revision = (patchRevisions.get(sid) ?? 0) + 1;
+ patchRevisions.set(sid, revision);
+ const previous = patchQueues.get(sid) ?? Promise.resolve();
+ const pending = previous.then(() => patchAgentChatSession(sid, body));
+ patchQueues.set(sid, pending.then(() => undefined, () => undefined));
try {
- const session = await patchAgentChatSession(sid, body);
- set((s) => ({
- activeSession: s.activeSessionId === sid ? session : s.activeSession,
- sessions: s.sessions.map((x) => (x.session_id === sid ? { ...x, ...session } : x)),
- }));
+ const session = await pending;
+ let reconciledDraft: ComposerDraft | null = null;
+ set((s) => {
+ const latest = patchRevisions.get(sid) === revision;
+ const active = s.activeSessionId === sid && latest;
+ if (active) reconciledDraft = draftFromSession(session, s.draft);
+ return {
+ activeSession: active ? session : s.activeSession,
+ draft: reconciledDraft ?? s.draft,
+ sessions: latest
+ ? s.sessions.map((x) => (x.session_id === sid ? { ...x, ...session } : x))
+ : s.sessions,
+ };
+ });
+ if (reconciledDraft) writeDraft(DRAFT_KEY, reconciledDraft);
} catch (err) {
- set({ lastError: errorText(err) });
+ if (get().activeSessionId === sid && patchRevisions.get(sid) === revision) {
+ set({ lastError: errorText(err) });
+ }
+ } finally {
+ if (patchRevisions.get(sid) === revision) {
+ patchQueues.delete(sid);
+ patchRevisions.delete(sid);
+ }
}
}
},
@@ -637,6 +661,8 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
set({ lastError: errorText(err) });
}
timelineCache.delete(sessionId);
+ patchQueues.delete(sessionId);
+ patchRevisions.delete(sessionId);
if (get().activeSessionId === sessionId) get().newChat();
set((s) => ({ sessions: s.sessions.filter((x) => x.session_id !== sessionId) }));
void get().loadSessions();
@@ -646,7 +672,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
const content = text.trim();
// A message may be files alone — dropping a screenshot and pressing
// Enter is a complete gesture — but never nothing at all.
- if (!content && attachments.length === 0) return;
+ if (!content && attachments.length === 0) return "failed";
const st = get();
set({ busy: true, lastError: null });
let sid = st.activeSessionId;
@@ -672,8 +698,10 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
}
await sendAgentChatMessage(sid, content, attachments, toolChoices);
if (get().activeSessionId === sid) void get().loadSessions();
+ return get().activeSessionId === sid ? "sent" : "stale";
} catch (err) {
if (get().activeSessionId === sid) set({ lastError: errorText(err) });
+ return get().activeSessionId === sid ? "failed" : "stale";
} finally {
// A switch away from this session already cleared `busy`; do not
// unlock (or error) the chat that is on screen now.
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 14d89c9d45..1e67bb24b6 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -71,6 +71,40 @@ def _typed_error(exc: RosterError | RoomError) -> HTTPException:
)
+def _validated_chat_runner(
+ rt: SocietyRuntime,
+ agent: AgentRecord,
+ provider: str,
+ *,
+ approval_mode: str | None = None,
+ permission_ceiling: str | None = None,
+) -> str:
+ """Reject a runner change that cannot honor the effective chat approval."""
+ from jarvis.agent_chat.permissions import normalize_permission, society_mode_supported
+ from jarvis.agent_chat.service import resolve_runner
+
+ runner = resolve_runner(provider, surface="society")
+ mode = approval_mode if approval_mode is not None else (
+ str(agent.approval_mode) if agent.approval_mode is not None else ""
+ )
+ if mode and not society_mode_supported(runner, mode):
+ raise HTTPException(422, "This runner cannot provide an actionable approval for that mode.")
+ ceiling = str(
+ permission_ceiling if permission_ceiling is not None else agent.permission_ceiling
+ )
+ if not mode and ceiling != "safe" and not society_mode_supported(runner, "ask"):
+ raise HTTPException(
+ 422, "This runner cannot provide an actionable approval for this legacy agent."
+ )
+ chat = rt.chat_service()
+ if chat is not None and chat.store.get_session(agent.session_id) is not None:
+ override = chat.store.permission_override(agent.session_id)
+ if override and override not in ("plan", "read-only"):
+ if not society_mode_supported(runner, normalize_permission("society", override)):
+ raise HTTPException(422, "This runner cannot honor the chat's approval choice.")
+ return runner
+
+
# ------------------------------------------------------------------- models
@@ -327,18 +361,14 @@ async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) ->
if has_brief(brief):
# A brief rewrites the standing instructions as a whole.
fields["description"] = compose_description(body.description or "", brief)
- requested_mode = body.approval_mode or (
- str(agent.approval_mode) if body.provider and agent.approval_mode else ""
- )
- if requested_mode:
- from jarvis.agent_chat.permissions import society_mode_supported
- from jarvis.agent_chat.service import resolve_runner
-
- provider = body.provider or agent.provider
- if not society_mode_supported(resolve_runner(provider, surface="society"), requested_mode):
- raise HTTPException(
- 422, "This runner cannot provide an actionable approval for that mode."
- )
+ if any(key in fields for key in ("provider", "approval_mode", "permission_ceiling")):
+ _validated_chat_runner(
+ rt,
+ agent,
+ body.provider or agent.provider,
+ approval_mode=body.approval_mode,
+ permission_ceiling=fields.get("permission_ceiling"),
+ )
if ("title" in fields or "description" in fields) and "focus" not in fields:
# A prose edit must not wipe what the agent earned in its chat: the
# derived focus is APPENDED to the existing order (existing first,
@@ -362,8 +392,17 @@ async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) ->
raise _typed_error(exc) from exc
if "approval_mode" in fields:
svc = rt.chat_service()
- if svc is not None and svc.store.get_session(updated.session_id) is not None:
- svc.store.update_session(updated.session_id, permission_mode=str(updated.approval_mode))
+ if (
+ svc is not None
+ and svc.store.get_session(updated.session_id) is not None
+ and not svc.is_running(updated.session_id)
+ ):
+ from jarvis.society.chat_binding import ensure_session
+
+ # An active turn keeps its pinned seat. An idle one rebinds through
+ # the roster plus any narrower chat override instead of replacing
+ # that override with the card's new default.
+ ensure_session(svc, rt.config(), updated)
if "state" in fields:
await rt.checkpoints.refresh(agent.agent_id)
updated = await rt.roster.get(agent.agent_id) or updated
@@ -716,8 +755,6 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -
"""Move the agent onto another provider / model / effort / subscription seat.
Its canonical chat is re-seated at once (transcript kept)."""
from jarvis.agent_chat.catalog import offers
- from jarvis.agent_chat.permissions import society_mode_supported
- from jarvis.agent_chat.service import resolve_runner
rt = await _runtime(request)
agent = await rt.roster.resolve(agent_id)
@@ -728,17 +765,14 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -
422,
{"reason": str(FailureReason.BLOCKED_BY_POLICY), "detail": "provider not offered"},
)
- if agent.approval_mode and not society_mode_supported(
- resolve_runner(body.provider, surface="society"), str(agent.approval_mode)
- ):
- raise HTTPException(422, "This runner cannot provide an actionable approval for that mode.")
+ target_runner = _validated_chat_runner(rt, agent, body.provider)
+ chat = rt._get_chat()
fields = {
"provider": body.provider.strip().lower(),
"model": body.model.strip(),
"effort": body.effort.strip(),
"account_id": body.account_id.strip(),
}
- chat = rt._get_chat()
if chat is not None and hasattr(chat, "controls") and chat.store.get_session(agent.session_id):
await chat.controls.pause(agent.session_id, "Model settings changed")
await chat.controls._clear_saved_native(agent.session_id)
@@ -758,7 +792,7 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -
log.info("society: %s re-seat deferred: %s", agent.agent_id, exc)
return {
"agent": _agent_row(updated, request),
- "runner": resolve_runner(updated.provider, surface="society"),
+ "runner": target_runner,
"reseated": reseated,
}
diff --git a/tests/contract/test_mars_ordinary.py b/tests/contract/test_mars_ordinary.py
index 0dba096674..5c0efce83a 100644
--- a/tests/contract/test_mars_ordinary.py
+++ b/tests/contract/test_mars_ordinary.py
@@ -26,6 +26,7 @@ class ControlledChat(AgentChatService):
self.sent: list[dict] = []
self.cancel_calls: list[tuple[str, str | None]] = []
self.cancel_status: str | None = "cancelled"
+ self.cancel_text = "Turn completed."
async def send(self, session_id, text, **kwargs):
self.sent.append({"session_id": session_id, "text": text, **kwargs})
@@ -35,6 +36,14 @@ class ControlledChat(AgentChatService):
"""Controlled terminal race; no real runner/provider or wall-clock sleep."""
self.cancel_calls.append((session_id, expected_turn_id))
if self.cancel_status is not None:
+ if self.cancel_status == "done" and self.cancel_text:
+ await self._emit(
+ session_id,
+ {
+ "kind": "assistant_text",
+ "payload": {"turn_id": expected_turn_id, "text": self.cancel_text},
+ },
+ )
await self._emit(
session_id,
{
@@ -166,6 +175,19 @@ async def test_cancel_rechecks_exact_durable_terminal_after_grace_period(
assert len(service.cancel_calls) == 1
+async def test_empty_done_terminal_stays_failed_on_cancel_replay(ordinary):
+ _, service, adapter = ordinary
+ args = {"agent_id": "comms", "command_id": "empty-done", "trace_id": "mars:empty-done"}
+ active = await adapter.dispatch(**args, draft="Draft a meeting invitation.")
+ service.cancel_status = "done"
+ service.cancel_text = " "
+ outcome = await adapter.cancel(**args, task_ref=active["task_ref"])
+ assert outcome["state"] == "failed" and outcome["cancel_attempt"] == "attempted"
+ replay = await adapter.cancel(**args, task_ref=active["task_ref"])
+ assert replay["state"] == "failed" and replay["cancel_attempt"] == "not_attempted"
+ assert len(service.cancel_calls) == 1
+
+
async def test_true_stop_receipt_without_terminal_cannot_manufacture_canceled(ordinary):
_, service, adapter = ordinary
args = {"agent_id": "comms", "command_id": "no-terminal", "trace_id": "mars:no-terminal"}
diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.py
index 73e0c8c4b9..303bec1fe3 100644
--- a/tests/unit/agent_chat/test_agent_chat_ladders.py
+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py
@@ -327,6 +327,21 @@ def test_agy_model_args_respects_the_strict_pairing():
assert agy_model_args("gemini-9.9-flash", "low")[-1] == "low"
+def test_agy_new_gemini_base_model_keeps_required_effort_with_stale_catalog():
+ stale = agy_model_catalog(None)
+ assert agy_model_args("gemini-3.8-flash", "medium", stale) == [
+ "--model",
+ "gemini-3.8-flash",
+ "--effort",
+ "medium",
+ ]
+ assert agy_model_args("gemini-3.8-flash", "", stale)[-2:] == ["--effort", "high"]
+ assert agy_model_args("gemini-3.8-flash-low", "high", stale) == [
+ "--model",
+ "gemini-3.8-flash-low",
+ ]
+
+
def test_agy_model_catalog_folds_suffixed_ids():
raw = [
{"id": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)"},
diff --git a/tests/unit/agent_chat/test_approval_bridge.py b/tests/unit/agent_chat/test_approval_bridge.py
index 4c58d08bab..c4265237cd 100644
--- a/tests/unit/agent_chat/test_approval_bridge.py
+++ b/tests/unit/agent_chat/test_approval_bridge.py
@@ -204,6 +204,26 @@ async def test_bypass_still_cards_an_explicit_require_approval_rule(tmp_path: Pa
assert len(card.asked) == 1
+async def test_require_approval_overrides_remembered_grants_in_every_stance(tmp_path: Path):
+ """An agent's explicit rule still asks after an earlier Always allow."""
+ for stance in ("ask", "bypass"):
+ executor, bridge, _ = _stack()
+ card = _Card("deny")
+ grant = _grant(card, stance, {"RunCommand"})
+ grant.pre_approved.add("RunCommand")
+ grant.force_ask = lambda _name, _args: True
+ bridge.arm(REF, grant)
+
+ run = ft.folder_tools(tmp_path)["RunCommand"]
+ result = await executor.execute(
+ run, {"command": "echo hi"}, config_snapshot=_snapshot()
+ )
+
+ assert not result.success and result.error, stance
+ assert result.error.startswith(APPROVAL_DENIED_PREFIX), stance
+ assert [asked[1] for asked in card.asked] == ["RunCommand"], stance
+
+
async def test_always_ask_cards_even_a_remembered_tool(tmp_path: Path):
executor, bridge, _ = _stack()
card = _Card("deny")
diff --git a/tests/unit/agent_chat/test_controls.py b/tests/unit/agent_chat/test_controls.py
index 58f0b87bc2..099dc57d71 100644
--- a/tests/unit/agent_chat/test_controls.py
+++ b/tests/unit/agent_chat/test_controls.py
@@ -34,6 +34,10 @@ class FakeService:
def is_running(self, sid: str) -> bool:
return sid in self.running
+ async def bind_society_session(self, sid: str):
+ # This unit fake has no roster; return its current stored seat.
+ return self.store.get_session(sid)
+
async def send(self, sid: str, text: str, **kwargs: Any) -> str:
assert sid not in self.running
self.sent.append((text, kwargs))
@@ -99,11 +103,13 @@ def test_plan_build_and_review_preserve_original_permissions_and_history() -> No
await controls.turn_completed(sid, "1", "Investigate first", True, False)
assert controls.state(sid).plan == "Actual work product"
assert controls.state(sid).previous_permission == "ask"
+ assert svc.store.permission_override(sid) == "plan"
result = await controls.execute(sid, request("message", "@Friend Hello", "r2"))
assert result.status == "failed" and "Plan mode" in result.error
await controls.execute(sid, request("build", rid="r3"))
await svc.wait_turn(sid)
assert svc.store.get_session(sid).permission_mode == "ask"
+ assert svc.store.permission_override(sid) == "ask"
await controls.execute(sid, request("review", rid="r4"))
await svc.wait_turn(sid)
assert svc.sent[-1][1]["read_only"] is True
@@ -324,9 +330,17 @@ def test_message_uses_executor_exact_text_sender_and_idempotency(monkeypatch: An
turn_completed=completed,
browser=SimpleNamespace(live=SimpleNamespace(sessions={})),
)
+ from jarvis.society import surface as society_surface
+
monkeypatch.setattr("jarvis.society.runtime.current_runtime", lambda: runtime)
+ monkeypatch.setattr(society_surface, "current_runtime", lambda: runtime)
monkeypatch.setattr("jarvis.society.agent_tools.MessageAgentTool", MessageTool)
svc = AgentChatService(AgentChatStore(), bus=lambda: bus)
+
+ async def isolated_session(sid: str, **_kwargs):
+ return svc.store.get_session(sid)
+
+ monkeypatch.setattr(svc, "bind_society_session", isolated_session)
sid = svc.store.create_session(
provider="openai",
model="",
diff --git a/tests/unit/society/test_browser.py b/tests/unit/society/test_browser.py
index ff38625700..fd0e65a4a8 100644
--- a/tests/unit/society/test_browser.py
+++ b/tests/unit/society/test_browser.py
@@ -211,6 +211,22 @@ async def test_tool_gates(rt, tmp_path, fake_runner):
assert (await tool.execute({"task": "read"}, CTX)).output["reason"] == "kill_switch"
+async def test_browser_does_not_queue_after_tool_executor_approval(
+ rt, tmp_path, fake_runner, monkeypatch
+):
+ """The fake browser job runs after the chat approved the same tool call."""
+ monkeypatch.setattr(
+ "jarvis.society.browser.tool.llm_spec_for",
+ lambda provider, model="", **kw: llm_spec_for(provider, model, secret=lambda p: "k"),
+ )
+ await rt.roster.update("scout", {"approval_mode": "ask"})
+ tool = BrowserTool(rt, "scout", _jobs(tmp_path, fake_runner))
+ approved_ctx = SimpleNamespace(**vars(CTX), approved_by="user")
+ result = await tool.execute({"task": "read the headlines"}, approved_ctx)
+ assert result.success, result.error
+ assert await rt.approvals.pending() == []
+
+
async def test_briefing_and_surface_reflect_the_browser(rt, tmp_path, fake_runner):
from jarvis.society.surface import society_system_extra, society_tools
diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.py
index 25da99fdb7..848dd03037 100644
--- a/tests/unit/society/test_chat_binding.py
+++ b/tests/unit/society/test_chat_binding.py
@@ -26,10 +26,25 @@ class FakeService:
async def _emit(self, session_id, event):
self.store.append_event(session_id, event)
+ async def post_notice(self, session_id, payload):
+ from jarvis.agent_chat.events import make_event
+
+ await self._emit(session_id, make_event("notice", payload))
+
+ async def cancel(self, _session_id, *, expected_turn_id=None):
+ self.cancelled_turns.append(expected_turn_id)
+ return False
+
+ async def bind_society_session(self, session_id):
+ from jarvis.society.chat_binding import bind_society_session
+
+ return await bind_society_session(self, session_id)
+
def __init__(self, store: AgentChatStore) -> None:
self.store = store
self.sent: list[tuple[str, str]] = []
self.busy: set[str] = set()
+ self.cancelled_turns: list[str | None] = []
def is_running(self, session_id: str) -> bool:
return session_id in self.busy
@@ -41,16 +56,22 @@ class FakeService:
@pytest.fixture
async def world(tmp_path: Path):
- runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False, cfg=lambda: cfg)
await runtime.ensure_started()
svc = FakeService(AgentChatStore(tmp_path / "agent_chat.db"))
- cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
try:
yield runtime, svc, cfg
finally:
await runtime.close()
+async def _legacy_agent(rt: SocietyRuntime, agent):
+ """Model a saved pre-approval-mode roster row in both stores."""
+ await rt.store.update_agent(agent.agent_id, {"approval_mode": None})
+ return dataclasses.replace(agent, approval_mode=None)
+
+
def test_society_is_a_surface():
assert "society" in SURFACES
@@ -89,6 +110,356 @@ async def test_legacy_ceiling_maps_to_stance(world):
assert ensure_session(svc, cfg, ask).permission_mode == "ask"
+async def test_existing_session_follows_roster_permissions_name_and_workspace(world):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ agent = await _legacy_agent(rt, agent)
+ first = ensure_session(svc, cfg, agent)
+ updated = await rt.roster.update(
+ agent.agent_id,
+ {
+ "name": "Research Scout",
+ "permission_ceiling": "safe",
+ "workspace_dir": "society/scout/research",
+ },
+ )
+
+ session = ensure_session(svc, cfg, updated)
+ assert session.session_id == first.session_id
+ assert session.permission_mode == "plan"
+ assert session.title == "Research Scout"
+ assert Path(session.cwd).name == "research"
+ assert len(svc.store.list_sessions(surface="society")) == 1
+
+
+async def test_rebinding_preserves_a_more_restrictive_user_stance(world):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ agent = await _legacy_agent(rt, agent)
+ first = ensure_session(svc, cfg, agent)
+ assert first.permission_mode == "ask"
+
+ svc.store.update_session(first.session_id, permission_mode="plan")
+ svc.store.set_permission_override(first.session_id, "plan")
+ assert ensure_session(svc, cfg, agent).permission_mode == "plan"
+
+ svc.store.update_session(first.session_id, permission_mode="ask")
+ svc.store.set_permission_override(first.session_id, "ask")
+ assert ensure_session(svc, cfg, agent).permission_mode == "ask"
+
+
+async def test_relaxed_roster_ceiling_restores_default_without_user_override(world):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Reader", provider="openai", permission_ceiling="safe")
+ agent = await _legacy_agent(rt, agent)
+ first = ensure_session(svc, cfg, agent)
+ assert first.permission_mode == "plan"
+
+ updated = await rt.roster.update(agent.agent_id, {"permission_ceiling": "monitor"})
+ assert ensure_session(svc, cfg, updated).permission_mode == "accept-edits"
+
+ svc.store.set_permission_override(first.session_id, "plan")
+ assert ensure_session(svc, cfg, updated).permission_mode == "plan"
+
+
+async def test_chat_route_records_an_explicit_permission_choice(world):
+ from jarvis.ui.web.agent_chat_routes import router
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ svc.controls = SimpleNamespace(state=lambda _sid: SimpleNamespace(goal=None))
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = svc
+
+ with TestClient(app) as client:
+ response = client.patch(
+ f"/api/agent-chat/sessions/{session.session_id}",
+ json={"permission_mode": "ask"},
+ )
+ stale_model = client.patch(
+ f"/api/agent-chat/sessions/{session.session_id}",
+ json={"model": "not-the-roster-model"},
+ )
+ assert response.status_code == 200
+ assert svc.store.permission_override(session.session_id) == "ask"
+ assert ensure_session(svc, cfg, agent).permission_mode == "ask"
+ assert stale_model.status_code == 200
+ assert stale_model.json()["model"] == agent.model
+ updates = [
+ event["payload"]
+ for event in svc.store.list_events(session.session_id)
+ if event["kind"] == "session_updated"
+ ]
+ assert {"model": agent.model} in updates
+
+
+async def test_safe_agent_route_clamps_a_requested_bypass(world):
+ from jarvis.ui.web.agent_chat_routes import router
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Reader", provider="openai", permission_ceiling="safe")
+ agent = await _legacy_agent(rt, agent)
+ session = ensure_session(svc, cfg, agent)
+ svc.controls = SimpleNamespace(state=lambda _sid: SimpleNamespace(goal=None))
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = svc
+
+ with TestClient(app) as client:
+ response = client.patch(
+ f"/api/agent-chat/sessions/{session.session_id}",
+ json={"permission_mode": "bypass"},
+ )
+ assert response.status_code == 200
+ assert response.json()["permission_mode"] == "plan"
+ assert svc.store.get_session(session.session_id).permission_mode == "plan"
+ assert svc.store.permission_override(session.session_id) == "plan"
+ assert any(
+ event["kind"] == "session_updated" and event["payload"].get("permission_mode") == "plan"
+ for event in svc.store.list_events(session.session_id)
+ )
+
+
+async def test_society_route_rejects_an_unsupported_ask_before_storage(world, monkeypatch):
+ from jarvis.ui.web import agent_chat_routes
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ monkeypatch.setattr(agent_chat_routes, "resolve_runner", lambda *_args, **_kw: "grok-cli")
+ app = FastAPI()
+ app.include_router(agent_chat_routes.router)
+ app.state.agent_chat = svc
+
+ with TestClient(app) as client:
+ response = client.patch(
+ f"/api/agent-chat/sessions/{session.session_id}",
+ json={"permission_mode": "ask"},
+ )
+ assert response.status_code == 422
+ assert svc.store.permission_override(session.session_id) == ""
+ assert svc.store.get_session(session.session_id).permission_mode == "bypass"
+
+
+async def test_society_patch_does_not_reseat_if_a_turn_starts_during_cleanup(world):
+ from jarvis.ui.web.agent_chat_routes import router
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+
+ async def begin_turn(_session_id):
+ svc.busy.add(session.session_id)
+
+ svc.controls = SimpleNamespace(
+ state=lambda _sid: SimpleNamespace(goal=None),
+ _clear_saved_native=begin_turn,
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = svc
+ with TestClient(app) as client:
+ response = client.patch(
+ f"/api/agent-chat/sessions/{session.session_id}",
+ json={"provider": "gemini"},
+ )
+ assert response.status_code == 409
+ assert svc.store.get_session(session.session_id).provider == "openai"
+
+
+async def test_direct_send_rebinds_safe_agent_before_runner(tmp_path: Path):
+ from jarvis.agent_chat.service import AgentChatService
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ try:
+ agent, _ = await rt.roster.create(
+ name="Reader", provider="openai", permission_ceiling="safe"
+ )
+ agent = await _legacy_agent(rt, agent)
+ session = ensure_session(svc, cfg, agent)
+ store.update_session(session.session_id, permission_mode="bypass")
+ store.set_permission_override(session.session_id, "bypass")
+ observed: list[str] = []
+
+ async def capture(handle, _text):
+ observed.append(handle.session.permission_mode)
+
+ await svc.send(
+ session.session_id,
+ "Read the note",
+ control_runner=capture,
+ control_owned=True,
+ direct_user=False,
+ )
+ await svc.wait_turn(session.session_id)
+ assert observed == ["plan"]
+ assert store.get_session(session.session_id).permission_mode == "plan"
+ finally:
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_routine_chat_rejects_direct_messages_and_inactive_owner(tmp_path: Path):
+ from jarvis.agent_chat.service import AgentChatService
+ from jarvis.ui.web.agent_chat_routes import router
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ routine = store.create_session(
+ session_id=f"{agent.session_id}:routine:task-1:run-1",
+ surface="society",
+ provider="openai",
+ model="",
+ effort="low",
+ cwd=str(tmp_path),
+ permission_mode="bypass",
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = svc
+ with TestClient(app) as client:
+ response = client.post(
+ f"/api/agent-chat/sessions/{routine.session_id}/messages",
+ json={"text": "Do something unrelated"},
+ )
+ assert response.status_code == 403
+ assert store.list_events(routine.session_id) == []
+
+ await rt.roster.update(agent.agent_id, {"state": "paused"})
+ with pytest.raises(PermissionError, match="active scheduled run"):
+ await svc.send(
+ routine.session_id, "Scheduled task", direct_user=False, routine_run=True
+ )
+ finally:
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_busy_turn_defers_provider_reseat_until_it_finishes(tmp_path: Path):
+ import asyncio
+
+ from jarvis.agent_chat.control_types import CommandRequest
+ from jarvis.agent_chat.service import AgentChatService, SessionBusy
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ started = asyncio.Event()
+ release = asyncio.Event()
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai", model="old")
+ session = ensure_session(svc, cfg, agent)
+
+ async def held_runner(_handle, _text):
+ started.set()
+ await release.wait()
+ return "old-vendor-session"
+
+ await svc.send(
+ session.session_id,
+ "First task",
+ control_runner=held_runner,
+ control_owned=True,
+ direct_user=False,
+ )
+ await asyncio.wait_for(started.wait(), timeout=3)
+ await rt.roster.update(agent.agent_id, {"provider": "gemini", "model": "new"})
+ with pytest.raises(SessionBusy):
+ await svc.send(session.session_id, "Second task")
+ command = await svc.controls.execute(
+ session.session_id, CommandRequest(command="status", request_id="busy-status")
+ )
+ assert command.status == "done"
+ assert command.data["running"] is True
+ assert store.get_session(session.session_id).provider == "openai"
+
+ release.set()
+ await svc.wait_turn(session.session_id)
+ assert store.get_session(session.session_id).vendor_session == "old-vendor-session"
+ moved = await svc.bind_society_session(session.session_id)
+ assert moved.provider == "gemini" and moved.model == "new"
+ assert moved.vendor_session == ""
+ finally:
+ release.set()
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_build_cannot_raise_a_safe_agent_above_its_ceiling(world):
+ from jarvis.agent_chat.control import ChatControls
+ from jarvis.agent_chat.control_types import CommandRequest
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ agent = await _legacy_agent(rt, agent)
+ session = ensure_session(svc, cfg, agent)
+ controls = ChatControls(svc, adapters=[])
+ svc.controls = controls
+ plan = await controls.execute(
+ session.session_id, CommandRequest(command="plan", request_id="plan-1")
+ )
+ assert plan.status == "done"
+ updated = await rt.roster.update(agent.agent_id, {"permission_ceiling": "safe"})
+ assert updated.permission_ceiling == "safe"
+ build = await controls.execute(
+ session.session_id, CommandRequest(command="build", request_id="build-1")
+ )
+ assert build.status == "failed"
+ assert svc.store.get_session(session.session_id).permission_mode == "plan"
+ assert svc.store.permission_override(session.session_id) == "plan"
+
+
+async def test_build_sees_a_relaxed_roster_ceiling_before_checking_plan(world):
+ from jarvis.agent_chat.control import ChatControls
+ from jarvis.agent_chat.control_types import CommandRequest
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Reader", provider="openai", permission_ceiling="safe")
+ agent = await _legacy_agent(rt, agent)
+ session = ensure_session(svc, cfg, agent)
+ controls = ChatControls(svc, adapters=[])
+ svc.controls = controls
+ await rt.roster.update(agent.agent_id, {"permission_ceiling": "monitor"})
+
+ result = await controls.execute(
+ session.session_id, CommandRequest(command="build", request_id="build-after-roster")
+ )
+ assert result.status == "done"
+ assert svc.store.get_session(session.session_id).permission_mode == "ask"
+
+
+async def test_provider_change_with_default_model_discards_old_provider_model(world):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai", model="gpt-5.2")
+ first = ensure_session(svc, cfg, agent)
+ assert first.model == "gpt-5.2"
+
+ updated = await rt.roster.update(agent.agent_id, {"provider": "gemini", "model": ""})
+ session = ensure_session(svc, cfg, updated)
+ assert session.provider == "gemini"
+ assert session.model == ""
+ assert session.session_id == first.session_id
+
+
async def test_explicit_approval_mode_wins(world):
rt, svc, cfg = world
asker, _ = await rt.roster.create(name="Asker", provider="openai")
@@ -96,6 +467,114 @@ async def test_explicit_approval_mode_wins(world):
assert ensure_session(svc, cfg, asker).permission_mode == "ask"
+async def test_explicit_chat_mode_stays_separate_from_tool_ceiling(world):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(
+ name="Reader", provider="openai", permission_ceiling="safe"
+ )
+ session = ensure_session(svc, cfg, agent)
+ assert session.permission_mode == "bypass"
+
+ agent = await rt.roster.update(agent.agent_id, {"approval_mode": "ask"})
+ assert ensure_session(svc, cfg, agent).permission_mode == "ask"
+
+ svc.store.set_permission_override(session.session_id, "always_ask")
+ assert ensure_session(svc, cfg, agent).permission_mode == "always_ask"
+
+
+async def test_legacy_ask_agent_refuses_runner_without_actionable_approvals(world, monkeypatch):
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Legacy", provider="openai")
+ agent = await _legacy_agent(rt, agent)
+ monkeypatch.setattr(
+ "jarvis.agent_chat.service.resolve_runner", lambda *_args, **_kw: "grok-cli"
+ )
+
+ with pytest.raises(PermissionError, match="actionable approval"):
+ ensure_session(svc, cfg, agent)
+ assert svc.store.get_session(agent.session_id) is None
+
+
[email protected]("blocked_by", ["paused", "kill_switch"])
+async def test_inactive_agent_cannot_bind_canonical_chat(world, blocked_by):
+ from jarvis.society.chat_binding import bind_society_session
+
+ rt, svc, cfg = world
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ ensure_session(svc, cfg, agent)
+ if blocked_by == "paused":
+ await rt.roster.update(agent.agent_id, {"state": "paused"})
+ else:
+ await rt.store.set_kill_switch(True)
+
+ with pytest.raises(PermissionError, match="paused or disabled"):
+ await bind_society_session(svc, agent.session_id)
+
+
+async def test_roster_mode_edit_defers_busy_chat_and_preserves_override(world, monkeypatch):
+ from jarvis.ui.web.society_routes import router
+
+ rt, svc, cfg = world
+ monkeypatch.setattr(rt, "_get_chat", lambda: svc)
+ agent, _ = await rt.roster.create(name="Scout", provider="openai", approval_mode="ask")
+ session = ensure_session(svc, cfg, agent)
+ svc.store.set_permission_override(session.session_id, "always_ask")
+ assert ensure_session(svc, cfg, agent).permission_mode == "always_ask"
+ svc.busy.add(session.session_id)
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = rt
+ with TestClient(app) as client:
+ response = client.patch(
+ f"/api/society/agents/{agent.agent_id}",
+ json={"approval_mode": "bypass"},
+ )
+ assert response.status_code == 200, response.text
+ assert svc.store.get_session(session.session_id).permission_mode == "always_ask"
+
+ svc.busy.remove(session.session_id)
+ updated = await rt.roster.get(agent.agent_id)
+ assert ensure_session(svc, cfg, updated).permission_mode == "always_ask"
+
+
+ ("method", "suffix", "payload"),
+ [
+ ("POST", "/model", {"provider": "grok", "model": "grok-test"}),
+ ("PATCH", "", {"provider": "grok"}),
+ ],
+)
+async def test_runner_change_rejects_incompatible_chat_override(
+ world, monkeypatch, method, suffix, payload
+):
+ from jarvis.ui.web.society_routes import router
+
+ rt, svc, cfg = world
+ monkeypatch.setattr(rt, "_get_chat", lambda: svc)
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ svc.store.set_permission_override(session.session_id, "always_ask")
+ assert ensure_session(svc, cfg, agent).permission_mode == "always_ask"
+ monkeypatch.setattr(
+ "jarvis.agent_chat.service.resolve_runner",
+ lambda provider, **_kw: "grok-cli" if provider == "grok" else "brain",
+ )
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = rt
+ with TestClient(app) as client:
+ response = client.request(
+ method,
+ f"/api/society/agents/{agent.agent_id}{suffix}",
+ json=payload,
+ )
+ assert response.status_code == 422
+ assert (await rt.roster.get(agent.agent_id)).provider == "openai"
+ assert svc.store.get_session(session.session_id).provider == "openai"
+
+
async def test_without_provider_the_agents_tier_answers(world, monkeypatch):
rt, svc, cfg = world
import jarvis.local_models.assistant_session as tier_mod
@@ -213,7 +692,9 @@ class FakeTurnService(FakeService):
return q
def unsubscribe(self, session_id: str, q) -> None:
- self.queues.get(session_id, []).remove(q)
+ subscribers = self.queues.get(session_id, [])
+ if q in subscribers:
+ subscribers.remove(q)
async def send(self, session_id: str, text: str, attachments=None, *, incoming=None) -> str:
self.sent.append((session_id, text))
@@ -278,3 +759,108 @@ async def test_failed_turn_becomes_a_blocked_result(tmp_path: Path):
assert result.payload["open"]
finally:
await rt.close()
+
+
+async def test_empty_successful_turn_does_not_claim_task_completion(tmp_path: Path):
+ import asyncio
+
+ svc = FakeTurnService(AgentChatStore(tmp_path / "agent_chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ try:
+ await rt.roster.create(name="Scout", provider="openai")
+ env = await rt.say(from_agent="user", to_agent="scout", text="x", msg_type=MsgType.ASSIGN)
+ await svc.finish("society:scout", "")
+ await asyncio.sleep(0.05)
+ result = (await rt.store.events_for_trace(env.trace_id))[-1]
+ assert result.msg_type is MsgType.RESULT
+ assert result.payload["status"] == "blocked"
+ assert result.payload["open"] == ["Agent finished without a result report."]
+ finally:
+ await rt.close()
+
+
+async def test_lost_subscriber_recovers_the_durable_turn_result(tmp_path: Path, monkeypatch):
+ import asyncio
+
+ import jarvis.society.runtime as runtime_module
+ from jarvis.agent_chat.events import make_event
+
+ monkeypatch.setattr(runtime_module, "_WATCH_EVENT_POLL_SECONDS", 0.01)
+ svc = FakeTurnService(AgentChatStore(tmp_path / "agent_chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ try:
+ await rt.roster.create(name="Scout", provider="openai")
+ env = await rt.say(
+ from_agent="user", to_agent="scout", text="Find the answer", msg_type=MsgType.ASSIGN
+ )
+ # A full subscriber queue is detached by the service. The terminal
+ # event still lives in the chat store but never reaches this queue.
+ svc.queues["society:scout"].clear()
+ svc.store.append_event(
+ "society:scout",
+ make_event("assistant_text", {"turn_id": "turn-1", "text": "Found the answer."}),
+ )
+ svc.store.append_event(
+ "society:scout",
+ make_event("turn_finished", {"turn_id": "turn-1", "status": "done"}),
+ )
+ for _ in range(20):
+ thread = await rt.store.events_for_trace(env.trace_id)
+ if thread[-1].msg_type is MsgType.RESULT:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("watcher did not recover the durable terminal event")
+ assert thread[-1].payload["status"] == "done"
+ assert thread[-1].payload["done"] == "Found the answer."
+ assert rt.scheduler.running == {}
+ finally:
+ await rt.close()
+
+
+async def test_durable_read_failure_releases_the_agent_slot(tmp_path: Path, monkeypatch):
+ import asyncio
+
+ import jarvis.society.runtime as runtime_module
+
+ monkeypatch.setattr(runtime_module, "_WATCH_EVENT_POLL_SECONDS", 0.01)
+ svc = FakeTurnService(AgentChatStore(tmp_path / "agent_chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ try:
+ await rt.roster.create(name="Scout", provider="openai")
+ env = await rt.say(
+ from_agent="user", to_agent="scout", text="Find the answer", msg_type=MsgType.ASSIGN
+ )
+ svc.queues["society:scout"].clear()
+
+ def unreadable(_session_id, *, after_seq=0):
+ raise OSError("chat history unavailable")
+
+ monkeypatch.setattr(svc.store, "list_events", unreadable)
+ for _ in range(30):
+ thread = await rt.store.events_for_trace(env.trace_id)
+ if thread[-1].msg_type is MsgType.RESULT:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("watcher did not release the slot after durable read failure")
+ assert thread[-1].payload["status"] == "blocked"
+ assert thread[-1].payload["open"] == [
+ "Agent result could not be recovered from chat history."
+ ]
+ assert svc.cancelled_turns == ["turn-1"]
+ assert rt.scheduler.running == {}
+ finally:
+ await rt.close()
diff --git a/tests/unit/society/test_cli_routines.py b/tests/unit/society/test_cli_routines.py
index bcc8ebd326..14879b15e4 100644
--- a/tests/unit/society/test_cli_routines.py
+++ b/tests/unit/society/test_cli_routines.py
@@ -174,6 +174,21 @@ async def test_read_only_session_can_inspect_but_not_schedule(world):
assert world.tasks.rows == []
+async def test_cli_catalog_uses_bound_chat_approval_mode(world):
+ world.store.update_session("society:scout", permission_mode="always_ask")
+ catalog = {tool.name: tool for tool in await world.gateway.session_catalog("society:scout")}
+ assert catalog["Read"].risk_tier == "safe"
+ assert catalog["Read"].risk_tier_for_args({"file_path": "note.txt"}) == "ask"
+
+
+async def test_legacy_cli_agent_honors_explicit_chat_override(world):
+ await world.rt.store.update_agent("scout", {"approval_mode": None})
+ world.store.set_permission_override("society:scout", "always_ask")
+ world.store.update_session("society:scout", permission_mode="always_ask")
+ catalog = {tool.name: tool for tool in await world.gateway.session_catalog("society:scout")}
+ assert catalog["Read"].risk_tier_for_args({"file_path": "note.txt"}) == "ask"
+
+
async def test_grants_are_checked_again_at_call_time(world):
tool = SimpleNamespace(name="gmail", schema={}, description="Mail", risk_tier="ask")
diff --git a/tests/unit/society/test_runtime_kill_switch.py b/tests/unit/society/test_runtime_kill_switch.py
new file mode 100644
index 0000000000..221067ebe1
--- /dev/null
+++ b/tests/unit/society/test_runtime_kill_switch.py
@@ -0,0 +1,60 @@
+"""The Society kill switch stops only Society-owned chat turns."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.society.runtime import SocietyRuntime
+from tests.fakes.fake_agent_chat import FakeChatService
+
+
+class CancellableChat(FakeChatService):
+ def __init__(self, store: AgentChatStore) -> None:
+ super().__init__(store)
+ self._running: dict[str, SimpleNamespace] = {}
+ self.signaled: list[str] = []
+ self.cancelled: list[str] = []
+
+ def signal_cancel(self, session_id: str) -> bool:
+ self.signaled.append(session_id)
+ return True
+
+ async def cancel(self, session_id: str) -> bool:
+ self.cancelled.append(session_id)
+ return True
+
+
+async def test_kill_switch_cancels_active_society_chats_only(tmp_path: Path):
+ chat_store = AgentChatStore(tmp_path / "chat.db")
+ chat = CancellableChat(chat_store)
+ ids = (
+ ("society:scout", "society"),
+ ("society:scout:routine:one", "society"),
+ ("agent:ordinary", "agent"),
+ )
+ for session_id, surface in ids:
+ chat_store.create_session(
+ session_id=session_id,
+ surface=surface,
+ provider="openai",
+ model="test",
+ effort="",
+ cwd=str(tmp_path),
+ permission_mode="ask",
+ )
+ chat._running[session_id] = SimpleNamespace(task=object())
+ runtime = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: chat
+ )
+ await runtime.ensure_started()
+ try:
+ result = await runtime.engage_kill_switch()
+ assert result["engaged"]
+ assert await runtime.store.kill_switch()
+ assert set(chat.signaled) == {"society:scout", "society:scout:routine:one"}
+ assert set(chat.cancelled) == set(chat.signaled)
+ finally:
+ await runtime.close()
+ chat_store.close()
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index 66b6ae5c5e..7ed580ab93 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -2,12 +2,20 @@
from __future__ import annotations
+import asyncio
from pathlib import Path
from types import SimpleNamespace
import pytest
+from jarvis.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_ref
+from jarvis.core.bus import EventBus
+from jarvis.core.config import SafetyConfig
+from jarvis.core.protocols import ToolResult
from jarvis.core.response_style import KEEP_GOING_ON_TOOL_FAILURE
+from jarvis.safety.approval import ApprovalWorkflow
+from jarvis.safety.risk_tier import RiskTierEvaluator
+from jarvis.safety.tool_executor import ToolExecutor
from jarvis.society import runtime as runtime_mod
from jarvis.society.agent_tools import (
MEMORY_RECALL_TOOL_NAME,
@@ -19,6 +27,7 @@ from jarvis.society.agent_tools import (
from jarvis.society.ask_tool import ASK_USER_TOOL_NAME
from jarvis.society.learning import RUN_SKILL_TOOL_NAME
from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.shell import ShellResult
from jarvis.society.surface import (
agent_id_of,
build_briefing,
@@ -230,6 +239,165 @@ async def test_a_granted_tool_is_gated_by_the_agents_rules(rt: SocietyRuntime, t
assert gmail.risk_tier_for_args({"action": "send"}) == "monitor"
+async def test_bound_chat_always_ask_cards_a_safe_read(rt: SocietyRuntime, tmp_path: Path):
+ await rt.roster.create(name="Reader", approval_mode="bypass", permission_ceiling="safe")
+ workspace = tmp_path / "workspace"
+ workspace.mkdir()
+ (workspace / "note.txt").write_text("hello", encoding="utf-8")
+ session = SimpleNamespace(
+ session_id="society:reader", permission_mode="always_ask", cwd=str(workspace)
+ )
+ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))
+ await society_system_extra(cfg, None, session)
+ filt = society_tool_filter(session)
+ assert filt is not None
+ read = filt(society_tools(cfg, None, session))["Read"]
+ assert read.risk_tier == "safe"
+ assert read.risk_tier_for_args({"file_path": "note.txt"}) == "ask"
+ bus = EventBus()
+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))
+ bridge = ChatApprovalBridge(bus)
+ asked = asyncio.Event()
+ release = asyncio.Event()
+ seen: list[str] = []
+
+ async def card(_call_id: str, name: str, _args: dict, _summary: str) -> str:
+ seen.append(name)
+ asked.set()
+ await release.wait()
+ return "allow"
+
+ ref = approval_ref(session.session_id)
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=session.session_id,
+ turn_id="turn-1",
+ stance="always_ask",
+ always_allowed=set(),
+ ask=card,
+ ),
+ )
+ running = asyncio.create_task(
+ executor.execute(
+ read,
+ {"file_path": "note.txt"},
+ config_snapshot={
+ "approval_surface": "interactive",
+ "approval_ref": ref,
+ "approval_timeout_s": 5,
+ },
+ )
+ )
+ try:
+ await asyncio.wait_for(asked.wait(), timeout=5)
+ assert seen == ["Read"]
+ assert not running.done(), "the tool waits for the person's card"
+ finally:
+ release.set()
+ result = await asyncio.wait_for(running, timeout=5)
+ assert result.success, result.error
+
+
+async def test_bound_chat_ask_gates_monitor_without_widening_roster(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailbox", approval_mode="bypass", permission_ceiling="monitor")
+ for mode, expected in (("bypass", "monitor"), ("ask", "ask"), ("always_ask", "ask")):
+ session = SimpleNamespace(session_id="society:mailbox", permission_mode=mode)
+ await society_system_extra(None, None, session)
+ filt = society_tool_filter(session)
+ assert filt is not None
+ assert filt(TOOLS)["gmail"].risk_tier_for_args({"action": "list"}) == expected
+
+ await rt.roster.update("mailbox", {"approval_mode": "ask"})
+ session = SimpleNamespace(session_id="society:mailbox", permission_mode="bypass")
+ await society_system_extra(None, None, session)
+ filt = society_tool_filter(session)
+ assert filt is not None
+ assert filt(TOOLS)["gmail"].risk_tier_for_args({"action": "list"}) == "ask"
+
+
+async def test_in_flight_tool_stops_after_kill_or_agent_pause(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailer", approval_mode="bypass")
+ session = SimpleNamespace(session_id="society:mailer", permission_mode="bypass")
+ await society_system_extra(None, None, session)
+ calls: list[dict] = []
+
+ async def execute(args: dict, _ctx: object) -> ToolResult:
+ calls.append(args)
+ return ToolResult(True, "ok", None)
+
+ tool = _tool("gmail")
+ tool.execute = execute
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({"gmail": tool})["gmail"]
+ ctx = SimpleNamespace(approved_by="auto")
+ assert (await gated.execute({"action": "list"}, ctx)).success
+ await rt.store.set_kill_switch(True)
+ killed = await gated.execute({"action": "list"}, ctx)
+ assert not killed.success and killed.output["reason"] == "kill_switch"
+ await rt.store.set_kill_switch(False)
+ await rt.roster.update("mailer", {"state": "paused"})
+ paused = await gated.execute({"action": "list"}, ctx)
+ assert not paused.success and paused.output["reason"] == "blocked_by_policy"
+ assert calls == [{"action": "list"}]
+
+
+async def test_shell_uses_one_chat_approval_for_one_command(rt: SocietyRuntime, tmp_path: Path):
+ await rt.roster.create(name="Runner", approval_mode="ask")
+ workspace = tmp_path / "workspace"
+ session = SimpleNamespace(
+ session_id="society:runner", permission_mode="ask", cwd=str(workspace)
+ )
+ await society_system_extra(None, None, session)
+ from jarvis.society.agent_tools import ShellTool
+
+ class Backend:
+ name = "fake"
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+
+ async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult:
+ self.calls.append(command)
+ return ShellResult(output="ok", exit_code=0, seconds=0.01)
+
+ backend = Backend()
+ shell = ShellTool(rt, "runner", workspace=workspace, backend=backend)
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({SHELL_TOOL_NAME: shell})[SHELL_TOOL_NAME]
+ bus = EventBus()
+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))
+ bridge = ChatApprovalBridge(bus)
+ cards: list[str] = []
+
+ async def card(_call_id: str, name: str, _args: dict, _summary: str) -> str:
+ cards.append(name)
+ return "allow"
+
+ ref = approval_ref(session.session_id)
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=session.session_id,
+ turn_id="turn-1",
+ stance="ask",
+ always_allowed=set(),
+ ask=card,
+ ),
+ )
+ result = await executor.execute(
+ gated,
+ {"command": "echo hi"},
+ config_snapshot={"approval_surface": "interactive", "approval_ref": ref},
+ )
+ assert result.success, result.error
+ assert cards == [SHELL_TOOL_NAME]
+ assert backend.calls == ["echo hi"]
+ assert await rt.approvals.pending() == []
+
+
async def test_always_allow_writes_the_agents_own_rule(rt: SocietyRuntime):
from jarvis.society.surface import remember_always_allow
diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.py
index 6087f38caa..6f0f2b4d77 100644
--- a/tests/unit/ui/web/test_society_routes.py
+++ b/tests/unit/ui/web/test_society_routes.py
@@ -423,7 +423,7 @@ def test_memory_file_serves_society_page_and_refuses_escape(memory_client):
runtime: SocietyRuntime = c.app.state.society
scout = asyncio.run(runtime.roster.get("scout"))
rel = asyncio.run(runtime.memory.remember(scout, "Loves maps.", root=vault))
- assert rel == "society/scout/memory.md"
+ assert rel == "society/scout/MEMORY.md"
got = c.get("/api/society/memory/file", params={"path": rel}).json()
assert got["path"] == rel and got["agent_id"] == "scout"
assert "Loves maps." in got["content"]