Skip to content

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

feat(agents): one action card for approvals with saved allow rules (#909)

Ruben Lütke38f7906f2169
diff --git a/dodaios/agent_chat/approval_bridge.py b/dodaios/agent_chat/approval_bridge.py
index 4610e099f9..5e45c28caa 100644
--- a/dodaios/agent_chat/approval_bridge.py
+++ b/dodaios/agent_chat/approval_bridge.py
@@ -106,6 +106,11 @@ class ChatApprovalBridge:
#: own timeout, another surface's answer — closes its card here, so a
#: late click can no longer read "approved" for a call that was refused.
self._asking: dict[UUID, asyncio.Task[None]] = {}
+ #: ``(session_id, tool_name) -> bool``: whether an "Always allow" also
+ #: stops this chat asking for the whole tool. The service answers no
+ #: when the card saved a rule on the agent instead: that rule (perhaps
+ #: one action only) governs, and the chat must not widen it.
+ self.chat_keeps_always: Callable[[str, str], bool] = lambda _sid, _tool: True
bus.subscribe(ActionProposed, self._on_proposed)
bus.subscribe(ActionApprovalRequired, self._on_required)
bus.subscribe(ActionApproved, self._on_settled)
@@ -188,6 +193,13 @@ class ChatApprovalBridge:
# ------------------------------------------------------------ policy
+ def _chat_keeps(self, grant: ChatGrant, tool_name: str) -> bool:
+ try:
+ return bool(self.chat_keeps_always(grant.session_id, tool_name))
+ except Exception: # noqa: BLE001 — as before: the chat remembers the tool
+ log.warning("chat approval bridge: always-allow check failed", exc_info=True)
+ return True
+
@staticmethod
def _decide_inline(
grant: ChatGrant, tool_name: str, args: dict[str, Any] | None = None
@@ -224,7 +236,7 @@ class ChatApprovalBridge:
# Our own answer below must not read as "settled elsewhere".
self._forget(event.trace_id, asyncio.current_task())
if decision in ("allow", "allow_always"):
- if decision == "allow_always":
+ if decision == "allow_always" and self._chat_keeps(grant, event.tool_name):
grant.always_allowed.add(_bare(event.tool_name))
await self._bus.publish(
ActionApproved(
diff --git a/dodaios/agent_chat/approval_card.py b/dodaios/agent_chat/approval_card.py
new file mode 100644
index 0000000000..bb4819dc36
--- /dev/null
+++ b/dodaios/agent_chat/approval_card.py
@@ -0,0 +1,357 @@
+"""What an approval card shows besides its three answers (display only).
+
+Every approval source ends in ``AgentChatService._ask``: the ToolExecutor
+bridge (brain runner and the MCP gateway), the API loop's folder tools, Claude
+Code's stdin control protocol and ACP ``session/request_permission`` from
+Hermes or OpenClaw. This module turns the call that asks ``(name, args,
+summary)`` into the fields the card reads. Nothing here decides anything: the
+decision set (allow / allow_always / deny / cancel / expired) and every policy
+stay where they are.
+
+Fields added to the ``approval_required`` payload. All are optional; an older
+event has none of them and the card falls back to the tool name and summary.
+
+``source`` ``{kind, app?, verb?}``. ``kind`` is one of :data:`SOURCE_KINDS`;
+ ``app`` names the connector or MCP server a ``connector`` call goes
+ to, ``verb`` the one-word action it performs there (``send``).
+``where`` the folder, site or machine the action runs at.
+``why`` the agent's own reason, when its runner passes one (Claude's Bash
+ ``description``, a Codex ``reason``).
+``caution`` ``""`` or one of :data:`CAUTIONS`: an action that cannot be undone,
+ one that changes security settings, or one that sends data out of
+ the chat.
+``detail`` the exact command or request for the card's disclosure, with
+ every secret masked. The raw ``input`` stays as it always was.
+``rule`` what "Always allow" saves (:func:`rule_offer`), or ``None`` when
+ the card offers no "Always allow" at all (a plan).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from typing import Any, Final
+from urllib.parse import urlparse
+
+from dodaios.core.mcp_names import own_cli_tool, split_cli_tool_name
+from dodaios.core.redact import redact_secrets
+
+log = logging.getLogger(__name__)
+
+SOURCE_KINDS: Final[tuple[str, ...]] = (
+ "terminal",
+ "files",
+ "browser",
+ "computer",
+ "plan",
+ "agent",
+ "connector",
+ "tool",
+)
+CAUTIONS: Final[tuple[str, ...]] = ("irreversible", "security", "data_leaves")
+
+#: How a card answers "Always allow" in this chat when no agent rule applies.
+#: ``tool``: this tool stops asking in this chat. ``all``: the chat stops asking
+#: (its stance becomes auto). ``runtime``: the runtime that asked remembers it.
+CHAT_EFFECTS: Final[tuple[str, ...]] = ("tool", "all", "runtime")
+
+_MASK: Final[str] = "••••••"
+_DETAIL_CHARS: Final[int] = 4000
+_LINE_CHARS: Final[int] = 240
+
+_PLAN_TOOLS: Final[frozenset[str]] = frozenset({"ExitPlanMode", "exit_plan_mode"})
+_TERMINAL_TOOLS: Final[frozenset[str]] = frozenset(
+ {
+ "bash",
+ "runcommand",
+ "run_command",
+ "shell",
+ "local_shell",
+ "exec",
+ "exec_command",
+ "execute",
+ "terminal",
+ "powershell",
+ "society_shell",
+ "society_sandbox",
+ }
+)
+_FILE_TOOLS: Final[frozenset[str]] = frozenset(
+ {
+ "write",
+ "edit",
+ "multiedit",
+ "notebookedit",
+ "apply_patch",
+ "write_file",
+ "edit_file",
+ "create_file",
+ "str_replace",
+ "str_replace_editor",
+ "delete_file",
+ "read",
+ "read_file",
+ }
+)
+_COMPUTER_TOOLS: Final[frozenset[str]] = frozenset(
+ {
+ "click",
+ "click-element",
+ "type-text",
+ "hotkey",
+ "scroll",
+ "drag",
+ "move-mouse",
+ "switch-window",
+ "open-app",
+ "computer",
+ "computer_use",
+ }
+)
+_AGENT_TOOLS: Final[frozenset[str]] = frozenset({"task", "agent", "spawn_agent"})
+
+_SECRET_KEY: Final[re.Pattern[str]] = re.compile(
+ r"(?i)(pass(word|wd|phrase)?|secret|token|api[_-]?key|apikey"
+ r"|(?<![a-z])auth(orization)?(?![a-z])|cookie|credential|private[_-]?key"
+ r"|session[_-]?key|(?<![a-z])otp(?![a-z])|pin[_-]?code)"
+)
+
+_IRREVERSIBLE: Final[re.Pattern[str]] = re.compile(
+ r"(?i)(\brm\s+-|\brm\b\s+\S|\brmdir\b|\bdel\s+/|\bremove-item\b|\brd\s+/s\b"
+ r"|\bdrop\s+(table|database|schema)\b|\btruncate\b|\bpush\b[^\n]*\s(-f|--force)\b"
+ r"|\breset\s+--hard\b|\bclean\s+-[a-z]*f|\bshred\b|\bmkfs\b|\bformat\s+[a-z]:"
+ r"|^(delete|remove|destroy|purge|wipe|trash|uninstall|pay|purchase|buy|transfer)\b)"
+)
+_SECURITY: Final[re.Pattern[str]] = re.compile(
+ r"(?i)(\bchmod\b|\bchown\b|\bicacls\b|\bsudo\b|\brunas\b|set-executionpolicy"
+ r"|\breg\s+(add|delete)\b|\bnetsh\b|\bfirewall\b|ssh-keygen|authorized_keys"
+ r"|^(grant|revoke|rotate|set_permission|share_access|make_public)\b)"
+)
+_DATA_LEAVES: Final[re.Pattern[str]] = re.compile(
+ r"(?i)(\bgit\s+push\b|\bgh\s+(pr|issue|release)\s+create\b|\bcurl\b[^\n]*\s(-d|--data|-X\s*POST|-F)\b"
+ r"|\bscp\b|\bnpm\s+publish\b|\btwine\s+upload\b"
+ r"|^(send|post|publish|share|upload|tweet|reply|forward|email|message|comment|invite"
+ r"|create_draft_and_send|send_message|send_email)\b)"
+)
+
+
+def describe_call(
+ name: str,
+ args: dict[str, Any] | None,
+ summary: str = "",
+ *,
+ cwd: str = "",
+ rule: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """The card's display fields for one call. Never raises."""
+ try:
+ return _describe(name or "", args if isinstance(args, dict) else {}, summary, cwd, rule)
+ except Exception: # noqa: BLE001 — a card without its extras still asks correctly
+ log.warning("approval card: could not describe %s", name, exc_info=True)
+ return {}
+
+
+def _describe(
+ name: str, args: dict[str, Any], summary: str, cwd: str, rule: dict[str, Any] | None
+) -> dict[str, Any]:
+ source = source_of(name, args)
+ kind = source["kind"]
+ command = _command_text(args)
+ verb = action_verb(args)
+ if kind == "connector" and verb:
+ source = {**source, "verb": verb}
+ fields: dict[str, Any] = {
+ "source": source,
+ "where": _where(kind, args, cwd),
+ "why": _why(args),
+ "caution": caution_of(kind, command, verb),
+ "detail": "" if kind == "plan" else request_detail(args, command),
+ "rule": None if kind == "plan" else rule,
+ }
+ return fields
+
+
+def source_of(name: str, args: dict[str, Any]) -> dict[str, str]:
+ """``{kind, app?}``: what is asking, as the card's source chip shows it."""
+ own = own_cli_tool(name)
+ other = None if own is not None else split_cli_tool_name(name)
+ bare = own or (other[1] if other else name)
+ low = bare.lower()
+ if bare in _PLAN_TOOLS:
+ return {"kind": "plan"}
+ if low in _TERMINAL_TOOLS or (low.endswith("shell") and "command" in args):
+ return {"kind": "terminal"}
+ if low in _FILE_TOOLS:
+ return {"kind": "files"}
+ if "browser" in low or low in {"webfetch", "web_fetch", "navigate", "fetch"}:
+ return {"kind": "browser"}
+ if low in _COMPUTER_TOOLS:
+ return {"kind": "computer"}
+ if low in _AGENT_TOOLS:
+ return {"kind": "agent"}
+ if other is not None:
+ # Another MCP server's tool: that server is the connector asking.
+ return {"kind": "connector", "app": app_label(other[0])}
+ if own is not None or _looks_like_connector(bare):
+ return {"kind": "connector", "app": app_label(bare)}
+ if isinstance(args.get("command"), (str, list)) and not args.get("action"):
+ return {"kind": "terminal"}
+ if isinstance(args.get("file_path"), str):
+ return {"kind": "files"}
+ return {"kind": "tool", "app": bare[:60]}
+
+
+def _looks_like_connector(bare: str) -> bool:
+ """A plugin/API tool name (``gmail``, ``google_calendar``, ``api_notion``)."""
+ return bool(re.fullmatch(r"[a-z][a-z0-9_]*(-[a-z0-9]+)*", bare)) and bare.lower() not in {
+ "read",
+ "grep",
+ "glob",
+ "ls",
+ "list",
+ "search",
+ }
+
+
+_APP_WORDS: Final[dict[str, str]] = {"github": "GitHub", "gitlab": "GitLab", "api": ""}
+
+
+def app_label(raw: str) -> str:
+ """``google_calendar`` -> ``Google Calendar``; a label stays as it is."""
+ text = (raw or "").strip()
+ if not text:
+ return ""
+ if any(ch.isupper() for ch in text) or " " in text:
+ return text[:60]
+ words = [w for w in re.split(r"[_\-.]+", text) if w]
+ shown = [_APP_WORDS.get(w, w[:1].upper() + w[1:]) for w in words]
+ return " ".join(w for w in shown if w)[:60] or text[:60]
+
+
+def action_verb(args: dict[str, Any]) -> str:
+ """The one-word action a mixed tool performs (``gmail``: ``send``), else ``""``.
+
+ Stricter than the gate's own verb reading on purpose: only a single word is
+ a verb a person can read in a rule. A shell command is never one.
+ """
+ for key in ("action", "operation", "method", "mode"):
+ raw = args.get(key)
+ if isinstance(raw, str):
+ word = raw.strip().lower()
+ if re.fullmatch(r"[a-z][a-z0-9_.-]{0,39}", word):
+ return word
+ return ""
+
+
+def _command_text(args: dict[str, Any]) -> str:
+ raw = args.get("command") if "command" in args else args.get("cmd")
+ if isinstance(raw, list):
+ return " ".join(str(part) for part in raw)
+ return raw if isinstance(raw, str) else ""
+
+
+def caution_of(kind: str, command: str, verb: str) -> str:
+ """The caution caption a card wears, from what the call does."""
+ for text in (command, verb):
+ if not text:
+ continue
+ if _IRREVERSIBLE.search(text):
+ return "irreversible"
+ if _SECURITY.search(text):
+ return "security"
+ if _DATA_LEAVES.search(text):
+ return "data_leaves"
+ return ""
+
+
+def _where(kind: str, args: dict[str, Any], cwd: str) -> str:
+ if kind in ("terminal", "files"):
+ folder = args.get("cwd") or args.get("workdir") or cwd
+ return str(folder)[:_LINE_CHARS] if isinstance(folder, str) else ""
+ if kind == "browser":
+ url = args.get("url") or args.get("href")
+ if isinstance(url, str) and url.strip():
+ host = urlparse(url.strip()).hostname
+ return (host or "")[:_LINE_CHARS]
+ return ""
+
+
+def _why(args: dict[str, Any]) -> str:
+ for key in ("description", "reason", "justification", "explanation"):
+ raw = args.get(key)
+ if isinstance(raw, str) and raw.strip():
+ line = " ".join(raw.split())
+ return redact_secrets(line)[:_LINE_CHARS]
+ return ""
+
+
+def mask_secrets(value: Any, _depth: int = 0) -> Any:
+ """``value`` with every secret-named field masked, recursively."""
+ if _depth > 8:
+ return _MASK
+ if isinstance(value, dict):
+ return {
+ str(k): (
+ _MASK
+ if _SECRET_KEY.search(str(k)) and isinstance(v, str) and v.strip()
+ else mask_secrets(v, _depth + 1)
+ )
+ for k, v in value.items()
+ }
+ if isinstance(value, list):
+ return [mask_secrets(v, _depth + 1) for v in value[:200]]
+ if isinstance(value, str):
+ return redact_secrets(value)
+ return value
+
+
+def request_detail(args: dict[str, Any], command: str = "") -> str:
+ """The exact command or request, secrets masked, for the card's disclosure."""
+ if command:
+ return redact_secrets(command)[:_DETAIL_CHARS]
+ if not args:
+ return ""
+ masked = mask_secrets(args)
+ try:
+ text = json.dumps(masked, ensure_ascii=False, indent=2, default=str)
+ except (TypeError, ValueError): # unserialisable args still show, as their plain repr
+ text = str(masked)
+ return redact_secrets(text)[:_DETAIL_CHARS]
+
+
+def rule_offer(
+ surface: str, name: str, args: dict[str, Any], agent_rule: dict[str, Any] | None
+) -> dict[str, Any]:
+ """What "Always allow" saves on this card.
+
+ ``scopes`` lists where a rule can live: ``agent`` (the society agent's own
+ approval rules, persistent) and ``chat`` (this conversation). ``chat``
+ names what a chat-wide "always" does on this surface (:data:`CHAT_EFFECTS`).
+ A society agent's own tool carries ``app``, ``verb``, ``pattern`` and
+ ``broad`` (the pattern for every action of that app).
+ """
+ if surface == "society" and agent_rule:
+ return {"scopes": ["agent", "chat"], "chat": "tool", **agent_rule}
+ bare = own_cli_tool(name) or name
+ if surface == "jarvis":
+ return {"scopes": ["chat"], "chat": "tool", "app": app_label(bare)}
+ if surface == "society":
+ # A runtime's own tool: its "always" is the runtime's to remember.
+ return {"scopes": [], "chat": "runtime"}
+ return {"scopes": ["chat"], "chat": "all"}
+
+
+__all__ = [
+ "CAUTIONS",
+ "CHAT_EFFECTS",
+ "SOURCE_KINDS",
+ "action_verb",
+ "app_label",
+ "caution_of",
+ "describe_call",
+ "mask_secrets",
+ "request_detail",
+ "rule_offer",
+ "source_of",
+]
diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.py
index b451789672..df8b7a7178 100644
--- a/dodaios/agent_chat/service.py
+++ b/dodaios/agent_chat/service.py
@@ -163,6 +163,10 @@ def _orphan_event(turn_id: str, started_ms: int, last_ms: int) -> dict[str, Any]
DECISIONS: tuple[str, ...] = ("allow", "allow_always", "deny")
+#: Where a rule from the approval card lives: the agent's own rules or this chat.
+RULE_SCOPES: tuple[str, ...] = ("agent", "chat")
+#: How far an agent rule from the card reaches: this action, or the whole app.
+RULE_BREADTHS: tuple[str, ...] = ("action", "app")
class SessionBusy(RuntimeError):
@@ -461,6 +465,13 @@ class AgentChatService:
# no word for "auto" and flipping to bypass would silence every later
# card, a mail send included.
self._always_allowed: dict[str, set[str]] = {}
+ # Where an "Always allow" from the card is to live, by approval id:
+ # ``(scope, breadth)`` as the card's rule chooser sent it.
+ self._approval_choice: dict[str, tuple[str, str]] = {}
+ # Tools whose "Always allow" the card just saved on the society agent,
+ # by session: the approval bridge must not also wave the whole tool
+ # through for the chat (a rule for one action would read wider).
+ self._ruled_on_agent: dict[str, set[str]] = {}
# Voice turn ids already mirrored into a chat timeline (see
# import_voice_turn): the bus may deliver a turn twice across
# reconnects, and a second copy in the chat would read as if the
@@ -835,8 +846,20 @@ class AgentChatService:
return None
if self._bridge is None:
self._bridge = ChatApprovalBridge(bus)
+ self._bridge.chat_keeps_always = self._chat_keeps_always
return self._bridge
+ def _chat_keeps_always(self, session_id: str, tool_name: str) -> bool:
+ """False once for a tool whose "always" the card saved as an agent rule."""
+ from .approval_bridge import _bare
+
+ ruled = self._ruled_on_agent.get(session_id)
+ bare = _bare(tool_name)
+ if ruled and bare in ruled:
+ ruled.discard(bare)
+ return False
+ return True
+
def create_session(
self,
*,
@@ -2082,6 +2105,7 @@ class AgentChatService:
make_event(
"approval_required",
{
+ **self._approval_card(session_id, name, args, summary),
"turn_id": turn_id,
"approval_id": approval_id,
"call_id": call_id,
@@ -2111,15 +2135,35 @@ class AgentChatService:
finally:
self._approvals.pop(approval_id, None)
self._approval_session.pop(approval_id, None)
+ choice = self._approval_choice.pop(approval_id, None)
await self._emit(
session_id,
make_event(
"approval_resolved",
- {"turn_id": turn_id, "approval_id": approval_id, "decision": decision},
+ {
+ "turn_id": turn_id,
+ "approval_id": approval_id,
+ "decision": decision,
+ **({"scope": choice[0]} if decision == "allow_always" and choice else {}),
+ },
),
)
if decision == "allow_always":
session = self.store.get_session(session_id)
+ if choice is not None and session is not None:
+ try:
+ saved = await self._rule_from_card(
+ session, approval_id, turn_id, name, args, "always_allow", *choice
+ )
+ except Exception: # noqa: BLE001 — falls back to the surface's own "always"
+ log.warning("agent chat: rule from the card failed for %s", name, exc_info=True)
+ saved = None
+ if saved is not None:
+ if choice[0] == "agent":
+ from .approval_bridge import _bare
+
+ self._ruled_on_agent.setdefault(session_id, set()).add(_bare(name))
+ return decision
handled = False
hook = kit_for(session.surface).session_always_allow if session is not None else None
if hook is not None:
@@ -2144,17 +2188,153 @@ class AgentChatService:
"""The tools waved through with "always allow" in this session (Jarvis surface)."""
return self._always_allowed.setdefault(session_id, set())
- def resolve_approval(self, session_id: str, approval_id: str, decision: str) -> bool:
+ def resolve_approval(
+ self,
+ session_id: str,
+ approval_id: str,
+ decision: str,
+ *,
+ scope: str = "",
+ breadth: str = "",
+ ) -> bool:
+ """Answer an open card. ``scope``/``breadth`` say where an "Always allow"
+ lives (the card's rule chooser); without them it does what it always did."""
if decision not in DECISIONS:
raise ValueError(f"decision must be one of {DECISIONS}")
+ if scope and scope not in RULE_SCOPES:
+ raise ValueError(f"scope must be one of {RULE_SCOPES}")
+ if breadth and breadth not in RULE_BREADTHS:
+ raise ValueError(f"breadth must be one of {RULE_BREADTHS}")
if self._approval_session.get(approval_id) != session_id:
return False
fut = self._approvals.get(approval_id)
if fut is None or fut.done():
return False
+ if decision == "allow_always" and scope:
+ self._approval_choice[approval_id] = (scope, breadth or "action")
fut.set_result(decision)
return True
+ def _approval_card(
+ self, session_id: str, name: str, args: dict[str, Any], summary: str
+ ) -> dict[str, Any]:
+ """The card's display fields (approval_card.py); empty when unavailable."""
+ from .approval_card import describe_call, rule_offer
+
+ try:
+ session = self.store.get_session(session_id)
+ surface = session.surface if session is not None else ""
+ agent_rule = None
+ if surface == "society":
+ from dodaios.society.approvals import card_rule
+
+ agent_rule = card_rule(name, args or {})
+ rule = rule_offer(surface, name, args or {}, agent_rule)
+ cwd = str(session.cwd or "") if session is not None else ""
+ return describe_call(name, args, summary, cwd=cwd, rule=rule)
+ except Exception: # noqa: BLE001 — the card still asks with its name and summary
+ log.warning("agent chat: approval card fields unavailable for %s", name, exc_info=True)
+ return {}
+
+ async def _rule_from_card(
+ self,
+ session: Any,
+ approval_id: str,
+ turn_id: str,
+ name: str,
+ args: dict[str, Any],
+ kind: str,
+ scope: str,
+ breadth: str,
+ ) -> dict[str, Any] | None:
+ """Save the rule a card asked for and note it on the card; ``None`` if none fits.
+
+ ``agent``: the society agent's own approval rules (persistent).
+ ``chat``: this conversation stops asking for this tool until the app
+ restarts (the Jarvis and society surfaces, whose tools ask through the
+ approval bridge). Nothing else is ever widened from here.
+ """
+ from .approval_bridge import _bare
+ from .approval_card import app_label
+
+ rule: dict[str, Any] | None = None
+ if scope == "agent" and session.surface == "society":
+ from dodaios.society.approvals import save_card_rule
+
+ rule = await save_card_rule(
+ session.session_id, name, args or {}, kind=kind, breadth=breadth
+ )
+ elif (
+ scope == "chat"
+ and kind == "always_allow"
+ and session.surface in ("society", "jarvis")
+ ):
+ bare = _bare(name)
+ self._always_allowed.setdefault(session.session_id, set()).add(bare)
+ rule = {"kind": kind, "pattern": bare, "app": app_label(bare), "verb": ""}
+ if rule is None:
+ return None
+ await self._emit(
+ session.session_id,
+ make_event(
+ "notice",
+ {
+ "kind": "approval_rule",
+ "turn_id": turn_id,
+ "approval_id": approval_id,
+ "rule_kind": rule["kind"],
+ "scope": scope,
+ "pattern": rule["pattern"],
+ "app": rule.get("app", ""),
+ "verb": rule.get("verb", ""),
+ "still_asks": bool(rule.get("still_asks")),
+ },
+ ),
+ )
+ return rule
+
+ async def save_approval_rule(
+ self,
+ session_id: str,
+ approval_id: str,
+ *,
+ kind: str,
+ scope: str,
+ breadth: str = "action",
+ ) -> dict[str, Any]:
+ """A rule from a card already answered (or expired): "Always allow next
+ time", "Ask first next time". Raises KeyError for an unknown card and
+ LookupError when no rule fits that card in that scope."""
+ if scope not in RULE_SCOPES:
+ raise ValueError(f"scope must be one of {RULE_SCOPES}")
+ session = self.store.get_session(session_id)
+ if session is None:
+ raise KeyError(session_id)
+ asked: dict[str, Any] | None = None
+ for event in await asyncio.to_thread(self.store.list_events, session_id):
+ payload = event.get("payload") or {}
+ if (
+ event.get("kind") == "approval_required"
+ and payload.get("approval_id") == approval_id
+ ):
+ asked = payload
+ if asked is None:
+ raise KeyError(approval_id)
+ args = asked.get("input") if isinstance(asked.get("input"), dict) else {}
+ rule = await self._rule_from_card(
+ session,
+ approval_id,
+ str(asked.get("turn_id") or ""),
+ str(asked.get("name") or ""),
+ args,
+ kind,
+ scope,
+ breadth,
+ )
+ if rule is None:
+ raise LookupError("no rule fits this card")
+ return rule
+
async def close_stale_approval(self, session_id: str, approval_id: str) -> bool:
"""Close a card the transcript still shows open but nothing waits on.
diff --git a/dodaios/society/approvals.py b/dodaios/society/approvals.py
index c3bde11f80..448e8eaffd 100644
--- a/dodaios/society/approvals.py
+++ b/dodaios/society/approvals.py
@@ -32,7 +32,19 @@ from .store import SocietyStore
log = logging.getLogger(__name__)
-__all__ = ["Approval", "Approvals", "Verdict", "decide", "matches"]
+__all__ = [
+ "RULE_BREADTHS",
+ "RULE_KINDS",
+ "Approval",
+ "Approvals",
+ "Verdict",
+ "apply_rule",
+ "card_rule",
+ "decide",
+ "matches",
+ "rule_text",
+ "save_card_rule",
+]
DEFAULT_TTL_MS: Final[int] = 24 * 60 * 60 * 1000
_TIER_RANK: Final[dict[str, int]] = {"safe": 0, "monitor": 1, "ask": 2, "block": 3}
@@ -272,3 +284,125 @@ class Approvals:
if got is not None:
revived.append(got)
return revived
+
+
+# ------------------------------------------------------------ rules from the card
+#
+# The chat's approval card can turn one answer into a standing rule on the
+# agent's own ``approval_rules`` (``always_allow`` / ``require_approval``). The
+# patterns stay the source of truth: a rule's readable text is derived from its
+# pattern for display, never stored. Nothing below changes ``decide()``.
+
+#: The two lists a card may write to.
+RULE_KINDS: Final[tuple[str, ...]] = ("always_allow", "require_approval")
+#: ``action``: only this verb of the app (``plugin:gmail:send``); ``app``: every
+#: action of the app (``plugin:gmail``).
+RULE_BREADTHS: Final[tuple[str, ...]] = ("action", "app")
+
+
+def card_rule(tool_name: str, args: dict[str, Any]) -> dict[str, str] | None:
+ """The rule an approval card for this call can save on the agent, if any.
+
+ Only a tool the agent's own rules govern qualifies: one of the capability
+ catalog's rows, reached bare or through this app's MCP server. A runtime's
+ or another server's own tool (Claude's ``Bash``, an ACP terminal) answers
+ ``None``; its "always" stays the runtime's business.
+ """
+ from dodaios.agent_chat.approval_card import action_verb, app_label
+ from dodaios.core.mcp_names import own_cli_tool
+
+ from .capabilities import capability_id_for_tool
+ from .runtime import current_runtime
+
+ if tool_name.startswith("mcp__") and own_cli_tool(tool_name) is None:
+ return None
+ bare = own_cli_tool(tool_name) or tool_name
+ capability = capability_id_for_tool(bare)
+ rt = current_runtime()
+ if capability is None or rt is None:
+ return None
+ try:
+ rows = rt.catalog()
+ except Exception: # noqa: BLE001 — no catalog, no rule offer; the card still asks
+ log.warning("approval card: capability catalog unavailable", exc_info=True)
+ return None
+ row = next((r for r in rows if r.id == capability), None)
+ if row is None:
+ return None
+ verb = action_verb(args)
+ return {
+ "capability": capability,
+ "app": app_label(row.label or bare),
+ "verb": verb,
+ "pattern": f"{capability}:{verb}" if verb else capability,
+ "broad": capability,
+ }
+
+
+def rule_text(kind: str, app: str, verb: str = "") -> str:
+ """A rule as a sentence, for logs and notices (the card localizes its own)."""
+ what = f"{verb} with {app}" if verb else app
+ if kind == "require_approval":
+ return f"Ask first before {what}"
+ return f"Always allow {what}"
+
+
+def apply_rule(rules: dict[str, list[str]], kind: str, pattern: str) -> dict[str, list[str]]:
+ """``rules`` with ``pattern`` added to ``kind`` and taken out of the other list.
+
+ A person who says "always allow" for exactly this pattern withdraws the
+ same "ask first", and the other way round. A broader opposite pattern is
+ left alone: :func:`decide` still reads ``require_approval`` first.
+ """
+ if kind not in RULE_KINDS:
+ raise ValueError(f"kind must be one of {RULE_KINDS}")
+ other = "require_approval" if kind == "always_allow" else "always_allow"
+ out = {
+ "require_approval": list(rules.get("require_approval", [])),
+ "always_allow": list(rules.get("always_allow", [])),
+ }
+ if pattern not in out[kind]:
+ out[kind] = sorted([*out[kind], pattern])
+ out[other] = [p for p in out[other] if p != pattern]
+ return out
+
+
+async def save_card_rule(
+ session_id: str, tool_name: str, args: dict[str, Any], *, kind: str, breadth: str = "action"
+) -> dict[str, Any] | None:
+ """Write a rule from the approval card onto the society agent of ``session_id``.
+
+ Returns ``{kind, pattern, app, verb, text, still_asks}`` or ``None`` when no
+ rule fits (not a society chat, not an agent's own tool). ``still_asks`` is
+ true when a broader ``require_approval`` keeps asking anyway.
+ """
+ from .runtime import current_runtime
+ from .surface import agent_id_of
+
+ if kind not in RULE_KINDS or breadth not in RULE_BREADTHS:
+ raise ValueError("unknown rule kind or breadth")
+ rt = current_runtime()
+ agent_id = agent_id_of(session_id)
+ offer = card_rule(tool_name, args)
+ if rt is None or agent_id is None or offer is None:
+ return None
+ agent = await rt.roster.get(agent_id)
+ if agent is None:
+ return None
+ pattern = offer["broad"] if breadth == "app" else offer["pattern"]
+ verb = "" if breadth == "app" else offer["verb"]
+ rules = apply_rule(agent.approval_rules, kind, pattern)
+ if rules != agent.approval_rules:
+ updated = await rt.roster.update(agent.agent_id, {"approval_rules": rules})
+ rt.cache_agent(updated)
+ still_asks = kind == "always_allow" and any(
+ matches(p, offer["capability"], offer["verb"]) for p in rules["require_approval"]
+ )
+ return {
+ "kind": kind,
+ "pattern": pattern,
+ "app": offer["app"],
+ "verb": verb,
+ "text": rule_text(kind, offer["app"], verb),
+ "still_asks": still_asks,
+ }
diff --git a/dodaios/ui/web/agent_chat_routes.py b/dodaios/ui/web/agent_chat_routes.py
index b5cada7bb5..c1e8995f46 100644
--- a/dodaios/ui/web/agent_chat_routes.py
+++ b/dodaios/ui/web/agent_chat_routes.py
@@ -12,7 +12,10 @@ Prefix ``/api/agent-chat``:
DELETE /sessions/{id}
POST /sessions/{id}/messages {text, attachments} -> starts a turn
POST /sessions/{id}/cancel
- POST /sessions/{id}/approvals/{aid} {decision: allow | allow_always | deny}
+ POST /sessions/{id}/approvals/{aid} {decision: allow | allow_always | deny,
+ scope?: agent | chat, breadth?: action | app}
+ POST /sessions/{id}/approvals/{aid}/rule {kind: always_allow | require_approval,
+ scope, breadth} -> a rule from a settled card
POST /sessions/{id}/questions/{qid} {index, option_index} or {index, text} -> answer
one question of an agent's card
POST /sessions/{id}/questions/{qid}/skip close the card: recommendations apply
@@ -70,6 +73,8 @@ from dodaios.agent_chat.permissions import (
)
from dodaios.agent_chat.service import (
DECISIONS,
+ RULE_BREADTHS,
+ RULE_SCOPES,
AgentChatService,
NoSuchSession,
SessionBusy,
@@ -266,6 +271,15 @@ class MessageBody(BaseModel):
class ApprovalBody(BaseModel):
decision: str
+ #: Where an "Always allow" lives (the card's rule chooser); empty = as before.
+ scope: str = ""
+ breadth: str = ""
+
+
+class ApprovalRuleBody(BaseModel):
+ kind: str
+ scope: str
+ breadth: str = "action"
class CredentialBody(BaseModel):
@@ -1336,7 +1350,15 @@ async def resolve_approval(
svc = (await _async_service(request))
if body.decision not in DECISIONS:
raise HTTPException(status_code=400, detail=f"decision must be one of {list(DECISIONS)}")
- ok = svc.resolve_approval(session_id, approval_id, body.decision)
+ if body.scope and body.scope not in RULE_SCOPES:
+ raise HTTPException(status_code=400, detail=f"scope must be one of {list(RULE_SCOPES)}")
+ if body.breadth and body.breadth not in RULE_BREADTHS:
+ raise HTTPException(
+ status_code=400, detail=f"breadth must be one of {list(RULE_BREADTHS)}"
+ )
+ ok = svc.resolve_approval(
+ session_id, approval_id, body.decision, scope=body.scope, breadth=body.breadth
+ )
if not ok:
if await svc.close_stale_approval(session_id, approval_id):
# The card outlived what it asked for (an app restart, a second
@@ -1352,6 +1374,29 @@ async def resolve_approval(
return {"ok": True, "approval_id": approval_id, "decision": body.decision}
[email protected]("/sessions/{session_id}/approvals/{approval_id}/rule")
+async def save_approval_rule(
+ session_id: str, approval_id: str, body: ApprovalRuleBody, request: Request
+) -> dict[str, Any]:
+ """Turn a card into a standing rule after the fact ("Always allow next time")."""
+ svc = await _async_service(request)
+ if body.kind not in ("always_allow", "require_approval"):
+ raise HTTPException(status_code=400, detail="kind must be always_allow or require_approval")
+ if body.breadth not in RULE_BREADTHS:
+ raise HTTPException(status_code=400, detail="breadth must be action or app")
+ try:
+ rule = await svc.save_approval_rule(
+ session_id, approval_id, kind=body.kind, scope=body.scope, breadth=body.breadth
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except KeyError as exc:
+ raise HTTPException(status_code=404, detail="no such approval card") from exc
+ except LookupError as exc:
+ raise HTTPException(status_code=409, detail="no rule fits this card here") from exc
+ return {"ok": True, "approval_id": approval_id, "rule": rule}
+
+
@router.post(
"/sessions/{session_id}/questions/{question_id}",
summary="Answer an agent's multiple-choice question",
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx
index be9ec3ea73..501ad14082 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/CredentialCard.tsx
@@ -1,9 +1,9 @@
import { memo, useId, useRef, useState, type FormEvent } from "react";
-import { Check, KeyRound, ShieldCheck, X } from "lucide-react";
+import { KeyRound, ShieldCheck, X } from "lucide-react";
import { fill, useT } from "@/i18n";
-import { cn } from "@/lib/utils";
import { AgentChatApiError, declineAgentChatCredential, submitAgentChatCredential, type CredentialResult } from "@/lib/agentChatApi";
import { useAgentChat } from "./AgentChatStoreContext";
+import { ActionCard } from "./actionCard/ActionCard";
import type { CredentialState } from "./reduce";
/**
@@ -85,37 +85,31 @@ function OpenCard({ credential, descriptionId }: { credential: CredentialState;
if (resolved) return <ClosedCard credential={{ ...credential, status: resolved }} />;
+ // The shared action card frame: the source says a secure field is asking,
+ // the field and its two answers sit where every card keeps its actions.
return (
- <section
- role="group"
- aria-label={t("credential_card.aria")}
- aria-describedby={descriptionId}
- data-testid="credential-card"
- data-state="open"
- className="w-full rounded-2xl border border-border bg-card p-4 text-foreground shadow-sm"
- >
- <header className="flex items-start gap-3">
- <div className="min-w-0 flex-1">
- <h3 className="text-sm font-semibold leading-6 [overflow-wrap:anywhere]">{credential.label}</h3>
- {credential.replace ? (
- <p className="mt-1 text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]">
- {fill(t("credential_card.replace_note"), { agent })}
- </p>
- ) : null}
- </div>
+ <ActionCard
+ id={`credential:${credential.requestId}`}
+ testId="credential-card"
+ state="open"
+ source={{ icon: <KeyRound strokeWidth={1.75} />, label: t("action_card.source.secure_field") }}
+ title={credential.label}
+ ariaLabel={t("credential_card.aria")}
+ lines={credential.replace ? [fill(t("credential_card.replace_note"), { agent })] : undefined}
+ trailing={
<button
type="button"
onClick={() => void run((sid) => declineAgentChatCredential(sid, credential.requestId), "declined")}
disabled={busy}
aria-label={t("credential_card.decline")}
title={t("credential_card.decline")}
- className="-mr-1 -mt-0.5 shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
+ className="action-card-dismiss"
>
- <X aria-hidden className="h-5 w-5" />
+ <X aria-hidden className="h-4 w-4" />
</button>
- </header>
-
- <form onSubmit={submit} className="mt-4 flex flex-col gap-2 sm:flex-row">
+ }
+ >
+ <form onSubmit={submit} aria-describedby={descriptionId} className="flex flex-col gap-2 sm:flex-row">
<input
type="password"
value={value}
@@ -133,34 +127,30 @@ function OpenCard({ credential, descriptionId }: { credential: CredentialState;
aria-label={credential.label}
aria-invalid={Boolean(error)}
aria-describedby={error ? `${descriptionId} ${errorId}` : descriptionId}
- className="min-w-0 flex-1 rounded-xl border border-border bg-background px-4 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"
+ className="h-[34px] min-w-0 flex-1 rounded-lg border border-border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"
/>
<button
type="submit"
disabled={busy || !value.trim()}
- className={cn(
- "shrink-0 rounded-xl px-4 py-2.5 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- "bg-primary text-primary-foreground hover:opacity-90",
- "disabled:bg-secondary disabled:text-muted-foreground disabled:hover:opacity-100",
- )}
+ className="action-card-button h-[34px] justify-center"
+ data-tone="primary"
>
{busy ? t("credential_card.saving") : t("credential_card.save")}
</button>
</form>
-
- <footer className="mt-3 space-y-1 text-xs leading-5 text-muted-foreground">
- <p className="flex items-center gap-1.5">
+ <div className="mt-2.5 space-y-0.5 text-xs leading-5 text-muted-foreground">
+ <p className="m-0 flex items-center gap-1.5">
<ShieldCheck aria-hidden className="h-3.5 w-3.5 shrink-0" />
<span>{t("credential_card.footer")}</span>
</p>
- <p>{t("credential_card.stays_open")}</p>
+ <p className="m-0">{t("credential_card.stays_open")}</p>
{error ? (
- <p id={errorId} role="alert" className="text-destructive">
+ <p id={errorId} role="alert" className="m-0 text-destructive">
{error}
</p>
) : null}
- </footer>
- </section>
+ </div>
+ </ActionCard>
);
}
@@ -168,17 +158,16 @@ function ClosedCard({ credential }: { credential: CredentialState }) {
const t = useT();
const saved = credential.status === "saved";
const key = saved ? "saved" : credential.status === "declined" ? "declined" : credential.status === "timeout" ? "timeout" : "cancelled";
+ const sentence = fill(t(`credential_card.${key}`), { label: credential.label, env: credential.env });
return (
- <div
- role="status"
- data-testid="credential-card"
- data-state={credential.status ?? ""}
- className="my-1 flex w-full max-w-2xl items-center gap-2 rounded-xl border border-border px-4 py-2.5 text-sm text-muted-foreground"
- >
- {saved ? <Check aria-hidden className="h-4 w-4 shrink-0 text-primary" /> : <KeyRound aria-hidden className="h-4 w-4 shrink-0" />}
- <span className="min-w-0 [overflow-wrap:anywhere]">
- {fill(t(`credential_card.${key}`), { label: credential.label, env: credential.env })}
- </span>
- </div>
+ <ActionCard
+ id={`credential:${credential.requestId}`}
+ testId="credential-card"
+ state={credential.status ?? ""}
+ source={{ icon: <KeyRound strokeWidth={1.75} />, label: t("action_card.source.secure_field") }}
+ title={credential.label}
+ ariaLabel={sentence}
+ settled={{ tone: saved ? "success" : "muted", label: sentence }}
+ />
);
}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
index 74e7f0c6ba..610c5c29c3 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
@@ -3,14 +3,14 @@ import { BookmarkPlus, CircleAlert, Clock3, Feather, NotebookPen, SlidersHorizon
import { ChatMarkdown } from "./ChatMarkdown";
import { CredentialCard } from "./CredentialCard";
import { QuestionCard } from "./QuestionCard";
-import type { ApprovalDecision } from "@/lib/agentChatApi";
+import { ApprovalActionCard, type ApprovalDecide } from "./actionCard/ApprovalActionCard";
import type { TurnItem } from "./reduce";
import { actionNoticeOf, type ActionNotice } from "./messengerPresence";
import { BotStage, useDoneFlourish } from "./botStage/BotStage";
import { ActivityLine } from "./activity/ActivityLine";
import type { NameOf } from "./activity/activityModel";
import { WorkDisclosure } from "./activity/WorkDisclosure";
-import { ApprovalPrompt, PROSE, THREAD_MEDIA } from "@/components/agentic/threads/ThreadTimeline";
+import { PROSE, THREAD_MEDIA } from "@/components/agentic/threads/ThreadTimeline";
import { SubagentCard } from "@/components/agentic/threads/ThreadSubagents";
import { isSubagentCall } from "@/components/agentic/threads/subagents";
import { useT } from "@/i18n";
@@ -34,7 +34,7 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,
avatar: ReactNode;
/** The agent's colour, for the accents of the scenes. */
color: string;
- onDecide: (approvalId: string, decision: ApprovalDecision) => void | Promise<void>;
+ onDecide: ApprovalDecide;
/** Memory receipts posted after the turn: each a "Noted" quill line that opens the file. */
memoryLinks?: MemoryLink[];
/** A teammate's roster id or name → the name the activity line says. */
@@ -61,7 +61,8 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,
if (block.kind !== "tool") return null;
if (block.credential) return <CredentialCard key={block.callId} credential={block.credential} />;
if (block.question) return <QuestionCard key={block.callId} question={block.question} />;
- if (block.approval && block.approval.decision === null) return <ApprovalPrompt key={block.callId} block={block} onDecide={onDecide} />;
+ // Open, the card asks; answered, it stays as the one line that says what happened.
+ if (block.approval) return <ApprovalActionCard key={block.callId} block={block} onDecide={onDecide} />;
if (isSubagentCall(block)) return <SubagentCard key={block.callId} block={block} turn={turn} />;
const notice = actionNoticeOf(block);
if (!notice) return null;
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.css b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.css
new file mode 100644
index 0000000000..a50edf845c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.css
@@ -0,0 +1,289 @@
+/* The action card (ActionCard.tsx). Built from the theme's own tokens only:
+ surfaces from the ladder, ink from the four ink steps, status from the
+ semantic set. No literal colour, no surface token with opacity. */
+
+.action-card-wrap {
+ width: 100%;
+ max-width: 42rem;
+ min-width: 0;
+}
+
+.action-card {
+ position: relative;
+ border: 1px solid hsl(var(--border));
+ border-radius: calc(var(--radius) + 2px);
+ background: hsl(var(--card));
+ color: hsl(var(--card-foreground));
+ padding: 12px 14px 12px;
+ box-shadow: 0 1px 2px rgb(var(--scrim-rgb) / 0.06);
+ animation: action-card-in 160ms ease-out;
+}
+
+/* A waiting card is the one thing in the chat that needs the person: one
+ strong hairline on its leading edge says so without shouting. */
+.action-card::before {
+ content: "";
+ position: absolute;
+ inset: 10px auto 10px -1px;
+ width: 2px;
+ border-radius: 2px;
+ background: hsl(var(--primary));
+}
+
+.action-card-tile {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border-radius: 6px;
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground-secondary));
+}
+.action-card-tile svg {
+ width: 13px;
+ height: 13px;
+}
+.action-card-tile .tool-choice-icon svg,
+.action-card-tile .tool-choice-icon img {
+ width: 14px;
+ height: 14px;
+}
+.action-card-tile-sm {
+ width: 18px;
+ height: 18px;
+ border-radius: 5px;
+}
+.action-card-tile-sm svg {
+ width: 12px;
+ height: 12px;
+}
+
+.action-card-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ height: 30px;
+ padding: 0 12px;
+ border-radius: 8px;
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1;
+ white-space: nowrap;
+ transition: background-color 120ms ease, color 120ms ease, border-color 120ms ease, opacity 120ms ease;
+}
+.action-card-button:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--background)), 0 0 0 4px hsl(var(--ring));
+}
+.action-card-button:disabled {
+ cursor: default;
+ opacity: 0.5;
+}
+.action-card-button[data-tone="primary"] {
+ background: hsl(var(--primary));
+ color: hsl(var(--primary-foreground));
+}
+.action-card-button[data-tone="primary"]:not(:disabled):hover {
+ opacity: 0.88;
+}
+.action-card-button[data-tone="secondary"] {
+ border: 1px solid hsl(var(--border));
+ background: hsl(var(--card));
+ color: hsl(var(--foreground));
+}
+.action-card-button[data-tone="secondary"]:not(:disabled):hover {
+ border-color: hsl(var(--border-strong));
+ background: hsl(var(--secondary));
+}
+.action-card-button[data-tone="tertiary"] {
+ color: hsl(var(--muted-foreground));
+ padding: 0 10px;
+}
+.action-card-button[data-tone="tertiary"]:not(:disabled):hover {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground));
+}
+.action-card-button-compact {
+ height: 24px;
+ padding: 0 8px;
+ border-radius: 6px;
+ font-size: 11px;
+}
+
+.action-card-code {
+ position: relative;
+ margin-top: 6px;
+ border-radius: 8px;
+ background: hsl(var(--surface-raised));
+ color: hsl(var(--foreground));
+}
+.action-card-code pre {
+ margin: 0;
+ max-height: 14rem;
+ overflow: auto;
+ padding: 8px 36px 8px 10px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12px;
+ line-height: 18px;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.action-card-copy {
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ border-radius: 6px;
+ color: hsl(var(--muted-foreground));
+ transition: background-color 120ms ease, color 120ms ease;
+}
+.action-card-copy:hover {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground));
+}
+.action-card-copy:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+
+.action-card-caution {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+ margin: 6px 2px 0;
+ font-size: 12px;
+ line-height: 18px;
+ color: hsl(var(--warning));
+}
+.action-card-caution svg {
+ margin-top: 2px;
+}
+
+.action-card-settled {
+ border: 1px solid hsl(var(--border));
+ border-radius: calc(var(--radius) - 2px);
+ background: hsl(var(--background));
+ padding: 6px 10px;
+}
+.action-card-settled-body {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-top: 6px;
+ padding: 0 0 2px 26px;
+}
+
+.action-card-dot {
+ flex-shrink: 0;
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: hsl(var(--muted-foreground));
+}
+.action-card-dot[data-tone="success"] {
+ background: hsl(var(--success));
+}
+.action-card-dot[data-tone="danger"] {
+ background: hsl(var(--destructive));
+}
+.action-card-dot[data-tone="warning"] {
+ background: hsl(var(--warning));
+}
+
+.action-card-receipt {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 11px;
+ color: hsl(var(--muted-foreground));
+}
+.action-card-receipt svg {
+ width: 12px;
+ height: 12px;
+ color: hsl(var(--success));
+}
+
+/* The rule chooser inside an open card. */
+.action-card-rule {
+ border-radius: 10px;
+ background: hsl(var(--secondary));
+ padding: 10px 12px;
+}
+.action-card-segments {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ padding: 2px;
+ border-radius: 8px;
+ background: hsl(var(--background));
+ border: 1px solid hsl(var(--border));
+}
+.action-card-segment {
+ height: 24px;
+ padding: 0 10px;
+ border-radius: 6px;
+ font-size: 12px;
+ color: hsl(var(--muted-foreground));
+ transition: background-color 120ms ease, color 120ms ease;
+}
+.action-card-segment:hover {
+ color: hsl(var(--foreground));
+}
+.action-card-segment[aria-checked="true"] {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground-strong));
+ font-weight: 500;
+}
+.action-card-segment:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+
+.action-card-dismiss {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+ color: hsl(var(--muted-foreground));
+ transition: background-color 120ms ease, color 120ms ease;
+}
+.action-card-dismiss:hover {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground));
+}
+.action-card-dismiss:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+.action-card-dismiss:disabled {
+ opacity: 0.5;
+}
+
+@keyframes action-card-in {
+ from {
+ opacity: 0;
+ transform: translateY(2px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .action-card {
+ animation: none;
+ }
+ .action-card-wrap *,
+ .action-card-wrap *::before {
+ transition: none !important;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.tsx
new file mode 100644
index 0000000000..55ecb4e9eb
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ActionCard.tsx
@@ -0,0 +1,229 @@
+import { useEffect, useId, useRef, useState, type ReactNode, type Ref } from "react";
+import { Check, ChevronDown, CircleAlert, Copy, Loader2 } from "lucide-react";
+import { useT } from "@/i18n";
+import { robustCopy } from "@/lib/clipboard";
+import { cn } from "@/lib/utils";
+import "./ActionCard.css";
+
+/**
+ * One card for everything that waits on the person: a tool approval, a
+ * secure field, a change an agent proposes. Each kind is a thin skin that
+ * maps its data onto these props; the frame, the order of things and the
+ * settled one-liner are the same everywhere, so a person learns them once.
+ *
+ * source chip ─────────────────────────── trailing (dismiss)
+ * Title, as a question
+ * subtitle lines (where · what · why · context)
+ * ▸ disclosure with the exact command, copyable
+ * free body
+ * failure note / answered note
+ * [primary] [secondary] [tertiary]
+ * ⚠ caution caption, under the card
+ *
+ * Settled, the card folds into one line: source icon, a status dot, the
+ * outcome and a quiet detail, with a chevron when there is more to read.
+ */
+
+export type ActionTone = "primary" | "secondary" | "tertiary";
+
+export interface ActionSpec {
+ id: string;
+ label: string;
+ tone: ActionTone;
+ onSelect: () => void;
+ disabled?: boolean;
+ /** Why the action is disabled, as its tooltip. */
+ reason?: string;
+ /** A tooltip for the enabled action. */
+ hint?: string;
+ icon?: ReactNode;
+ keyShortcut?: string;
+ testId?: string;
+}
+
+export type SettledTone = "success" | "danger" | "muted" | "warning";
+
+export interface SettledSpec {
+ tone: SettledTone;
+ label: string;
+ /** What it was about, after a " · ". */
+ detail?: string;
+ /** Read when the line is expanded. */
+ body?: ReactNode;
+ /** Small actions that stay available on the settled line ("Always allow next time"). */
+ actions?: ActionSpec[];
+ /** Shown beside the actions once one of them did its job ("Rule saved"). */
+ receipt?: ReactNode;
+}
+
+export interface ActionCardProps {
+ /** A stable id for this card: remembers whether its settled line is open. */
+ id: string;
+ source: { icon: ReactNode; label: string; showLabel?: boolean };
+ title: ReactNode;
+ /** The accessible name, "Needs approval: Run this command?". */
+ ariaLabel: string;
+ /** Subtitle lines in their fixed order: where, what, why, context. */
+ lines?: ReactNode[];
+ disclosure?: { text: string; showLabel: string; hideLabel: string; defaultOpen?: boolean };
+ children?: ReactNode;
+ failure?: string | null;
+ note?: ReactNode;
+ actions?: ActionSpec[];
+ /** The action in flight: it spins, every other one waits. */
+ pending?: string | null;
+ trailing?: ReactNode;
+ /** An already worded caution, shown under the card. */
+ caution?: string | null;
+ settled?: SettledSpec | null;
+ testId?: string;
+ state?: string;
+ rootRef?: Ref<HTMLDivElement>;
+ className?: string;
+}
+
+/** Which settled cards the person opened, across remounts (a virtualized list, a fold). */
+const openSettled = new Map<string, boolean>();
+
+export function ActionCard(props: ActionCardProps) {
+ if (props.settled) return <SettledCard {...props} settled={props.settled} />;
+ return <OpenCard {...props} />;
+}
+
+function OpenCard({
+ source, title, ariaLabel, lines, disclosure, children, failure, note, actions = [], pending = null, trailing, caution,
+ testId, state = "open", rootRef, className,
+}: ActionCardProps) {
+ const titleId = useId();
+ const lead = actions.filter((a) => a.tone !== "tertiary");
+ const tail = actions.filter((a) => a.tone === "tertiary");
+ return <div className={cn("action-card-wrap", className)} data-testid={testId} data-state={state}>
+ <div ref={rootRef} role="group" aria-label={ariaLabel} aria-busy={pending !== null || undefined}
+ className="action-card" data-action-card="open">
+ <div className="flex items-center gap-2">
+ <SourceChip icon={source.icon} label={source.label} showLabel={source.showLabel !== false} />
+ {trailing ? <div className="-mr-1.5 ml-auto flex shrink-0 items-center">{trailing}</div> : null}
+ </div>
+ <h3 id={titleId} className="mt-2 text-sm font-semibold leading-5 text-foreground-strong [overflow-wrap:anywhere]">{title}</h3>
+ {lines?.filter(Boolean).length ? <div className="mt-0.5 space-y-0.5">
+ {lines.filter(Boolean).map((line, i) => <p key={i} className="m-0 text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]">{line}</p>)}
+ </div> : null}
+ {disclosure?.text ? <Disclosure {...disclosure} /> : null}
+ {children ? <div className="mt-2.5 min-w-0">{children}</div> : null}
+ {failure ? <p role="alert" className="mt-2.5 flex items-start gap-1.5 text-xs leading-5 text-destructive">
+ <CircleAlert aria-hidden className="mt-0.5 h-3.5 w-3.5 shrink-0" /><span>{failure}</span>
+ </p> : null}
+ {note ? <p className="mt-2 text-xs leading-5 text-muted-foreground">{note}</p> : null}
+ {actions.length ? <div className="mt-3 flex flex-wrap items-center gap-2">
+ {lead.map((a) => <ActionButton key={a.id} action={a} pending={pending} />)}
+ {tail.length ? <div className="ml-auto flex flex-wrap items-center gap-1">
+ {tail.map((a) => <ActionButton key={a.id} action={a} pending={pending} />)}
+ </div> : null}
+ </div> : null}
+ </div>
+ {caution ? <p className="action-card-caution" data-testid="action-card-caution">
+ <CircleAlert aria-hidden className="h-3.5 w-3.5 shrink-0" /><span>{caution}</span>
+ </p> : null}
+ </div>;
+}
+
+function SettledCard({ id, source, ariaLabel, lines, disclosure, children, settled, testId, state, rootRef, className }:
+ ActionCardProps & { settled: SettledSpec }) {
+ const t = useT();
+ const bodyId = useId();
+ const expandable = Boolean(lines?.filter(Boolean).length || disclosure?.text || children || settled.body);
+ const [open, setOpen] = useState(() => openSettled.get(id) ?? false);
+ const toggle = () => setOpen((was) => {
+ openSettled.set(id, !was);
+ return !was;
+ });
+ const sentence = <>
+ <span className={cn("action-card-dot")} data-tone={settled.tone} aria-hidden />
+ <span className={cn("shrink-0", settled.tone === "danger" ? "text-destructive" : "text-foreground-secondary")}>{settled.label}</span>
+ {settled.detail ? <span className="min-w-0 truncate text-muted-foreground">{` · ${settled.detail}`}</span> : null}
+ </>;
+ const extras = settled.actions?.length || settled.receipt
+ ? <div className="flex shrink-0 flex-wrap items-center gap-1">
+ {settled.receipt}
+ {settled.actions?.map((a) => <ActionButton key={a.id} action={a} pending={null} compact />)}
+ </div>
+ : null;
+ return <div className={cn("action-card-wrap", className)} data-testid={testId} data-state={state} aria-label={ariaLabel}
+ role={expandable ? "group" : "status"}>
+ <div ref={rootRef} className="action-card-settled" data-action-card="settled" data-tone={settled.tone}>
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="action-card-tile action-card-tile-sm" aria-hidden>{source.icon}</span>
+ {expandable
+ ? <button type="button" onClick={toggle} aria-expanded={open} aria-controls={bodyId}
+ title={open ? t("action_card.collapse") : t("action_card.expand")}
+ className="flex min-w-0 flex-1 items-center gap-2 rounded-md text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {sentence}
+ <ChevronDown aria-hidden className={cn("ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150", open && "rotate-180")} />
+ </button>
+ : <p className="m-0 flex min-w-0 flex-1 items-center gap-2 text-xs">{sentence}</p>}
+ {extras}
+ </div>
+ {expandable && open ? <div id={bodyId} className="action-card-settled-body">
+ {lines?.filter(Boolean).map((line, i) => <p key={i} className="m-0 text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]">{line}</p>)}
+ {disclosure?.text ? <Disclosure {...disclosure} defaultOpen /> : null}
+ {children}
+ {settled.body}
+ </div> : null}
+ </div>
+ </div>;
+}
+
+export function SourceChip({ icon, label, showLabel = true }: { icon: ReactNode; label: string; showLabel?: boolean }) {
+ return <span className="flex min-w-0 items-center gap-1.5" title={showLabel ? undefined : label}>
+ <span className="action-card-tile" aria-hidden>{icon}</span>
+ {showLabel ? <span className="truncate text-xs font-medium text-muted-foreground">{label}</span> : <span className="sr-only">{label}</span>}
+ </span>;
+}
+
+function ActionButton({ action, pending, compact = false }: { action: ActionSpec; pending: string | null; compact?: boolean }) {
+ const busy = pending === action.id;
+ const disabled = Boolean(action.disabled) || (pending !== null && !busy);
+ return <button type="button" onClick={action.onSelect} disabled={disabled || busy}
+ title={action.disabled ? action.reason : action.hint}
+ aria-keyshortcuts={action.keyShortcut}
+ data-tone={action.tone}
+ data-testid={action.testId}
+ className={cn("action-card-button", compact && "action-card-button-compact")}>
+ {busy ? <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin" /> : action.icon}
+ <span>{action.label}</span>
+ </button>;
+}
+
+function Disclosure({ text, showLabel, hideLabel, defaultOpen = false }: NonNullable<ActionCardProps["disclosure"]>) {
+ const [open, setOpen] = useState(defaultOpen);
+ const id = useId();
+ return <div className="mt-2.5 min-w-0">
+ <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open} aria-controls={id}
+ className="flex items-center gap-1 rounded-md text-xs font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <ChevronDown aria-hidden className={cn("h-3.5 w-3.5 transition-transform duration-150", !open && "-rotate-90")} />
+ {open ? hideLabel : showLabel}
+ </button>
+ {open ? <div id={id} className="action-card-code">
+ <pre data-testid="action-card-detail">{text}</pre>
+ <CopyText text={text} />
+ </div> : null}
+ </div>;
+}
+
+function CopyText({ text }: { text: string }) {
+ const t = useT();
+ const [done, setDone] = useState(false);
+ const timer = useRef<number | null>(null);
+ useEffect(() => () => { if (timer.current) window.clearTimeout(timer.current); }, []);
+ const copy = async () => {
+ // The clipboard may be unavailable; the text stays selectable either way.
+ if (!(await robustCopy(text))) return;
+ setDone(true);
+ if (timer.current) window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => setDone(false), 1400);
+ };
+ const label = done ? t("action_card.copied") : t("action_card.copy");
+ return <button type="button" onClick={() => void copy()} aria-label={label} title={label} className="action-card-copy">
+ {done ? <Check aria-hidden className="h-3.5 w-3.5" /> : <Copy aria-hidden className="h-3.5 w-3.5" />}
+ </button>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.test.tsx
new file mode 100644
index 0000000000..6482a40d81
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.test.tsx
@@ -0,0 +1,277 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { createAgentChatStore } from "@/store/agentChat";
+import { AgentChatStoreProvider } from "../AgentChatStoreContext";
+import { MessengerTurn } from "../MessengerTurn";
+import { EMPTY_TIMELINE, reduceEvents, type ToolBlock, type TurnItem } from "../reduce";
+import { ApprovalActionCard } from "./ApprovalActionCard";
+
+let seq = 0;
+function ev(kind: string, payload: Record<string, unknown>): AgentChatEvent {
+ return { seq: ++seq, ts_ms: 1000 + seq, kind, payload } as AgentChatEvent;
+}
+
+afterEach(() => {
+ cleanup();
+ seq = 0;
+ vi.restoreAllMocks();
+});
+
+const GMAIL_CARD = {
+ source: { kind: "connector", app: "Gmail", verb: "send" },
+ where: "",
+ why: "The weekly report is ready",
+ caution: "data_leaves",
+ detail: "{\n \"action\": \"send\",\n \"to\": \"[email protected]\"\n}",
+ rule: { scopes: ["agent", "chat"], chat: "tool", app: "Gmail", verb: "send", pattern: "plugin:gmail:send", broad: "plugin:gmail" },
+};
+
+function asking(approvalId = "a1", extra: Record<string, unknown> = GMAIL_CARD, callId = "c1"): AgentChatEvent[] {
+ return [
+ ev("tool_call", { turn_id: "t1", call_id: callId, name: "gmail", input: { action: "send", to: "[email protected]" } }),
+ ev("approval_required", {
+ turn_id: "t1", approval_id: approvalId, call_id: callId, name: "gmail",
+ input: { action: "send", to: "[email protected]" }, summary: "Send the weekly report to [email protected]", ...extra,
+ }),
+ ];
+}
+
+function turnOf(events: AgentChatEvent[]): TurnItem {
+ const tl = reduceEvents(EMPTY_TIMELINE, [ev("turn_started", { turn_id: "t1" }), ...events]);
+ return tl.items.find((item) => item.type === "turn") as TurnItem;
+}
+
+function blockOf(events: AgentChatEvent[], callId = "c1"): ToolBlock {
+ return turnOf(events).blocks.find((b) => b.kind === "tool" && b.callId === callId) as ToolBlock;
+}
+
+function drawTurn(events: AgentChatEvent[], onDecide = vi.fn()) {
+ const store = createAgentChatStore("society");
+ store.setState({ activeSessionId: "society:ada" });
+ const view = (current: AgentChatEvent[]) => <AgentChatStoreProvider store={store}>
+ <MessengerTurn turn={turnOf(current)} avatar={<span />} color="#888888" onDecide={onDecide} />
+ </AgentChatStoreProvider>;
+ const rendered = render(view(events));
+ return { store, onDecide, rerender: (current: AgentChatEvent[]) => rendered.rerender(view(current)) };
+}
+
+describe("the approval action card", () => {
+ it("asks in plain words with the source, the reason, the caution and Allow once first", async () => {
+ const { onDecide } = drawTurn(asking());
+ const card = screen.getByTestId("thread-approval");
+ expect(card.textContent).toContain("Gmail");
+ expect(screen.getByRole("heading", { name: "Use Gmail to send?" })).toBeTruthy();
+ expect(card.textContent).toContain("Send the weekly report");
+ expect(card.textContent).toContain("“The weekly report is ready”");
+ expect(screen.getByTestId("action-card-caution").textContent).toBe("This sends data outside this chat.");
+ const buttons = [...card.querySelectorAll("button[data-tone]")].map((b) => [b.textContent, b.getAttribute("data-tone")]);
+ expect(buttons).toEqual([["Allow once", "primary"], ["Always allow…", "secondary"], ["Deny", "tertiary"]]);
+ expect(screen.getByRole("group", { name: "Needs approval: Use Gmail to send?" })).toBeTruthy();
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-allow")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow");
+ });
+
+ it("shows the exact request behind a disclosure, copyable", () => {
+ drawTurn(asking());
+ expect(screen.queryByTestId("action-card-detail")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Show details" }));
+ expect(screen.getByTestId("action-card-detail").textContent).toContain("[email protected]");
+ expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy();
+ });
+
+ it("opens a command's disclosure by default", () => {
+ drawTurn([
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "Bash", input: { command: "rm -rf build" },
+ summary: "rm -rf build", source: { kind: "terminal" }, where: "C:/work/app", why: "", caution: "irreversible",
+ detail: "rm -rf build", rule: { scopes: ["chat"], chat: "all" },
+ }),
+ ]);
+ expect(screen.getByRole("heading", { name: "Run this command?" })).toBeTruthy();
+ expect(screen.getByText("In C:/work/app")).toBeTruthy();
+ expect(screen.getByTestId("action-card-detail").textContent).toBe("rm -rf build");
+ expect(screen.getByTestId("action-card-caution").textContent).toBe("This can't be undone.");
+ // A chat-wide "always" says honestly what it does.
+ expect(screen.getByTestId("action-card-always").getAttribute("title")).toBe("Stops asking for anything in this chat.");
+ });
+
+ it("turns Always allow into a readable rule the person scopes before saving", async () => {
+ const { onDecide } = drawTurn(asking());
+ fireEvent.click(screen.getByTestId("action-card-always"));
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow “send” with Gmail");
+ fireEvent.click(screen.getByRole("radio", { name: "All of Gmail" }));
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow Gmail");
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-rule-save")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always", { scope: "agent", breadth: "app" });
+ });
+
+ it("saves an always for this chat only", async () => {
+ const { onDecide } = drawTurn(asking());
+ fireEvent.click(screen.getByTestId("action-card-always"));
+ fireEvent.click(screen.getByRole("radio", { name: "This chat" }));
+ expect(screen.queryByRole("radio", { name: "All of Gmail" })).toBeNull();
+ expect(screen.getByText("Stops asking in this chat until the app restarts.")).toBeTruthy();
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-rule-save")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always", { scope: "chat", breadth: "action" });
+ });
+
+ it("never offers an always on a plan", () => {
+ drawTurn([
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "ExitPlanMode",
+ input: { plan: "1. Add the table" }, summary: "Plan ready", source: { kind: "plan" }, rule: null,
+ }),
+ ]);
+ expect(screen.queryByTestId("action-card-always")).toBeNull();
+ expect(screen.getByText("Start building")).toBeTruthy();
+ expect(screen.getByText("Add the table")).toBeTruthy();
+ });
+
+ it("keeps working on an event written before the card fields existed", async () => {
+ const { onDecide } = drawTurn([
+ ev("approval_required", { turn_id: "t1", approval_id: "a1", call_id: "c1", name: "Bash", input: { command: "ls" }, summary: "ls" }),
+ ]);
+ expect(screen.getByRole("heading", { name: "Run this command?" })).toBeTruthy();
+ expect(screen.getByTestId("action-card-always").textContent).toBe("Always allow");
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-always")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always");
+ });
+
+ it("says why an answer did not go through and lets the person try again", async () => {
+ const onDecide = vi.fn().mockRejectedValueOnce(new Error("server error"));
+ drawTurn(asking(), onDecide);
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-allow")); });
+ expect(screen.getByRole("alert").textContent).toContain("server error");
+ expect((screen.getByTestId("action-card-allow") as HTMLButtonElement).disabled).toBe(false);
+ });
+});
+
+describe("Esc on an approval card", () => {
+ it("denies once, and only the newest open card", async () => {
+ const onDecide = vi.fn();
+ drawTurn([...asking("old", GMAIL_CARD, "c1"), ...asking("new", GMAIL_CARD, "c2")], onDecide);
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+ expect(onDecide).toHaveBeenCalledTimes(1);
+ expect(onDecide).toHaveBeenCalledWith("new", "deny");
+ });
+
+ it("leaves a key meant for a text field, a modifier or a repeat alone", async () => {
+ const onDecide = vi.fn();
+ drawTurn(asking(), onDecide);
+ const field = document.createElement("textarea");
+ document.body.appendChild(field);
+ await act(async () => {
+ fireEvent.keyDown(field, { key: "Escape" });
+ fireEvent.keyDown(window, { key: "Escape", ctrlKey: true });
+ fireEvent.keyDown(window, { key: "Escape", repeat: true });
+ });
+ field.remove();
+ expect(onDecide).not.toHaveBeenCalled();
+ });
+
+ it("first backs out of the rule chooser", async () => {
+ const onDecide = vi.fn();
+ drawTurn(asking(), onDecide);
+ fireEvent.click(screen.getByTestId("action-card-always"));
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+ expect(screen.queryByTestId("action-card-rule")).toBeNull();
+ expect(onDecide).not.toHaveBeenCalled();
+ });
+
+ it("does nothing once the card is answered", async () => {
+ const onDecide = vi.fn();
+ drawTurn([...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow" })], onDecide);
+ await act(async () => { fireEvent.keyDown(window, { key: "Escape" }); });
+ expect(onDecide).not.toHaveBeenCalled();
+ });
+});
+
+describe("a settled approval", () => {
+ it("stays as one outcome line rebuilt from the event log", () => {
+ drawTurn([
+ ...asking(),
+ ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow_always", scope: "agent" }),
+ ev("notice", {
+ kind: "approval_rule", turn_id: "t1", approval_id: "a1", rule_kind: "always_allow", scope: "agent",
+ pattern: "plugin:gmail:send", app: "Gmail", verb: "send", still_asks: false,
+ }),
+ ]);
+ const line = screen.getByTestId("approval-outcome");
+ expect(line.getAttribute("data-state")).toBe("allow_always");
+ expect(line.textContent).toContain("Always allowed");
+ expect(line.textContent).toContain("Send the weekly report");
+ expect(screen.getByTestId("action-card-rule-saved").getAttribute("title")).toBe("Rule saved: Always allow “send” with Gmail");
+ // The rule notice patched the card; it never became a line of its own.
+ expect(screen.queryAllByTestId("approval-outcome")).toHaveLength(1);
+ expect(screen.queryByTestId("thread-approval")).toBeNull();
+ });
+
+ it("reads a denial in danger ink and opens to what was asked", () => {
+ drawTurn([...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "deny" })]);
+ const toggle = screen.getByRole("button", { name: /Denied/ });
+ expect(toggle.getAttribute("aria-expanded")).toBe("false");
+ fireEvent.click(toggle);
+ expect(screen.getByText("The agent was told no and did not do it.")).toBeTruthy();
+ expect(screen.getByTestId("action-card-detail").textContent).toContain("[email protected]");
+ });
+
+ it("offers Always allow next time on an expired card and saves it as a rule", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({
+ ok: true, approval_id: "a1",
+ rule: { kind: "always_allow", pattern: "plugin:gmail:send", app: "Gmail", verb: "send", still_asks: false },
+ }), { status: 200 }));
+ const { store, rerender } = drawTurn([...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "expired" })]);
+ store.setState({ timeline: reduceEvents(EMPTY_TIMELINE, [ev("turn_started", { turn_id: "t1" }), ...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "expired" })]) });
+ expect(screen.getByText("Expired")).toBeTruthy();
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-always-next")); });
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("/api/agent-chat/sessions/society%3Aada/approvals/a1/rule");
+ expect(JSON.parse(String(init.body))).toEqual({ kind: "always_allow", scope: "agent", breadth: "action" });
+ const patched = store.getState().timeline.items.find((i) => i.type === "turn") as TurnItem;
+ const block = patched.blocks.find((b) => b.kind === "tool") as ToolBlock;
+ expect(block.approval?.rule).toMatchObject({ kind: "always_allow", scope: "agent", pattern: "plugin:gmail:send" });
+ rerender([...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "expired" }),
+ ev("notice", { kind: "approval_rule", turn_id: "t1", approval_id: "a1", rule_kind: "always_allow", scope: "agent", pattern: "plugin:gmail:send", app: "Gmail", verb: "send" })]);
+ await waitFor(() => expect(screen.queryByTestId("action-card-always-next")).toBeNull());
+ expect(screen.getByTestId("action-card-rule-saved")).toBeTruthy();
+ });
+
+ it("offers Ask first next time after an agent-wide always", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({
+ ok: true, rule: { kind: "require_approval", pattern: "plugin:gmail:send", app: "Gmail", verb: "send" },
+ }), { status: 200 }));
+ drawTurn([...asking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow_always", scope: "agent" })]);
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-ask-next")); });
+ expect(JSON.parse(String((fetchMock.mock.calls[0] as [string, RequestInit])[1].body))).toEqual({
+ kind: "require_approval", scope: "agent", breadth: "action",
+ });
+ });
+});
+
+describe("secrets in the disclosure", () => {
+ // Built at runtime so no credential-shaped literal sits in the source.
+ const SECRETS = ["hunter2-correct-horse", ["sk", "proj", "q7".repeat(18)].join("-"), "gh" + "p_" + "Z9".repeat(20)];
+
+ it("are masked on an event without the backend's masked detail", () => {
+ drawTurn([
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "mcp__acme__login",
+ input: { user: "ada", password: SECRETS[0], api_key: SECRETS[1], note: `token ${SECRETS[2]}` }, summary: "Sign in",
+ }),
+ ]);
+ fireEvent.click(screen.getByRole("button", { name: "Show details" }));
+ const detail = screen.getByTestId("action-card-detail").textContent ?? "";
+ expect(detail).toContain("ada");
+ for (const secret of SECRETS) expect(detail).not.toContain(secret);
+ for (const secret of SECRETS) expect(document.body.textContent).not.toContain(secret);
+ });
+
+ it("are masked again even if a detail ever carried one", () => {
+ const block = blockOf(asking("a1", { ...GMAIL_CARD, detail: `Authorization: Bearer ${"x".repeat(30)} api_key=${SECRETS[1]}` }));
+ render(<ApprovalActionCard block={block} onDecide={vi.fn()} />);
+ fireEvent.click(screen.getByRole("button", { name: "Show details" }));
+ expect(screen.getByTestId("action-card-detail").textContent).not.toContain(SECRETS[1]);
+ expect(screen.getByTestId("action-card-detail").textContent).not.toContain("x".repeat(30));
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
new file mode 100644
index 0000000000..c863e412be
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
@@ -0,0 +1,295 @@
+import { memo, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { Bot, Check, FilePenLine, Globe, ListChecks, Monitor, Plug, SquareTerminal, Wrench } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import type { ApprovalDecision, ApprovalRuleChoice, ApprovalRuleRequest } from "@/lib/agentChatApi";
+import { ChatMarkdown } from "../ChatMarkdown";
+import { useAgentChat } from "../AgentChatStoreContext";
+import type { ApprovalState, ToolBlock } from "../reduce";
+import { ToolChoiceIcon } from "../ToolChoiceChips";
+import type { ToolChoice } from "../toolChoices";
+import { ActionCard, type ActionSpec, type SettledSpec } from "./ActionCard";
+import { approvalTitle, cardInfoOf, outcomeLabel, outcomeTone, ruleSentence, savedRuleSentence, sourceLabel } from "./approvalCopy";
+import type { ApprovalCardInfo, ApprovalRuleOffer, RuleBreadth, RuleScope } from "./approvalInfo";
+import { claimKeyboardTarget, TARGET_PRIORITY } from "./keyboardTarget";
+
+/** How a surface answers an approval: by its id, the decision, and where an "always" lives. */
+export type ApprovalDecide = (approvalId: string, decision: ApprovalDecision, rule?: ApprovalRuleChoice) => void | Promise<void>;
+
+type T = (key: string) => string;
+
+/**
+ * A tool approval on the action card. Open, it asks in plain words with
+ * "Allow once" first; an "Always allow" that can become a standing rule opens
+ * a small chooser (this agent or this chat, this action or the whole app)
+ * before it saves. Answered, it stays in the chat as one line that says what
+ * happened, rebuilt from the event log after a reload.
+ */
+export const ApprovalActionCard = memo(function ApprovalActionCard({ block, onDecide }: { block: ToolBlock; onDecide?: ApprovalDecide }) {
+ const approval = block.approval;
+ const info = useMemo(() => cardInfoOf(block), [block]);
+ if (!approval) return null;
+ return approval.decision === null
+ ? <OpenApproval key={approval.approvalId} block={block} approval={approval} info={info} onDecide={onDecide} />
+ : <SettledApproval block={block} approval={approval} info={info} />;
+});
+
+const KIND_ICONS = {
+ terminal: SquareTerminal,
+ files: FilePenLine,
+ browser: Globe,
+ computer: Monitor,
+ plan: ListChecks,
+ agent: Bot,
+ tool: Wrench,
+} as const;
+
+function SourceIcon({ info }: { info: ApprovalCardInfo }) {
+ const { kind, app } = info.source;
+ if (kind === "connector") {
+ if (!app) return <Plug strokeWidth={1.75} />;
+ const slug = app.toLowerCase().replace(/\s+/g, "_");
+ const row: ToolChoice = {
+ id: `plugin:${slug}`, label: app, description: "", category: "plugins", group: "", brand: slug,
+ available: true, tool_names: [], skill: "",
+ };
+ return <ToolChoiceIcon row={row} size={14} />;
+ }
+ const Icon = KIND_ICONS[kind];
+ return <Icon strokeWidth={1.75} />;
+}
+
+function subtitleLines(info: ApprovalCardInfo, approval: ApprovalState, title: string, t: T): ReactNode[] {
+ const lines: ReactNode[] = [];
+ const { kind } = info.source;
+ if (info.where) {
+ lines.push(fill(t(kind === "browser" ? "action_card.field.on" : "action_card.field.in"), { where: info.where }));
+ }
+ // A command is read in its own block below; a summary that only repeats it says nothing new.
+ const what = approval.summary.trim();
+ const repeatsCommand = kind === "terminal" && Boolean(info.detail) && info.detail.startsWith(what);
+ if (what && !repeatsCommand && kind !== "plan" && what !== title) lines.push(<span className="text-foreground-secondary">{what}</span>);
+ if (info.why) lines.push(fill(t("action_card.field.why"), { why: info.why }));
+ return lines;
+}
+
+function errorText(err: unknown, t: T): string {
+ return err instanceof Error && err.message ? err.message : t("action_card.failed");
+}
+
+function planText(block: ToolBlock): string {
+ const input = block.input && typeof block.input === "object" ? (block.input as Record<string, unknown>) : {};
+ return typeof input.plan === "string" ? input.plan : "";
+}
+
+function OpenApproval({ block, approval, info, onDecide }: {
+ block: ToolBlock; approval: ApprovalState; info: ApprovalCardInfo; onDecide?: ApprovalDecide;
+}) {
+ const t = useT();
+ const [pending, setPending] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [choosing, setChoosing] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const mounted = useRef(true);
+ useEffect(() => () => { mounted.current = false; }, []);
+ const kind = info.source.kind;
+ const isPlan = kind === "plan";
+ const offer = isPlan ? null : info.rule;
+ const withChooser = Boolean(offer?.scopes.includes("agent"));
+ const title = approvalTitle(info, t);
+
+ const decide = async (decision: ApprovalDecision, rule?: ApprovalRuleChoice) => {
+ if (!onDecide || pending) return;
+ setPending(decision);
+ setError(null);
+ try {
+ if (rule) await onDecide(approval.approvalId, decision, rule);
+ else await onDecide(approval.approvalId, decision);
+ } catch (err) {
+ if (mounted.current) setError(errorText(err, t));
+ } finally {
+ if (mounted.current) setPending(null);
+ }
+ };
+ // Esc answers the newest open approval: back out of the chooser, else deny once.
+ const escape = useRef<() => void>(() => {});
+ escape.current = () => (choosing ? setChoosing(false) : void decide("deny"));
+ useEffect(() => {
+ if (!onDecide) return;
+ return claimKeyboardTarget({ priority: TARGET_PRIORITY.approval, element: () => rootRef.current, onEscape: () => escape.current() });
+ }, [onDecide]);
+
+ const elsewhere = onDecide ? undefined : t("action_card.elsewhere");
+ const chatHint = offer?.chat === "tool" && offer.app
+ ? fill(t("action_card.rule.chat_tool"), { app: offer.app })
+ : offer?.chat === "all" ? t("action_card.rule.chat_all") : undefined;
+ const actions: ActionSpec[] = isPlan
+ ? [
+ { id: "allow", label: t("action_card.plan_build"), tone: "primary", onSelect: () => void decide("allow"), disabled: !onDecide, reason: elsewhere, testId: "action-card-allow" },
+ { id: "deny", label: t("action_card.plan_keep"), tone: "tertiary", onSelect: () => void decide("deny"), disabled: !onDecide, reason: elsewhere, hint: t("action_card.deny_esc"), keyShortcut: "Escape", testId: "action-card-deny" },
+ ]
+ : [
+ { id: "allow", label: t("action_card.allow_once"), tone: "primary", onSelect: () => void decide("allow"), disabled: !onDecide, reason: elsewhere, testId: "action-card-allow" },
+ ...(offer ? [{
+ id: "allow_always", label: withChooser ? t("action_card.always_allow_more") : t("action_card.always_allow"), tone: "secondary" as const,
+ onSelect: () => (withChooser ? setChoosing(true) : void decide("allow_always", offer.scopes.includes("chat") ? { scope: "chat" } : undefined)),
+ disabled: !onDecide, reason: elsewhere, hint: chatHint, testId: "action-card-always",
+ }] : []),
+ { id: "deny", label: t("action_card.deny"), tone: "tertiary", onSelect: () => void decide("deny"), disabled: !onDecide, reason: elsewhere, hint: t("action_card.deny_esc"), keyShortcut: "Escape", testId: "action-card-deny" },
+ ];
+ const plan = isPlan ? planText(block) : "";
+ return <ActionCard
+ id={approval.approvalId}
+ testId="thread-approval"
+ rootRef={rootRef}
+ source={{ icon: <SourceIcon info={info} />, label: sourceLabel(info, t) }}
+ title={title}
+ ariaLabel={`${t("action_card.needs_approval")}: ${title}`}
+ lines={subtitleLines(info, approval, title, t)}
+ disclosure={info.detail ? {
+ text: info.detail,
+ showLabel: t(kind === "terminal" ? "action_card.show_command" : "action_card.show_details"),
+ hideLabel: t(kind === "terminal" ? "action_card.hide_command" : "action_card.hide_details"),
+ defaultOpen: kind === "terminal" && info.detail.length <= 400,
+ } : undefined}
+ failure={error}
+ actions={choosing ? [] : actions}
+ pending={pending}
+ caution={info.caution ? t(`action_card.caution.${info.caution}`) : null}
+ >
+ {plan ? <div className="max-h-72 overflow-auto rounded-lg bg-secondary px-3 py-2 text-sm scrollbar-jarvis"><ChatMarkdown text={plan} /></div> : null}
+ {choosing && offer ? <RuleChooser offer={offer} pending={pending === "allow_always"}
+ onSave={(choice) => void decide("allow_always", choice)} onBack={() => setChoosing(false)} /> : null}
+ </ActionCard>;
+}
+
+/** "Make it a rule": where the "always" lives and how wide it reaches, read back as a sentence. */
+export function RuleChooser({ offer, pending, onSave, onBack }: {
+ offer: ApprovalRuleOffer; pending: boolean; onSave: (choice: ApprovalRuleChoice) => void; onBack: () => void;
+}) {
+ const t = useT();
+ const [scope, setScope] = useState<RuleScope>(offer.scopes.includes("agent") ? "agent" : "chat");
+ const [breadth, setBreadth] = useState<RuleBreadth>("action");
+ const verb = scope === "agent" && breadth === "action" ? offer.verb : "";
+ const sentence = scope === "chat"
+ ? ruleSentence("always_allow", offer.app, "", t)
+ : ruleSentence("always_allow", offer.app, verb, t);
+ return <div className="action-card-rule" data-testid="action-card-rule">
+ <p className="m-0 text-xs font-medium text-foreground">{t("action_card.rule.heading")}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Segments label={t("action_card.rule.scope_label")} value={scope} onChange={setScope}
+ options={offer.scopes.map((s) => ({ value: s, label: t(`action_card.rule.scope_${s}`) }))} />
+ {scope === "agent" && offer.verb ? <Segments label={t("action_card.rule.breadth_label")} value={breadth} onChange={setBreadth}
+ options={[
+ { value: "action", label: fill(t("action_card.rule.breadth_action"), { verb: offer.verb }) },
+ { value: "app", label: fill(t("action_card.rule.breadth_app"), { app: offer.app }) },
+ ]} /> : null}
+ </div>
+ <p className="mt-2.5 text-sm font-medium text-foreground-strong" data-testid="action-card-rule-text">{sentence}</p>
+ <p className="m-0 mt-0.5 text-xs leading-5 text-muted-foreground">
+ {t(scope === "agent" ? "action_card.rule.where_agent" : "action_card.rule.where_chat")}
+ </p>
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <button type="button" className="action-card-button" data-tone="primary" disabled={pending} data-testid="action-card-rule-save"
+ onClick={() => onSave({ scope, breadth: scope === "agent" ? breadth : "action" })}>
+ {t("action_card.rule.save_allow")}
+ </button>
+ <button type="button" className="action-card-button" data-tone="tertiary" disabled={pending} onClick={onBack}>
+ {t("action_card.rule.back")}
+ </button>
+ </div>
+ </div>;
+}
+
+function Segments<V extends string>({ label, value, options, onChange }: {
+ label: string; value: V; options: { value: V; label: string }[]; onChange: (value: V) => void;
+}) {
+ if (options.length < 2) return null;
+ return <div role="radiogroup" aria-label={label} className="action-card-segments">
+ {options.map((option) => <button key={option.value} type="button" role="radio" aria-checked={option.value === value}
+ className="action-card-segment" onClick={() => onChange(option.value)}>
+ {option.label}
+ </button>)}
+ </div>;
+}
+
+function SettledApproval({ block, approval, info }: { block: ToolBlock; approval: ApprovalState; info: ApprovalCardInfo }) {
+ const t = useT();
+ const saveRule = useAgentChat((s) => s.saveApprovalRule);
+ const [saving, setSaving] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const decision = approval.decision ?? "cancel";
+ const title = approvalTitle(info, t);
+ const offer = info.source.kind === "plan" ? null : info.rule;
+ const saved = approval.rule;
+
+ const save = async (id: string, rule: ApprovalRuleRequest) => {
+ if (saving) return;
+ setSaving(id);
+ setError(null);
+ try {
+ await saveRule(approval.approvalId, rule);
+ } catch {
+ setError(t("action_card.rule.save_failed"));
+ } finally {
+ setSaving(null);
+ }
+ };
+ const actions: ActionSpec[] = [];
+ const unanswered = decision === "expired" || decision === "cancel";
+ // A chat-wide "always" that would silence the whole chat is never offered after the fact.
+ const canRemember = Boolean(offer && (offer.scopes.includes("agent") || (offer.scopes.includes("chat") && offer.chat === "tool")));
+ if (unanswered && offer && canRemember && !saved) {
+ const scope: RuleScope = offer.scopes.includes("agent") ? "agent" : "chat";
+ actions.push({
+ id: "always_next", label: t("action_card.rule.always_next_time"), tone: "secondary",
+ hint: ruleSentence("always_allow", offer.app, scope === "agent" ? offer.verb : "", t),
+ onSelect: () => void save("always_next", { kind: "always_allow", scope }), disabled: saving !== null, testId: "action-card-always-next",
+ });
+ }
+ const alwaysOnAgent = decision === "allow_always" && (approval.scope === "agent" || saved?.scope === "agent");
+ if (alwaysOnAgent && offer?.scopes.includes("agent") && saved?.kind !== "require_approval") {
+ const breadth: RuleBreadth = saved && offer.broad && saved.pattern === offer.broad ? "app" : "action";
+ actions.push({
+ id: "ask_next", label: t("action_card.rule.ask_next_time"), tone: "tertiary",
+ hint: ruleSentence("require_approval", offer.app, breadth === "action" ? offer.verb : "", t),
+ onSelect: () => void save("ask_next", { kind: "require_approval", scope: "agent", breadth }), disabled: saving !== null, testId: "action-card-ask-next",
+ });
+ }
+ const savedText = saved
+ ? saved.scope === "chat"
+ ? fill(t("action_card.rule.saved_chat"), { app: saved.app || title })
+ : fill(t("action_card.rule.saved"), { rule: savedRuleSentence(saved, t) })
+ : "";
+ const note = decision === "expired" || decision === "cancel" || decision === "deny" ? t(`action_card.outcome_note.${decision}`) : "";
+ const settled: SettledSpec = {
+ tone: outcomeTone(decision),
+ label: outcomeLabel(decision, t),
+ detail: approval.summary.trim() || title,
+ actions,
+ receipt: saved ? <span className="action-card-receipt" title={savedText} data-testid="action-card-rule-saved">
+ <Check aria-hidden />{t("action_card.rule.saved_short")}
+ </span> : error ? <span role="alert" className="text-[11px] text-destructive">{error}</span> : null,
+ body: <>
+ {note ? <p className="m-0 text-xs leading-5 text-muted-foreground">{note}</p> : null}
+ {savedText ? <p className="m-0 text-xs leading-5 text-foreground-secondary">{savedText}</p> : null}
+ {saved?.stillAsks ? <p className="m-0 text-xs leading-5 text-warning">{t("action_card.rule.still_asks")}</p> : null}
+ </>,
+ };
+ return <ActionCard
+ id={approval.approvalId}
+ testId="approval-outcome"
+ state={decision}
+ source={{ icon: <SourceIcon info={info} />, label: sourceLabel(info, t) }}
+ title={title}
+ ariaLabel={`${settled.label}: ${title}`}
+ lines={subtitleLines(info, approval, title, t)}
+ disclosure={info.detail ? {
+ text: info.detail,
+ showLabel: t(info.source.kind === "terminal" ? "action_card.show_command" : "action_card.show_details"),
+ hideLabel: t(info.source.kind === "terminal" ? "action_card.hide_command" : "action_card.hide_details"),
+ } : undefined}
+ settled={settled}
+ >
+ {info.source.kind === "plan" && planText(block) ? <div className="max-h-56 overflow-auto rounded-lg bg-secondary px-3 py-2 text-sm scrollbar-jarvis"><ChatMarkdown text={planText(block)} /></div> : null}
+ </ActionCard>;
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
new file mode 100644
index 0000000000..c20172ec25
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
@@ -0,0 +1,125 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EMPTY_TIMELINE, reduceEvents, type ToolBlock, type TurnItem } from "../reduce";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { claimKeyboardTarget, TARGET_PRIORITY } from "./keyboardTarget";
+import { maskedRequest, maskText } from "./redact";
+import { parseApprovalCard, parseSavedRule } from "./approvalInfo";
+
+let seq = 0;
+const ev = (kind: string, payload: Record<string, unknown>): AgentChatEvent => ({ seq: ++seq, ts_ms: seq, kind, payload } as AgentChatEvent);
+
+afterEach(() => { seq = 0; });
+
+describe("the keyboard target", () => {
+ it("goes to the highest priority, then the newest claim, and releases cleanly", () => {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const calls: string[] = [];
+ const releaseApproval = claimKeyboardTarget({ priority: TARGET_PRIORITY.approval, element: () => element, onEscape: () => calls.push("approval") });
+ const releaseQuestion = claimKeyboardTarget({ priority: TARGET_PRIORITY.question, element: () => element, onEscape: () => calls.push("question") });
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ releaseApproval();
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ releaseQuestion();
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ element.remove();
+ expect(calls).toEqual(["approval", "question"]);
+ });
+
+ it("ignores a card no longer in the document", () => {
+ const onEscape = vi.fn();
+ const release = claimKeyboardTarget({ priority: 2, element: () => document.createElement("div"), onEscape });
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ release();
+ expect(onEscape).not.toHaveBeenCalled();
+ });
+
+ it("stands back while a dialog is open", () => {
+ const element = document.createElement("div");
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ dialog.setAttribute("aria-modal", "true");
+ document.body.append(element, dialog);
+ const onEscape = vi.fn();
+ const release = claimKeyboardTarget({ priority: 2, element: () => element, onEscape });
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ release();
+ element.remove();
+ dialog.remove();
+ expect(onEscape).not.toHaveBeenCalled();
+ });
+
+ it("leaves Esc to an open menu or listbox, but not to one kept hidden", () => {
+ const element = document.createElement("div");
+ const menu = document.createElement("div");
+ menu.setAttribute("role", "menu");
+ document.body.append(element, menu);
+ const onEscape = vi.fn();
+ const release = claimKeyboardTarget({ priority: 2, element: () => element, onEscape });
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ expect(onEscape).not.toHaveBeenCalled();
+ menu.hidden = true;
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ expect(onEscape).toHaveBeenCalledTimes(1);
+ release();
+ element.remove();
+ menu.remove();
+ });
+
+ it("leaves Esc to a focused control whose popup is open", () => {
+ const element = document.createElement("div");
+ const button = document.createElement("button");
+ button.setAttribute("aria-haspopup", "listbox");
+ button.setAttribute("aria-expanded", "true");
+ document.body.append(element, button);
+ const onEscape = vi.fn();
+ const release = claimKeyboardTarget({ priority: 2, element: () => element, onEscape });
+ button.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
+ release();
+ element.remove();
+ button.remove();
+ expect(onEscape).not.toHaveBeenCalled();
+ });
+});
+
+describe("masking", () => {
+ it("masks secret-named fields and credential shapes, keeps the rest readable", () => {
+ const text = maskedRequest({ to: "[email protected]", password: "hunter2-correct-horse", nested: { auth_token: "abcdefgh12345678" }, max_tokens: 400 });
+ expect(text).toContain("[email protected]");
+ expect(text).toContain("400");
+ expect(text).not.toContain("hunter2");
+ expect(text).not.toContain("abcdefgh12345678");
+ // Built at runtime so no credential-shaped literal sits in the source.
+ const key = ["sk", "proj", "q7".repeat(14)].join("-");
+ expect(maskText(`export OPENAI_API_KEY=${key} && run`)).not.toContain(key);
+ expect(maskedRequest({ command: "curl -H 'Authorization: Bearer abcdefghijklmnopqrstuv' x" })).not.toContain("abcdefghijklmnopqrstuv");
+ });
+});
+
+describe("the reducer and the card fields", () => {
+ it("parses the backend's card fields, tolerating junk", () => {
+ expect(parseApprovalCard({})).toBeUndefined();
+ const info = parseApprovalCard({ source: { kind: "nonsense", app: 3 }, caution: "loud", rule: { scopes: ["agent", "world"], chat: "x" } });
+ expect(info?.source).toEqual({ kind: "tool", app: "", verb: "" });
+ expect(info?.caution).toBeNull();
+ expect(info?.rule?.scopes).toEqual(["agent"]);
+ expect(info?.rule?.chat).toBe("");
+ expect(parseSavedRule({ rule_kind: "always_allow", scope: "galaxy" })).toBeNull();
+ });
+
+ it("records the scope of an always and patches the card with a saved rule", () => {
+ const tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("turn_started", { turn_id: "t1" }),
+ ev("approval_required", { turn_id: "t1", approval_id: "a1", call_id: "c1", name: "gmail", input: {}, summary: "s", source: { kind: "connector", app: "Gmail" } }),
+ ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow_always", scope: "agent" }),
+ ev("notice", { kind: "approval_rule", turn_id: "t1", approval_id: "a1", rule_kind: "always_allow", scope: "agent", pattern: "plugin:gmail", app: "Gmail", verb: "", still_asks: true }),
+ ]);
+ expect(tl.items).toHaveLength(1);
+ const block = (tl.items[0] as TurnItem).blocks[0] as ToolBlock;
+ expect(block.approval).toMatchObject({
+ decision: "allow_always", scope: "agent", card: { source: { kind: "connector", app: "Gmail" } },
+ rule: { kind: "always_allow", scope: "agent", pattern: "plugin:gmail", stillAsks: true },
+ });
+ expect(tl.pendingApprovals).toEqual([]);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
new file mode 100644
index 0000000000..f3170837e9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
@@ -0,0 +1,99 @@
+import { fill } from "@/i18n";
+import type { ToolBlock } from "../reduce";
+import type { ApprovalCardInfo, ApprovalSourceKind, RuleBreadth, RuleKind, SavedApprovalRule } from "./approvalInfo";
+import { maskText, maskedRequest } from "./redact";
+
+type T = (key: string) => string;
+
+const OWN_SERVER = /^mcp__(?:dodaios|jarvis)__/;
+
+function humanize(raw: string): string {
+ const words = raw.split(/[_\-.]+/).filter(Boolean);
+ if (!words.length) return raw;
+ return words.map((w) => (w === "github" ? "GitHub" : w.charAt(0).toUpperCase() + w.slice(1))).join(" ");
+}
+
+/**
+ * The card fields of an approval, from the backend's own fields when the
+ * event carries them, else read off the tool name and input (events written
+ * before the fields existed).
+ */
+export function cardInfoOf(block: ToolBlock): ApprovalCardInfo {
+ const known = block.approval?.card;
+ if (known) return { ...known, detail: maskText(known.detail) };
+ const name = block.name || "";
+ const input = block.input && typeof block.input === "object" ? (block.input as Record<string, unknown>) : {};
+ let kind: ApprovalSourceKind = "tool";
+ let app = "";
+ if (name === "ExitPlanMode" || name === "exit_plan_mode") kind = "plan";
+ else if (/^(bash|runcommand|run_command|shell|exec|exec_command|powershell)$/i.test(name)) kind = "terminal";
+ else if (/^(write|edit|multiedit|notebookedit|apply_patch|write_file|edit_file|create_file)$/i.test(name)) kind = "files";
+ else if (/browser|webfetch|web_fetch/i.test(name)) kind = "browser";
+ else if (name.startsWith("mcp__")) {
+ kind = "connector";
+ const [, server = "", tool = ""] = name.split("__");
+ app = humanize(OWN_SERVER.test(name) ? tool : server);
+ } else if (typeof input.command === "string") kind = "terminal";
+ else app = name;
+ const where = (kind === "terminal" || kind === "files") && typeof input.cwd === "string" ? input.cwd : "";
+ const why = typeof input.description === "string" ? maskText(input.description) : "";
+ return {
+ source: { kind, app, verb: typeof input.action === "string" && /^[a-z][a-z0-9_.-]{0,39}$/.test(input.action) ? input.action : "" },
+ where,
+ why,
+ caution: null,
+ detail: kind === "plan" ? "" : maskedRequest(block.input),
+ // An older card cannot say what its "always" saves; it does what it always did.
+ rule: kind === "plan" ? null : { scopes: [], chat: "", app: "", verb: "", pattern: "", broad: "" },
+ };
+}
+
+/** The source chip's label: what is asking. */
+export function sourceLabel(info: ApprovalCardInfo, t: T): string {
+ const { kind, app } = info.source;
+ if ((kind === "connector" || kind === "tool") && app) return app;
+ return t(`action_card.source.${kind}`);
+}
+
+/** The card's question-form title. */
+export function approvalTitle(info: ApprovalCardInfo, t: T): string {
+ const { kind, app, verb } = info.source;
+ if (kind === "connector") {
+ if (verb && app) return fill(t("action_card.title.connector_verb"), { app, verb });
+ return app ? fill(t("action_card.title.connector"), { app }) : t("action_card.title.tool_plain");
+ }
+ if (kind === "tool") return app ? fill(t("action_card.title.tool"), { tool: app }) : t("action_card.title.tool_plain");
+ return t(`action_card.title.${kind}`);
+}
+
+/** How a settled approval reads in one line ("Allowed once"). */
+export function outcomeLabel(decision: string, t: T): string {
+ const known = ["allow", "allow_always", "deny", "expired", "cancel"].includes(decision) ? decision : "cancel";
+ return t(`action_card.outcome.${known}`);
+}
+
+export type OutcomeTone = "success" | "danger" | "muted";
+
+export function outcomeTone(decision: string): OutcomeTone {
+ if (decision === "allow" || decision === "allow_always") return "success";
+ if (decision === "deny") return "danger";
+ return "muted";
+}
+
+/** A rule as the person reads it: "Always allow send with Gmail". */
+export function ruleSentence(kind: RuleKind, app: string, verb: string, t: T): string {
+ const base = kind === "require_approval" ? "ask" : "always";
+ if (!app) return t(`action_card.rule.${base}_generic`);
+ return verb
+ ? fill(t(`action_card.rule.${base}_verb`), { app, verb })
+ : fill(t(`action_card.rule.${base}_app`), { app });
+}
+
+export function savedRuleSentence(rule: SavedApprovalRule, t: T): string {
+ return ruleSentence(rule.kind, rule.app, rule.verb, t);
+}
+
+/** The verb a rule of this breadth is about. */
+export function breadthVerb(verb: string, breadth: RuleBreadth): string {
+ return breadth === "app" ? "" : verb;
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
new file mode 100644
index 0000000000..6bf879dc9e
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
@@ -0,0 +1,100 @@
+/**
+ * The display fields an approval card reads, parsed from the
+ * `approval_required` payload (dodaios/agent_chat/approval_card.py). Every
+ * field is optional: an event written before the backend sent them parses to
+ * `undefined`, and the card falls back to the tool name and the summary.
+ */
+
+export type ApprovalSourceKind = "terminal" | "files" | "browser" | "computer" | "plan" | "agent" | "connector" | "tool";
+export type ApprovalCaution = "irreversible" | "security" | "data_leaves";
+/** Where a rule from the card lives: the agent's own approval rules, or this chat. */
+export type RuleScope = "agent" | "chat";
+/** `action`: only this action of the app; `app`: every action of it. */
+export type RuleBreadth = "action" | "app";
+export type RuleKind = "always_allow" | "require_approval";
+
+/** What "Always allow" saves on this card. */
+export interface ApprovalRuleOffer {
+ scopes: RuleScope[];
+ /** What a chat-wide "always" does here: this tool, the whole chat, or the runtime remembers. */
+ chat: "tool" | "all" | "runtime" | "";
+ app: string;
+ verb: string;
+ pattern: string;
+ broad: string;
+}
+
+export interface ApprovalCardInfo {
+ /** What is asking; `verb` is the one-word action a connector call performs ("send"). */
+ source: { kind: ApprovalSourceKind; app: string; verb: string };
+ where: string;
+ why: string;
+ caution: ApprovalCaution | null;
+ /** The exact command or request, secrets masked by the backend. */
+ detail: string;
+ /** `null`: the card offers no "Always allow" (a plan). */
+ rule: ApprovalRuleOffer | null;
+}
+
+/** A standing rule saved from a card (`notice{kind:"approval_rule"}`). */
+export interface SavedApprovalRule {
+ kind: RuleKind;
+ scope: RuleScope;
+ pattern: string;
+ app: string;
+ verb: string;
+ /** A broader "ask first" rule keeps asking anyway. */
+ stillAsks: boolean;
+}
+
+const KINDS = new Set<ApprovalSourceKind>(["terminal", "files", "browser", "computer", "plan", "agent", "connector", "tool"]);
+const CAUTIONS = new Set<ApprovalCaution>(["irreversible", "security", "data_leaves"]);
+const SCOPES = new Set<RuleScope>(["agent", "chat"]);
+
+const text = (v: unknown): string => (typeof v === "string" ? v : "");
+const record = (v: unknown): Record<string, unknown> | null =>
+ v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+
+export function parseApprovalCard(payload: Record<string, unknown>): ApprovalCardInfo | undefined {
+ const source = record(payload.source);
+ if (!source) return undefined;
+ const kind = text(source.kind) as ApprovalSourceKind;
+ const caution = text(payload.caution) as ApprovalCaution;
+ return {
+ source: { kind: KINDS.has(kind) ? kind : "tool", app: text(source.app), verb: text(source.verb) },
+ where: text(payload.where),
+ why: text(payload.why),
+ caution: CAUTIONS.has(caution) ? caution : null,
+ detail: text(payload.detail),
+ rule: parseRuleOffer(payload.rule),
+ };
+}
+
+function parseRuleOffer(raw: unknown): ApprovalRuleOffer | null {
+ const rule = record(raw);
+ if (!rule) return null;
+ const scopes = Array.isArray(rule.scopes) ? rule.scopes.filter((s): s is RuleScope => SCOPES.has(s as RuleScope)) : [];
+ const chat = text(rule.chat);
+ return {
+ scopes,
+ chat: chat === "tool" || chat === "all" || chat === "runtime" ? chat : "",
+ app: text(rule.app),
+ verb: text(rule.verb),
+ pattern: text(rule.pattern),
+ broad: text(rule.broad),
+ };
+}
+
+export function parseSavedRule(payload: Record<string, unknown>): SavedApprovalRule | null {
+ const kind = text(payload.rule_kind);
+ const scope = text(payload.scope) as RuleScope;
+ if ((kind !== "always_allow" && kind !== "require_approval") || !SCOPES.has(scope)) return null;
+ return {
+ kind,
+ scope,
+ pattern: text(payload.pattern),
+ app: text(payload.app),
+ verb: text(payload.verb),
+ stillAsks: payload.still_asks === true,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/keyboardTarget.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/keyboardTarget.ts
new file mode 100644
index 0000000000..7ab1d71fc0
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/keyboardTarget.ts
@@ -0,0 +1,130 @@
+/**
+ * The one card a plain key press answers.
+ *
+ * Several cards can be open in a chat at once. Only one of them is the
+ * keyboard target: the newest open card of the highest priority (a pending
+ * approval outranks a question). Esc then answers that card's dismiss action
+ * (an approval's "Deny") — and only when the press is not meant for anything
+ * else: no modifier, no key repeat, no text field or contenteditable holding
+ * focus, no open dialog, menu, listbox or popover, and the card actually on
+ * screen.
+ *
+ * A card claims the target while it is open and releases it when it settles
+ * or unmounts. One capture-phase listener serves every card.
+ */
+
+export interface KeyboardTarget {
+ /** Higher wins; equal priority goes to the newest claim. */
+ priority: number;
+ /** The card's element, to check it is on screen. */
+ element: () => HTMLElement | null;
+ onEscape: () => void;
+}
+
+/** Priorities for the cards that claim the target. */
+export const TARGET_PRIORITY = { approval: 2, question: 1 } as const;
+
+interface Claim extends KeyboardTarget {
+ order: number;
+}
+
+const claims = new Map<symbol, Claim>();
+let order = 0;
+let listening = false;
+
+function current(): Claim | null {
+ let best: Claim | null = null;
+ for (const claim of claims.values()) {
+ if (!best || claim.priority > best.priority || (claim.priority === best.priority && claim.order > best.order)) best = claim;
+ }
+ return best;
+}
+
+function isTyping(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ if (target.isContentEditable) return true;
+ const tag = target.tagName;
+ if (tag === "TEXTAREA" || tag === "SELECT") return true;
+ if (tag === "INPUT") {
+ const type = (target as HTMLInputElement).type;
+ return !["button", "checkbox", "radio", "submit", "reset"].includes(type);
+ }
+ return Boolean(target.closest("[contenteditable='true'], .xterm"));
+}
+
+/**
+ * A dialog, menu, listbox or popover is open: its Esc closes it. This
+ * listener runs in the window's capture phase, before any of their own
+ * handlers, so it must stand back or that Esc would deny the card instead.
+ */
+const OVERLAYS = [
+ "[role='dialog'][data-state='open']",
+ "[aria-modal='true']",
+ "[role='alertdialog']",
+ "[role='menu']",
+ "[role='listbox']",
+ "[data-radix-popper-content-wrapper]",
+ "[popover]:popover-open",
+].join(", ");
+
+function overlays(): NodeListOf<Element> {
+ try {
+ return document.querySelectorAll(OVERLAYS);
+ } catch {
+ // An engine without `:popover-open` cannot parse the list; check without it.
+ return document.querySelectorAll(OVERLAYS.replace(", [popover]:popover-open", ""));
+ }
+}
+
+function dialogOpen(): boolean {
+ // A menu kept mounted but `hidden` while closed is not open.
+ return Array.from(overlays()).some((el) => !el.closest("[hidden]"));
+}
+
+/** Focus sits on a control whose own popup is open (a combobox, a menu button). */
+function popupOpen(target: EventTarget | null): boolean {
+ return target instanceof HTMLElement && Boolean(target.closest("[aria-expanded='true'][aria-haspopup]"));
+}
+
+function onScreen(element: HTMLElement | null): boolean {
+ if (!element || !element.isConnected || element.closest("[hidden]")) return false;
+ // Without a layout engine (tests) there is nothing more to measure.
+ if (typeof element.checkVisibility !== "function") return true;
+ if (!element.checkVisibility()) return false;
+ const rect = element.getBoundingClientRect();
+ return rect.bottom > 0 && rect.top < window.innerHeight;
+}
+
+function onKeyDown(event: KeyboardEvent): void {
+ if (event.key !== "Escape" || event.repeat || event.defaultPrevented) return;
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
+ if (document.visibilityState === "hidden" || isTyping(event.target) || popupOpen(event.target) || dialogOpen()) return;
+ const target = current();
+ if (!target || !onScreen(target.element())) return;
+ event.preventDefault();
+ event.stopPropagation();
+ target.onEscape();
+}
+
+/** Claim the keyboard target; the returned function releases it. */
+export function claimKeyboardTarget(target: KeyboardTarget): () => void {
+ const key = Symbol("keyboard-target");
+ claims.set(key, { ...target, order: ++order });
+ if (!listening && typeof window !== "undefined") {
+ window.addEventListener("keydown", onKeyDown, true);
+ listening = true;
+ }
+ return () => {
+ claims.delete(key);
+ if (claims.size === 0 && listening) {
+ window.removeEventListener("keydown", onKeyDown, true);
+ listening = false;
+ }
+ };
+}
+
+/** Whether `element` belongs to the card that holds the target right now. */
+export function holdsKeyboardTarget(element: HTMLElement | null): boolean {
+ const target = current();
+ return Boolean(target && element && target.element() === element);
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/redact.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/redact.ts
new file mode 100644
index 0000000000..7c1f63f8d2
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/redact.ts
@@ -0,0 +1,52 @@
+/**
+ * The disclosure text of a card whose event predates the backend's masked
+ * `detail` (dodaios/agent_chat/approval_card.py). Same rule as there: a field
+ * named like a secret is masked whole, and anything shaped like a credential
+ * inside other text is masked in place. Over-masking is fine; leaking is not.
+ */
+
+const MASK = "••••••";
+const SECRET_KEY = /(pass(word|wd|phrase)?|secret|token|api[_-]?key|apikey|(?<![a-z])auth(orization)?(?![a-z])|cookie|credential|private[_-]?key|session[_-]?key|(?<![a-z])otp(?![a-z])|pin[_-]?code)/i;
+const SHAPES: RegExp[] = [
+ /\bsk-(?:proj-|ant-|or-|live-)?[A-Za-z0-9_-]{20,}\b/g,
+ /\b(?:AIza[0-9A-Za-z_-]{30,}|xai-[A-Za-z0-9]{20,}|gsk_[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{16,}|xox[abprs]-[A-Za-z0-9-]{10,})\b/g,
+ /\b[Bb]earer\s+[A-Za-z0-9._-]{16,}\b/g,
+ /\beyJ[A-Za-z0-9_-]{6,}\.eyJ[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{3,}\b/g,
+ /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/g,
+ /\b[0-9a-fA-F]{64,}\b/g,
+ /\b[A-Za-z0-9+/]{64,}={0,2}/g,
+];
+const LABELLED = /(\b(?:api[_-]?key|secret(?:[_-]?key)?|password|passwd|pwd|access[_-]?token|auth[_-]?token|client[_-]?secret)\b['"]?\s*[:=]\s*)['"]?[^\s'"]{6,}/gi;
+
+export function maskText(text: string): string {
+ let out = text.replace(LABELLED, `$1${MASK}`);
+ for (const shape of SHAPES) out = out.replace(shape, MASK);
+ return out;
+}
+
+function mask(value: unknown, depth = 0): unknown {
+ if (depth > 8) return MASK;
+ if (Array.isArray(value)) return value.slice(0, 200).map((v) => mask(v, depth + 1));
+ if (value && typeof value === "object") {
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, v]) => [
+ k, SECRET_KEY.test(k) && typeof v === "string" && v.trim() ? MASK : mask(v, depth + 1),
+ ]));
+ }
+ return typeof value === "string" ? maskText(value) : value;
+}
+
+/** The exact command (or the whole request as JSON), secrets masked. */
+export function maskedRequest(input: unknown): string {
+ if (input && typeof input === "object" && !Array.isArray(input)) {
+ const raw = (input as Record<string, unknown>).command;
+ if (typeof raw === "string" && raw.trim()) return maskText(raw).slice(0, 4000);
+ if (Array.isArray(raw) && raw.length) return maskText(raw.map(String).join(" ")).slice(0, 4000);
+ if (Object.keys(input).length === 0) return "";
+ }
+ if (input === null || input === undefined || input === "") return "";
+ try {
+ return maskText(JSON.stringify(mask(input), null, 2)).slice(0, 4000);
+ } catch {
+ return "";
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
index 62f96ce459..c4cfd2e123 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -3,6 +3,7 @@ import type { ChatControlState } from "@/lib/chatControlApi";
import { hideAskBlocks } from "./askFence";
import { hideMeetingPass } from "./meetingPass";
import { readToolChoices, type ToolChoice } from "./toolChoices";
+import { parseApprovalCard, parseSavedRule, type ApprovalCardInfo, type RuleScope, type SavedApprovalRule } from "./actionCard/approvalInfo";
/**
* Fold the agent-chat event log into the timeline the column renders.
@@ -48,6 +49,12 @@ export interface ApprovalState {
summary: string;
/** Set once the person (or a cancel) decided. */
decision: string | null;
+ /** What the card shows besides its answers; absent on events older than the fields. */
+ card?: ApprovalCardInfo;
+ /** Where an "Always allow" from the card lives (`approval_resolved.scope`). */
+ scope?: RuleScope;
+ /** A standing rule saved from this card, now or later. */
+ rule?: SavedApprovalRule;
}
/** One prepared answer on an agent's question card. */
@@ -676,13 +683,15 @@ function expireOpenApproval(block: TurnBlock): TurnBlock {
* does a decision the backend already confirmed (or reported expired) before
* that event arrived — the card must not wait on the socket to go away.
*/
-export function settleApproval(tl: Timeline, approvalId: string, decision: string, turnId = ""): Timeline {
+export function settleApproval(tl: Timeline, approvalId: string, decision: string, turnId = "", scope?: RuleScope): Timeline {
const owner = turnId || tl.pendingApprovals.find((a) => a.approvalId === approvalId)?.turnId || "";
const settle = (turn: TurnItem): TurnItem => {
const blocks = mapToolDeep(
turn.blocks,
(b) => b.approval?.approvalId === approvalId,
- (b) => (b.approval && b.approval.decision === null ? { ...b, approval: { ...b.approval, decision } } : b),
+ (b) => (b.approval && b.approval.decision === null
+ ? { ...b, approval: { ...b.approval, decision, ...(scope ? { scope } : {}) } }
+ : b),
);
return blocks && blocks !== turn.blocks ? { ...turn, blocks } : turn;
};
@@ -696,6 +705,21 @@ export function settleApproval(tl: Timeline, approvalId: string, decision: strin
return pendingApprovals.length === withTurn.pendingApprovals.length ? withTurn : { ...withTurn, pendingApprovals };
}
+/** Record a standing rule saved from approval `approvalId`'s card, decided or not. */
+export function noteApprovalRule(tl: Timeline, approvalId: string, rule: SavedApprovalRule, turnId = ""): Timeline {
+ const patch = (turn: TurnItem): TurnItem => {
+ const blocks = mapToolDeep(
+ turn.blocks,
+ (b) => b.approval?.approvalId === approvalId,
+ (b) => (b.approval ? { ...b, approval: { ...b.approval, rule } } : b),
+ );
+ return blocks && blocks !== turn.blocks ? { ...turn, blocks } : turn;
+ };
+ if (turnId) return updateTurn(tl, turnId, patch);
+ const items = tl.items.map((item) => (item.type === "turn" ? patch(item) : item));
+ return items.some((item, i) => item !== tl.items[i]) ? { ...tl, items } : tl;
+}
+
/** Update the sub-agent `agentId` spawned; a spawn call the stream never announced gets a row of its own. */
function updateSubagent(
turn: TurnItem,
@@ -1118,7 +1142,8 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
summary: str(p.summary),
};
const withTurn = updateTurn(base, turnId, (turn) => {
- const approval = { approvalId, summary: pending.summary, decision: null };
+ const card = parseApprovalCard(p as Record<string, unknown>);
+ const approval: ApprovalState = { approvalId, summary: pending.summary, decision: null, ...(card ? { card } : {}) };
const nested = mapToolDeep(turn.blocks, (b) => b.callId === callId, (b) => ({ ...b, approval }));
if (nested) return nested === turn.blocks ? turn : { ...turn, blocks: nested };
return upsertBlock<ToolBlock>(
@@ -1147,8 +1172,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
};
}
- case "approval_resolved":
- return settleApproval(base, str(p.approval_id), str(p.decision), turnId);
+ case "approval_resolved": {
+ const scope = str(p.scope);
+ return settleApproval(base, str(p.approval_id), str(p.decision), turnId,
+ scope === "agent" || scope === "chat" ? scope : undefined);
+ }
case "question_required": {
const questionId = str(p.question_id);
@@ -1295,6 +1323,11 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
const text = str(p.text);
const kind = str(p.kind);
if (!text && !kind) return base;
+ if (kind === "approval_rule") {
+ // A rule saved from an approval card patches that card, never a row of its own.
+ const rule = parseSavedRule(p as Record<string, unknown>);
+ return rule ? noteApprovalRule(base, str(p.approval_id), rule, turnId) : base;
+ }
if (kind === "message_dequeued") {
// A waiting message started (or could not): its waiting line goes.
const queueId = str(p.queue_id);
diff --git a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
index b681a34ae3..f79f7dea58 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
@@ -9,7 +9,7 @@ import { CallMark, StretchMark } from "@/components/agentchat/TraceTimeline";
import { plural, readableOutput, traceDuration, type Call } from "@/components/agentchat/traceEntries";
import { fill, useI18nStore, useT } from "@/i18n";
import { localeForUiLanguage } from "@/components/runs/format";
-import type { ApprovalDecision } from "@/lib/agentChatApi";
+import { ApprovalActionCard, type ApprovalDecide } from "@/components/agentchat/actionCard/ApprovalActionCard";
import { robustCopy } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { ChatThought } from "./ChatThought";
@@ -544,8 +544,8 @@ function answerText(turn: TurnItem): string {
return turn.blocks.filter((block): block is TextBlock => block.kind === "text").map((block) => block.text.trim()).filter(Boolean).join("\n\n");
}
-/** How a surface answers an approval: by its id, with the person's decision. */
-export type Decide = (id: string, decision: ApprovalDecision) => void | Promise<void>;
+/** How a surface answers an approval: by its id, the person's decision and where an "always" lives. */
+export type Decide = ApprovalDecide;
/** A call still waiting for the person: an open question or an undecided approval. */
function waitsForPerson(block: ToolBlock): boolean {
@@ -561,40 +561,11 @@ function pendingLabel(block: ToolBlock, t: (key: string) => string): { icon: Rea
}
/**
- * An approval answered in the turn itself: the waiting line, what the agent
- * asks for, and the three answers under it.
+ * An approval answered in the turn itself, on the shared action card: what
+ * the agent asks for in plain words, with "Allow once" first.
*/
export function ApprovalPrompt({ block, onDecide }: { block: ToolBlock; onDecide?: Decide }) {
- const t = useT();
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const approval = block.approval;
- if (!approval) return null;
- const decide = async (decision: ApprovalDecision) => {
- if (!onDecide || busy) return;
- setBusy(true);
- setError(null);
- try { await onDecide(approval.approvalId, decision); }
- catch (err) { setError(err instanceof Error ? err.message : String(err)); }
- finally { setBusy(false); }
- };
- return <div className="min-w-0" role="group" aria-label={t("work_trace.approval")} data-testid="thread-approval">
- <WorkRow icon={<ShieldAlert strokeWidth={1.75} />} label={t("thread_turn.approval_waiting")} live />
- <div className="mb-1.5 ml-7 space-y-2 text-sm">
- {approval.summary && <p className="m-0 text-foreground [overflow-wrap:anywhere]">{approval.summary}</p>}
- {onDecide
- ? <div className="flex flex-wrap gap-2">
- {(["allow", "allow_always", "deny"] as const).map((decision) => <button key={decision} type="button" disabled={busy}
- onClick={() => void decide(decision)}
- className={cn("rounded-md px-3 py-1.5 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
- decision === "allow" ? "bg-primary text-primary-foreground hover:opacity-90" : "border border-border text-foreground hover:bg-secondary")}>
- {t(`work_trace.${decision}`)}
- </button>)}
- </div>
- : <p className="m-0 text-xs text-muted-foreground">{t("work_trace.approval_elsewhere")}</p>}
- {error && <p role="alert" className="m-0 text-xs text-destructive">{error}</p>}
- </div>
- </div>;
+ return <ApprovalActionCard block={block} onDecide={onDecide} />;
}
/**
diff --git a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTurn.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTurn.test.tsx
index 61469579e3..3a460b9f08 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTurn.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/threads/ThreadTurn.test.tsx
@@ -53,7 +53,7 @@ describe("a thread turn in an agent chat", () => {
// The turn ended while it waited: the work folds, the approval stays in view.
expect(screen.getByTestId("thread-worked-for")).toBeTruthy();
expect(screen.getByText("Push to origin?")).toBeTruthy();
- await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Approve" })); });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Allow once" })); });
expect(onDecide).toHaveBeenCalledWith("ap1", "allow");
});
@@ -61,7 +61,7 @@ describe("a thread turn in an agent chat", () => {
const asking = tool("c1", "git push", { output: null, durationMs: null, approval: { approvalId: "ap1", summary: "Push to origin?", decision: null } });
render(<ThreadTurn turn={turn([asking], "running")} />);
expect(screen.getByText("Waiting for approval — Push to origin?")).toBeTruthy();
- expect(screen.queryByRole("button", { name: "Approve" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Allow once" })).toBeNull();
});
it("folds memory receipts with the work, above the answer", () => {
diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index 3e9a2e19af..34dd68cdbb 100644
--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -62,6 +62,8 @@ import {
type UserItem,
} from "@/components/agentchat/reduce";
import { AwaitingTurn, MessengerTurn, type MemoryLink } from "@/components/agentchat/MessengerTurn";
+import { ActionCard, type ActionSpec } from "@/components/agentchat/actionCard/ActionCard";
+import { WandSparkles as ProposalIcon } from "lucide-react";
import { VoiceStage } from "@/components/home/VoiceStage";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { fill, useT } from "@/i18n";
@@ -998,33 +1000,51 @@ function ProposalCard({ item }: { item: NoticeItem }) {
: item.resolved
? t("society.chat.proposal_failed")
: "";
- if (item.resolved && item.resolved !== "failed") return <ChatActivity
- label={<>{resolvedLabel} · {kind ? t(`society.chat.proposal_kind_${kind}`) : ""} · {summary}</>}>
- <p className="whitespace-pre-wrap">{detail || summary}</p>
- {reason ? <p className="mt-2">{reason}</p> : null}
- {outcome ? <p className="mt-2">{outcome}</p> : null}
- </ChatActivity>;
+ const kindLabel = kind ? t(`society.chat.proposal_kind_${kind}`) : "";
+ const title = t("society.chat.proposal_title").replace("{0}", item.agentName || t("society.chat.result_agent"));
+ const source = { icon: <ProposalIcon strokeWidth={1.75} />, label: kindLabel || t("action_card.source.proposal") };
+ if (item.resolved) {
+ // Decided: one line that says what happened, the proposal itself one click away.
+ return <ActionCard
+ id={`proposal:${proposalId || item.id}`}
+ testId="proposal-card"
+ state={item.resolved}
+ source={source}
+ title={title}
+ ariaLabel={`${resolvedLabel}: ${summary}`}
+ settled={{
+ tone: item.resolved === "applied" ? "success" : item.resolved === "rejected" ? "muted" : "danger",
+ label: resolvedLabel,
+ detail: summary,
+ body: <>
+ <p className="m-0 whitespace-pre-wrap text-xs leading-5 text-foreground-secondary">{detail || summary}</p>
+ {reason ? <p className="m-0 text-xs leading-5 text-muted-foreground">{reason}</p> : null}
+ {outcome ? <p className={cn("m-0 text-xs leading-5", item.resolved === "failed" ? "text-destructive" : "text-muted-foreground")}>{outcome}</p> : null}
+ </>,
+ }}
+ />;
+ }
+ const actions: ActionSpec[] = [
+ { id: "confirm", label: t("society.chat.proposal_confirm"), tone: "primary", onSelect: () => void decide(true), disabled: busy || (kind === "team" && chosen.length === 0) },
+ { id: "reject", label: t("society.chat.proposal_reject"), tone: "tertiary", onSelect: () => void decide(false), disabled: busy },
+ ];
return (
- <div
- className={cn(
- "flex max-w-[85%] flex-col gap-1.5 self-start rounded-2xl rounded-bl-md border px-3.5 py-2.5 text-xs",
- item.resolved === "applied"
- ? "border-primary/40 bg-primary/5"
- : item.resolved
- ? "border-border bg-card"
- : "border-primary/60 bg-card",
- )}
+ <ActionCard
+ id={`proposal:${proposalId || item.id}`}
+ testId="proposal-card"
+ source={source}
+ title={title}
+ ariaLabel={`${t("society.chat.proposal_pending")}: ${title}`}
+ lines={reason ? [<><span className="font-medium text-foreground-secondary">{t("society.chat.proposal_reason")}: </span>{reason}</>] : undefined}
+ actions={actions}
+ failure={error || null}
+ note={t("society.chat.proposal_pending")}
+ className="self-start"
>
- <p className="font-medium text-foreground">
- {t("society.chat.proposal_title").replace("{0}", item.agentName || t("society.chat.result_agent"))}
- </p>
- <p className="text-[11px] uppercase tracking-wide text-muted-foreground">
- {kind ? t(`society.chat.proposal_kind_${kind}`) : ""}
- </p>
- {kind === "team" && !item.resolved ? (
- <ul className="flex flex-col gap-1">
+ {kind === "team" ? (
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
{offered.map((row) => (
- <li key={row.name} className="flex items-center gap-2">
+ <li key={row.name} className="flex items-center gap-2 text-sm">
<input
type="checkbox"
id={`${proposalId}-${row.name}`}
@@ -1037,7 +1057,7 @@ function ProposalCard({ item }: { item: NoticeItem }) {
: chosen.filter((name) => name !== row.name),
)
}
- className="h-3.5 w-3.5 accent-[var(--primary)]"
+ className="h-3.5 w-3.5 accent-[hsl(var(--primary))]"
/>
<label htmlFor={`${proposalId}-${row.name}`} className="cursor-pointer text-foreground">
<span className="font-medium">{row.name}</span>
@@ -1047,42 +1067,9 @@ function ProposalCard({ item }: { item: NoticeItem }) {
))}
</ul>
) : (
- <p className="whitespace-pre-wrap leading-relaxed text-foreground">{detail || summary}</p>
+ <p className="m-0 whitespace-pre-wrap text-sm leading-relaxed text-foreground">{detail || summary}</p>
)}
- {reason ? (
- <p className="leading-relaxed text-muted-foreground">
- <span className="font-medium">{t("society.chat.proposal_reason")}: </span>
- {reason}
- </p>
- ) : null}
- {item.resolved ? (
- <p className={cn("font-medium", item.resolved === "failed" ? "text-destructive" : "text-foreground")}>
- {resolvedLabel}
- {outcome ? <span className="font-normal text-muted-foreground"> — {outcome}</span> : null}
- </p>
- ) : (
- <div className="mt-1 flex items-center gap-2">
- <button
- type="button"
- disabled={busy}
- onClick={() => void decide(true)}
- className="rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
- >
- {t("society.chat.proposal_confirm")}
- </button>
- <button
- type="button"
- disabled={busy}
- onClick={() => void decide(false)}
- className="rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground hover:bg-muted disabled:opacity-50"
- >
- {t("society.chat.proposal_reject")}
- </button>
- <span className="text-muted-foreground">{t("society.chat.proposal_pending")}</span>
- </div>
- )}
- {error ? <p className="text-destructive">{error}</p> : null}
- </div>
+ </ActionCard>
);
}
diff --git a/dodaios/ui/web/frontend/src/i18n/action-card-i18n-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/action-card-i18n-parity.test.ts
new file mode 100644
index 0000000000..0f3b557432
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/i18n/action-card-i18n-parity.test.ts
@@ -0,0 +1,81 @@
+/**
+ * The action card's copy (`action_card.*`) exists in every locale with the
+ * same keys and the same placeholders, and every key the card's sources ask
+ * for is defined. Template keys (`action_card.source.${kind}`) are covered by
+ * listing what they expand to.
+ */
+import { readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import en from "./locales/en.json";
+import de from "./locales/de.json";
+import es from "./locales/es.json";
+import pt from "./locales/pt.json";
+import zh from "./locales/zh.json";
+
+const LOCALES = { en, de, es, pt, zh } as Record<string, Record<string, unknown>>;
+
+function flatten(obj: Record<string, unknown>, prefix: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [k, v] of Object.entries(obj)) {
+ const key = `${prefix}.${k}`;
+ if (v && typeof v === "object" && !Array.isArray(v)) Object.assign(out, flatten(v as Record<string, unknown>, key));
+ else out[key] = String(v);
+ }
+ return out;
+}
+
+const block = (loc: Record<string, unknown>) => flatten((loc.action_card ?? {}) as Record<string, unknown>, "action_card");
+const placeholders = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
+
+const SRC = join(__dirname, "..");
+const FILES = [
+ ...readdirSync(join(SRC, "components", "agentchat", "actionCard"))
+ .filter((f) => /\.tsx?$/.test(f) && !/\.test\.tsx?$/.test(f))
+ .map((f) => join(SRC, "components", "agentchat", "actionCard", f)),
+ join(SRC, "components", "agentchat", "CredentialCard.tsx"),
+ join(SRC, "components", "society", "chat", "AgentChatPanel.tsx"),
+];
+
+const TEMPLATES: Record<string, string[]> = {
+ "action_card.source.": ["terminal", "files", "browser", "computer", "plan", "agent", "connector", "tool"],
+ "action_card.title.": ["terminal", "files", "browser", "computer", "plan", "agent"],
+ "action_card.caution.": ["irreversible", "security", "data_leaves"],
+ "action_card.outcome.": ["allow", "allow_always", "deny", "expired", "cancel"],
+ "action_card.outcome_note.": ["expired", "cancel", "deny"],
+ "action_card.rule.scope_": ["agent", "chat"],
+ "action_card.rule.": ["always_verb", "always_app", "always_generic", "ask_verb", "ask_app", "ask_generic"],
+};
+
+function usedKeys(): Set<string> {
+ const found = new Set<string>();
+ for (const file of FILES) {
+ for (const m of readFileSync(file, "utf8").matchAll(/"(action_card\.[a-z0-9_.]+)"/g)) found.add(m[1]);
+ }
+ for (const [prefix, rest] of Object.entries(TEMPLATES)) for (const r of rest) found.add(prefix + r);
+ return found;
+}
+
+describe("action card locale parity", () => {
+ const base = block(en);
+
+ it("defines every key the card asks for", () => {
+ const missing = [...usedKeys()].filter((key) => !(key in base));
+ expect(missing).toEqual([]);
+ });
+
+ it.each(Object.keys(LOCALES).filter((lang) => lang !== "en"))("%s carries exactly the English keys and placeholders", (lang) => {
+ const other = block(LOCALES[lang]);
+ expect(Object.keys(other).sort()).toEqual(Object.keys(base).sort());
+ for (const [key, text] of Object.entries(base)) {
+ expect([key, placeholders(other[key] ?? "")]).toEqual([key, placeholders(text)]);
+ expect((other[key] ?? "").trim()).not.toBe("");
+ }
+ });
+
+ it("writes German with real umlauts", () => {
+ const german = Object.values(block(de)).join(" ");
+ expect(german).not.toMatch(/\b(fuer|ueber|koennen|aendern|loesch\w*|zurueck)\b/i);
+ expect(german).toMatch(/[äöüß]/);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index c2867640e8..243078d0b2 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -10358,5 +10358,99 @@
"new_other": "{count} neue Nachrichten",
"dismiss": "Ausblenden"
}
+ },
+ "action_card": {
+ "needs_approval": "Braucht deine Freigabe",
+ "source": {
+ "terminal": "Terminal",
+ "files": "Dateien",
+ "browser": "Browser",
+ "computer": "Computer",
+ "plan": "Plan",
+ "agent": "Hilfsagent",
+ "connector": "Verbindung",
+ "tool": "Werkzeug",
+ "secure_field": "Sicheres Feld",
+ "proposal": "Vorgeschlagene Änderung"
+ },
+ "title": {
+ "terminal": "Diesen Befehl ausführen?",
+ "files": "Diese Datei ändern?",
+ "browser": "Den Browser verwenden?",
+ "computer": "Diesen Computer steuern?",
+ "plan": "Nach diesem Plan loslegen?",
+ "agent": "Einen Hilfsagenten starten?",
+ "connector": "{app} verwenden?",
+ "connector_verb": "{app} für „{verb}“ verwenden?",
+ "tool": "{tool} ausführen?",
+ "tool_plain": "Dieses Werkzeug ausführen?"
+ },
+ "field": {
+ "in": "In {where}",
+ "on": "Auf {where}",
+ "why": "„{why}“"
+ },
+ "show_command": "Befehl anzeigen",
+ "hide_command": "Befehl ausblenden",
+ "show_details": "Details anzeigen",
+ "hide_details": "Details ausblenden",
+ "copy": "Kopieren",
+ "copied": "Kopiert",
+ "allow_once": "Einmal erlauben",
+ "always_allow": "Immer erlauben",
+ "always_allow_more": "Immer erlauben…",
+ "deny": "Ablehnen",
+ "deny_esc": "Ablehnen (Esc)",
+ "elsewhere": "Beantworte das im Chat, aus dem es kommt.",
+ "plan_build": "Loslegen",
+ "plan_keep": "Weiter planen",
+ "caution": {
+ "irreversible": "Das lässt sich nicht rückgängig machen.",
+ "security": "Das ändert Sicherheits- oder Zugriffseinstellungen.",
+ "data_leaves": "Das schickt Daten aus diesem Chat hinaus."
+ },
+ "outcome": {
+ "allow": "Einmal erlaubt",
+ "allow_always": "Immer erlaubt",
+ "deny": "Abgelehnt",
+ "expired": "Abgelaufen",
+ "cancel": "Ohne Antwort geschlossen"
+ },
+ "outcome_note": {
+ "expired": "Nichts ist gelaufen: Niemand hat rechtzeitig geantwortet.",
+ "cancel": "Nichts ist gelaufen: Die Anfrage endete, bevor jemand antwortete.",
+ "deny": "Der Agent hat ein Nein bekommen und es nicht getan."
+ },
+ "expand": "Details anzeigen",
+ "collapse": "Details ausblenden",
+ "failed": "Das hat nicht geklappt. Versuch es noch einmal.",
+ "rule": {
+ "heading": "Als Regel speichern",
+ "scope_label": "Wo die Regel gilt",
+ "scope_agent": "Dieser Agent",
+ "scope_chat": "Dieser Chat",
+ "breadth_label": "Wie weit sie reicht",
+ "breadth_action": "Nur „{verb}“",
+ "breadth_app": "Alles in {app}",
+ "always_verb": "„{verb}“ mit {app} immer erlauben",
+ "always_app": "{app} immer erlauben",
+ "always_generic": "Das immer erlauben",
+ "ask_verb": "Vor „{verb}“ mit {app} erst fragen",
+ "ask_app": "Vor der Nutzung von {app} erst fragen",
+ "ask_generic": "Nächstes Mal erst fragen",
+ "where_agent": "Wird in den Regeln dieses Agenten gespeichert. Du kannst sie in seinen Einstellungen ändern.",
+ "where_chat": "Fragt in diesem Chat nicht mehr, bis die App neu startet.",
+ "chat_tool": "Fragt in diesem Chat nicht mehr nach {app}.",
+ "chat_all": "Fragt in diesem Chat nach nichts mehr.",
+ "save_allow": "Speichern und erlauben",
+ "back": "Zurück",
+ "always_next_time": "Nächstes Mal immer erlauben",
+ "ask_next_time": "Nächstes Mal erst fragen",
+ "saved": "Regel gespeichert: {rule}",
+ "saved_chat": "In diesem Chat erlaubt: {app}",
+ "saved_short": "Regel gespeichert",
+ "still_asks": "Eine strengere Regel fragt trotzdem zuerst.",
+ "save_failed": "Die Regel ließ sich nicht speichern."
+ }
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index 39449927b1..9be45521de 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -10358,5 +10358,99 @@
"new_other": "{count} new messages",
"dismiss": "Dismiss"
}
+ },
+ "action_card": {
+ "needs_approval": "Needs approval",
+ "source": {
+ "terminal": "Terminal",
+ "files": "Files",
+ "browser": "Browser",
+ "computer": "Computer",
+ "plan": "Plan",
+ "agent": "Helper agent",
+ "connector": "Connector",
+ "tool": "Tool",
+ "secure_field": "Secure field",
+ "proposal": "Suggested change"
+ },
+ "title": {
+ "terminal": "Run this command?",
+ "files": "Change this file?",
+ "browser": "Use the browser?",
+ "computer": "Control this computer?",
+ "plan": "Start building from this plan?",
+ "agent": "Start a helper agent?",
+ "connector": "Use {app}?",
+ "connector_verb": "Use {app} to {verb}?",
+ "tool": "Run {tool}?",
+ "tool_plain": "Run this tool?"
+ },
+ "field": {
+ "in": "In {where}",
+ "on": "On {where}",
+ "why": "“{why}”"
+ },
+ "show_command": "Show command",
+ "hide_command": "Hide command",
+ "show_details": "Show details",
+ "hide_details": "Hide details",
+ "copy": "Copy",
+ "copied": "Copied",
+ "allow_once": "Allow once",
+ "always_allow": "Always allow",
+ "always_allow_more": "Always allow…",
+ "deny": "Deny",
+ "deny_esc": "Deny (Esc)",
+ "elsewhere": "Answer this in the chat it came from.",
+ "plan_build": "Start building",
+ "plan_keep": "Keep planning",
+ "caution": {
+ "irreversible": "This can't be undone.",
+ "security": "This changes security or access settings.",
+ "data_leaves": "This sends data outside this chat."
+ },
+ "outcome": {
+ "allow": "Allowed once",
+ "allow_always": "Always allowed",
+ "deny": "Denied",
+ "expired": "Expired",
+ "cancel": "Closed without an answer"
+ },
+ "outcome_note": {
+ "expired": "Nothing ran: no one answered in time.",
+ "cancel": "Nothing ran: the request ended before anyone answered.",
+ "deny": "The agent was told no and did not do it."
+ },
+ "expand": "Show details",
+ "collapse": "Hide details",
+ "failed": "That did not go through. Try again.",
+ "rule": {
+ "heading": "Make it a rule",
+ "scope_label": "Where the rule applies",
+ "scope_agent": "This agent",
+ "scope_chat": "This chat",
+ "breadth_label": "How far it reaches",
+ "breadth_action": "Only “{verb}”",
+ "breadth_app": "All of {app}",
+ "always_verb": "Always allow “{verb}” with {app}",
+ "always_app": "Always allow {app}",
+ "always_generic": "Always allow this",
+ "ask_verb": "Ask first before “{verb}” with {app}",
+ "ask_app": "Ask first before using {app}",
+ "ask_generic": "Ask first next time",
+ "where_agent": "Saved to this agent's rules. You can change it in the agent's settings.",
+ "where_chat": "Stops asking in this chat until the app restarts.",
+ "chat_tool": "Stops asking for {app} in this chat.",
+ "chat_all": "Stops asking for anything in this chat.",
+ "save_allow": "Save and allow",
+ "back": "Back",
+ "always_next_time": "Always allow next time",
+ "ask_next_time": "Ask first next time",
+ "saved": "Rule saved: {rule}",
+ "saved_chat": "Allowed in this chat: {app}",
+ "saved_short": "Rule saved",
+ "still_asks": "A stricter rule still asks first.",
+ "save_failed": "Could not save the rule."
+ }
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index edb45fdb89..5b772b99d2 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -10358,5 +10358,99 @@
"new_other": "{count} mensajes nuevos",
"dismiss": "Descartar"
}
+ },
+ "action_card": {
+ "needs_approval": "Necesita tu aprobación",
+ "source": {
+ "terminal": "Terminal",
+ "files": "Archivos",
+ "browser": "Navegador",
+ "computer": "Ordenador",
+ "plan": "Plan",
+ "agent": "Agente auxiliar",
+ "connector": "Conector",
+ "tool": "Herramienta",
+ "secure_field": "Campo seguro",
+ "proposal": "Cambio sugerido"
+ },
+ "title": {
+ "terminal": "¿Ejecutar este comando?",
+ "files": "¿Cambiar este archivo?",
+ "browser": "¿Usar el navegador?",
+ "computer": "¿Controlar este ordenador?",
+ "plan": "¿Empezar a construir con este plan?",
+ "agent": "¿Iniciar un agente auxiliar?",
+ "connector": "¿Usar {app}?",
+ "connector_verb": "¿Usar {app} para «{verb}»?",
+ "tool": "¿Ejecutar {tool}?",
+ "tool_plain": "¿Ejecutar esta herramienta?"
+ },
+ "field": {
+ "in": "En {where}",
+ "on": "En {where}",
+ "why": "«{why}»"
+ },
+ "show_command": "Mostrar comando",
+ "hide_command": "Ocultar comando",
+ "show_details": "Mostrar detalles",
+ "hide_details": "Ocultar detalles",
+ "copy": "Copiar",
+ "copied": "Copiado",
+ "allow_once": "Permitir una vez",
+ "always_allow": "Permitir siempre",
+ "always_allow_more": "Permitir siempre…",
+ "deny": "Denegar",
+ "deny_esc": "Denegar (Esc)",
+ "elsewhere": "Responde en el chat del que viene.",
+ "plan_build": "Empezar a construir",
+ "plan_keep": "Seguir planificando",
+ "caution": {
+ "irreversible": "Esto no se puede deshacer.",
+ "security": "Esto cambia ajustes de seguridad o de acceso.",
+ "data_leaves": "Esto envía datos fuera de este chat."
+ },
+ "outcome": {
+ "allow": "Permitido una vez",
+ "allow_always": "Permitido siempre",
+ "deny": "Denegado",
+ "expired": "Caducado",
+ "cancel": "Cerrado sin respuesta"
+ },
+ "outcome_note": {
+ "expired": "No se ejecutó nada: nadie respondió a tiempo.",
+ "cancel": "No se ejecutó nada: la solicitud terminó antes de que alguien respondiera.",
+ "deny": "El agente recibió un no y no lo hizo."
+ },
+ "expand": "Mostrar detalles",
+ "collapse": "Ocultar detalles",
+ "failed": "No se pudo completar. Inténtalo de nuevo.",
+ "rule": {
+ "heading": "Convertirlo en regla",
+ "scope_label": "Dónde se aplica la regla",
+ "scope_agent": "Este agente",
+ "scope_chat": "Este chat",
+ "breadth_label": "Hasta dónde llega",
+ "breadth_action": "Solo «{verb}»",
+ "breadth_app": "Todo {app}",
+ "always_verb": "Permitir siempre «{verb}» con {app}",
+ "always_app": "Permitir siempre {app}",
+ "always_generic": "Permitir siempre esto",
+ "ask_verb": "Preguntar antes de «{verb}» con {app}",
+ "ask_app": "Preguntar antes de usar {app}",
+ "ask_generic": "Preguntar la próxima vez",
+ "where_agent": "Se guarda en las reglas de este agente. Puedes cambiarla en sus ajustes.",
+ "where_chat": "Deja de preguntar en este chat hasta que la app se reinicie.",
+ "chat_tool": "Deja de preguntar por {app} en este chat.",
+ "chat_all": "Deja de preguntar por todo en este chat.",
+ "save_allow": "Guardar y permitir",
+ "back": "Atrás",
+ "always_next_time": "Permitir siempre la próxima vez",
+ "ask_next_time": "Preguntar la próxima vez",
+ "saved": "Regla guardada: {rule}",
+ "saved_chat": "Permitido en este chat: {app}",
+ "saved_short": "Regla guardada",
+ "still_asks": "Una regla más estricta sigue preguntando primero.",
+ "save_failed": "No se pudo guardar la regla."
+ }
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index af8ec29bd9..b4371498cf 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -10358,5 +10358,99 @@
"new_other": "{count} novas mensagens",
"dismiss": "Dispensar"
}
+ },
+ "action_card": {
+ "needs_approval": "Precisa da sua aprovação",
+ "source": {
+ "terminal": "Terminal",
+ "files": "Arquivos",
+ "browser": "Navegador",
+ "computer": "Computador",
+ "plan": "Plano",
+ "agent": "Agente auxiliar",
+ "connector": "Conector",
+ "tool": "Ferramenta",
+ "secure_field": "Campo seguro",
+ "proposal": "Mudança sugerida"
+ },
+ "title": {
+ "terminal": "Executar este comando?",
+ "files": "Alterar este arquivo?",
+ "browser": "Usar o navegador?",
+ "computer": "Controlar este computador?",
+ "plan": "Começar a construir com este plano?",
+ "agent": "Iniciar um agente auxiliar?",
+ "connector": "Usar {app}?",
+ "connector_verb": "Usar {app} para “{verb}”?",
+ "tool": "Executar {tool}?",
+ "tool_plain": "Executar esta ferramenta?"
+ },
+ "field": {
+ "in": "Em {where}",
+ "on": "Em {where}",
+ "why": "“{why}”"
+ },
+ "show_command": "Mostrar comando",
+ "hide_command": "Ocultar comando",
+ "show_details": "Mostrar detalhes",
+ "hide_details": "Ocultar detalhes",
+ "copy": "Copiar",
+ "copied": "Copiado",
+ "allow_once": "Permitir uma vez",
+ "always_allow": "Sempre permitir",
+ "always_allow_more": "Sempre permitir…",
+ "deny": "Negar",
+ "deny_esc": "Negar (Esc)",
+ "elsewhere": "Responda no chat de onde veio.",
+ "plan_build": "Começar a construir",
+ "plan_keep": "Continuar planejando",
+ "caution": {
+ "irreversible": "Isso não pode ser desfeito.",
+ "security": "Isso muda configurações de segurança ou de acesso.",
+ "data_leaves": "Isso envia dados para fora deste chat."
+ },
+ "outcome": {
+ "allow": "Permitido uma vez",
+ "allow_always": "Sempre permitido",
+ "deny": "Negado",
+ "expired": "Expirado",
+ "cancel": "Fechado sem resposta"
+ },
+ "outcome_note": {
+ "expired": "Nada foi executado: ninguém respondeu a tempo.",
+ "cancel": "Nada foi executado: o pedido terminou antes de alguém responder.",
+ "deny": "O agente recebeu um não e não fez isso."
+ },
+ "expand": "Mostrar detalhes",
+ "collapse": "Ocultar detalhes",
+ "failed": "Não deu certo. Tente de novo.",
+ "rule": {
+ "heading": "Transformar em regra",
+ "scope_label": "Onde a regra vale",
+ "scope_agent": "Este agente",
+ "scope_chat": "Este chat",
+ "breadth_label": "Até onde vai",
+ "breadth_action": "Só “{verb}”",
+ "breadth_app": "Tudo de {app}",
+ "always_verb": "Sempre permitir “{verb}” com {app}",
+ "always_app": "Sempre permitir {app}",
+ "always_generic": "Sempre permitir isto",
+ "ask_verb": "Perguntar antes de “{verb}” com {app}",
+ "ask_app": "Perguntar antes de usar {app}",
+ "ask_generic": "Perguntar da próxima vez",
+ "where_agent": "Fica salva nas regras deste agente. Você pode mudá-la nas configurações dele.",
+ "where_chat": "Para de perguntar neste chat até o app reiniciar.",
+ "chat_tool": "Para de perguntar sobre {app} neste chat.",
+ "chat_all": "Para de perguntar sobre tudo neste chat.",
+ "save_allow": "Salvar e permitir",
+ "back": "Voltar",
+ "always_next_time": "Sempre permitir da próxima vez",
+ "ask_next_time": "Perguntar da próxima vez",
+ "saved": "Regra salva: {rule}",
+ "saved_chat": "Permitido neste chat: {app}",
+ "saved_short": "Regra salva",
+ "still_asks": "Uma regra mais rígida ainda pergunta antes.",
+ "save_failed": "Não foi possível salvar a regra."
+ }
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 73dcfb3b1c..fdb32f63fc 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -10358,5 +10358,99 @@
"new_other": "{count} 条新消息",
"dismiss": "关闭"
}
+ },
+ "action_card": {
+ "needs_approval": "需要你的批准",
+ "source": {
+ "terminal": "终端",
+ "files": "文件",
+ "browser": "浏览器",
+ "computer": "电脑",
+ "plan": "计划",
+ "agent": "辅助智能体",
+ "connector": "连接器",
+ "tool": "工具",
+ "secure_field": "安全输入",
+ "proposal": "建议的更改"
+ },
+ "title": {
+ "terminal": "运行这个命令?",
+ "files": "修改这个文件?",
+ "browser": "使用浏览器?",
+ "computer": "控制这台电脑?",
+ "plan": "按这个计划开始构建?",
+ "agent": "启动一个辅助智能体?",
+ "connector": "使用 {app}?",
+ "connector_verb": "用 {app} 执行“{verb}”?",
+ "tool": "运行 {tool}?",
+ "tool_plain": "运行这个工具?"
+ },
+ "field": {
+ "in": "位置:{where}",
+ "on": "网站:{where}",
+ "why": "“{why}”"
+ },
+ "show_command": "显示命令",
+ "hide_command": "隐藏命令",
+ "show_details": "显示详情",
+ "hide_details": "隐藏详情",
+ "copy": "复制",
+ "copied": "已复制",
+ "allow_once": "允许一次",
+ "always_allow": "始终允许",
+ "always_allow_more": "始终允许…",
+ "deny": "拒绝",
+ "deny_esc": "拒绝(Esc)",
+ "elsewhere": "请在它来自的对话中回答。",
+ "plan_build": "开始构建",
+ "plan_keep": "继续规划",
+ "caution": {
+ "irreversible": "此操作无法撤销。",
+ "security": "这会更改安全或访问设置。",
+ "data_leaves": "这会把数据发送到此对话之外。"
+ },
+ "outcome": {
+ "allow": "已允许一次",
+ "allow_always": "已始终允许",
+ "deny": "已拒绝",
+ "expired": "已过期",
+ "cancel": "未回答即关闭"
+ },
+ "outcome_note": {
+ "expired": "没有执行任何操作:无人及时回答。",
+ "cancel": "没有执行任何操作:请求在有人回答前就结束了。",
+ "deny": "智能体收到了拒绝,没有执行。"
+ },
+ "expand": "显示详情",
+ "collapse": "隐藏详情",
+ "failed": "没有成功,请重试。",
+ "rule": {
+ "heading": "设为规则",
+ "scope_label": "规则适用范围",
+ "scope_agent": "这个智能体",
+ "scope_chat": "这个对话",
+ "breadth_label": "覆盖范围",
+ "breadth_action": "仅“{verb}”",
+ "breadth_app": "{app} 的全部操作",
+ "always_verb": "始终允许用 {app} 执行“{verb}”",
+ "always_app": "始终允许 {app}",
+ "always_generic": "始终允许此操作",
+ "ask_verb": "用 {app} 执行“{verb}”前先询问",
+ "ask_app": "使用 {app} 前先询问",
+ "ask_generic": "下次先询问",
+ "where_agent": "保存到这个智能体的规则中,可在它的设置里修改。",
+ "where_chat": "在这个对话中不再询问,直到应用重启。",
+ "chat_tool": "在这个对话中不再询问 {app}。",
+ "chat_all": "在这个对话中不再询问任何操作。",
+ "save_allow": "保存并允许",
+ "back": "返回",
+ "always_next_time": "下次始终允许",
+ "ask_next_time": "下次先询问",
+ "saved": "规则已保存:{rule}",
+ "saved_chat": "已在此对话中允许:{app}",
+ "saved_short": "规则已保存",
+ "still_asks": "仍有更严格的规则会先询问。",
+ "save_failed": "无法保存规则。"
+ }
}
}
diff --git a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
index 0098b7a5ca..7cfea1b9f9 100644
--- a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
@@ -595,24 +595,65 @@ export async function cancelAgentChatTurn(sessionId: string, via = ""): Promise<
export type ApprovalDecision = "allow" | "allow_always" | "deny";
+/** Where an "Always allow" from the card lives (the card's rule chooser). */
+export interface ApprovalRuleChoice {
+ scope: "agent" | "chat";
+ breadth?: "action" | "app";
+}
+
+function approvalUrl(sessionId: string, approvalId: string): string {
+ return `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/approvals/${encodeURIComponent(approvalId)}`;
+}
+
export async function resolveAgentChatApproval(
sessionId: string,
approvalId: string,
decision: ApprovalDecision,
+ rule?: ApprovalRuleChoice,
): Promise<void> {
await json(
- await fetch(
- `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/approvals/${encodeURIComponent(approvalId)}`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ decision }),
- },
- ),
+ await fetch(approvalUrl(sessionId, approvalId), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(
+ rule && decision === "allow_always"
+ ? { decision, scope: rule.scope, breadth: rule.breadth ?? "action" }
+ : { decision },
+ ),
+ }),
"approval-failed",
);
}
+/** A standing rule saved from a settled card: "Always allow next time", "Ask first next time". */
+export interface ApprovalRuleRequest extends ApprovalRuleChoice {
+ kind: "always_allow" | "require_approval";
+}
+
+export interface SavedApprovalRuleReply {
+ kind: string;
+ pattern: string;
+ app?: string;
+ verb?: string;
+ still_asks?: boolean;
+}
+
+export async function saveAgentChatApprovalRule(
+ sessionId: string,
+ approvalId: string,
+ rule: ApprovalRuleRequest,
+): Promise<SavedApprovalRuleReply> {
+ const reply = await json<{ ok: boolean; rule: SavedApprovalRuleReply }>(
+ await fetch(`${approvalUrl(sessionId, approvalId)}/rule`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ kind: rule.kind, scope: rule.scope, breadth: rule.breadth ?? "action" }),
+ }),
+ "approval-rule-failed",
+ );
+ return reply.rule;
+}
+
/** The person's answer to an agent's question: one option, or their own words. */
export type QuestionAnswerInput = { optionIndex: number } | { text: string };
diff --git a/dodaios/ui/web/frontend/src/store/agentChat.ts b/dodaios/ui/web/frontend/src/store/agentChat.ts
index f0894c760b..4b691f900f 100644
--- a/dodaios/ui/web/frontend/src/store/agentChat.ts
+++ b/dodaios/ui/web/frontend/src/store/agentChat.ts
@@ -17,6 +17,7 @@ import {
invalidateAgentChatSessions,
patchAgentChatSession,
resolveAgentChatApproval,
+ saveAgentChatApprovalRule,
answerAgentChatQuestion,
bindVoiceChat,
skipAgentChatQuestion,
@@ -32,12 +33,14 @@ import {
type AgentChatSurface,
type AgentConnectionRow,
type ApprovalDecision,
+ type ApprovalRuleChoice,
+ type ApprovalRuleRequest,
type ChatAttachment,
type CuratedModel,
type PatchSessionInput,
type ProviderHealth,
} from "@/lib/agentChatApi";
-import { EMPTY_TIMELINE, reduceEvent, reduceEvents, settleApproval, type Timeline } from "@/components/agentchat/reduce";
+import { EMPTY_TIMELINE, noteApprovalRule, reduceEvent, reduceEvents, settleApproval, type Timeline } from "@/components/agentchat/reduce";
import { jitteredDelay, requestConnect } from "../lib/connectBudget";
import { reuseHistoryRows } from "@/lib/historyRequests";
@@ -186,7 +189,13 @@ export interface AgentChatStore {
* the backend took the answer, or said nothing waits on it any more; any
* other failure throws so the card can say why.
*/
- decide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
+ decide: (approvalId: string, decision: ApprovalDecision, rule?: ApprovalRuleChoice) => Promise<void>;
+ /**
+ * Turn an approval card into a standing rule after the fact ("Always allow
+ * next time", "Ask first next time"). The card shows it at once; throws so
+ * the card can say why when nothing was saved.
+ */
+ saveApprovalRule: (approvalId: string, rule: ApprovalRuleRequest) => Promise<void>;
/** Answer question `index` of an agent's card in the active session; throws so the card can say why. */
answerQuestion: (questionId: string, index: number, answer: QuestionAnswerInput) => Promise<void>;
/** Close an agent's card so its recommendations apply; throws so the card can say why. */
@@ -880,12 +889,13 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
}
},
- decide: async (approvalId, decision) => {
+ decide: async (approvalId, decision, rule) => {
const sid = get().activeSessionId;
if (!sid) return;
let outcome: string = decision;
try {
- await resolveAgentChatApproval(sid, approvalId, decision);
+ if (rule) await resolveAgentChatApproval(sid, approvalId, decision, rule);
+ else await resolveAgentChatApproval(sid, approvalId, decision);
} catch (err) {
// 410: the card outlived what it asked for (an app restart) and is
// closed now; 404: the backend never knew it. Either way nothing
@@ -894,7 +904,22 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
if (!gone) throw err;
outcome = "expired";
}
- if (get().activeSessionId === sid) set({ timeline: settleApproval(get().timeline, approvalId, outcome) });
+ if (get().activeSessionId === sid) {
+ const scope = outcome === "allow_always" ? rule?.scope : undefined;
+ set({ timeline: settleApproval(get().timeline, approvalId, outcome, "", scope) });
+ }
+ },
+
+ saveApprovalRule: async (approvalId, rule) => {
+ const sid = get().activeSessionId;
+ if (!sid) throw new Error("no open chat");
+ const saved = await saveAgentChatApprovalRule(sid, approvalId, rule);
+ if (get().activeSessionId !== sid) return;
+ // The socket's notice says the same; the card must not wait on it.
+ set({ timeline: noteApprovalRule(get().timeline, approvalId, {
+ kind: rule.kind, scope: rule.scope, pattern: saved.pattern,
+ app: saved.app ?? "", verb: saved.verb ?? "", stillAsks: saved.still_asks === true,
+ }) });
},
answerQuestion: async (questionId, index, answer) => {
diff --git a/dodaios/ui/web/frontend/src/store/newPaneChat.ts b/dodaios/ui/web/frontend/src/store/newPaneChat.ts
index d1b9d95c6f..8bf719ae81 100644
--- a/dodaios/ui/web/frontend/src/store/newPaneChat.ts
+++ b/dodaios/ui/web/frontend/src/store/newPaneChat.ts
@@ -263,6 +263,7 @@ export function createNewPaneChatStore(options: NewPaneChatOptions) {
// shared composer calls them without asking which surface it is on.
cancel: async () => undefined,
decide: async () => undefined,
+ saveApprovalRule: async () => undefined,
answerQuestion: async () => undefined,
skipQuestion: async () => undefined,
resolvePlan: async () => undefined,
diff --git a/dodaios/ui/web/frontend/src/store/paneChat.ts b/dodaios/ui/web/frontend/src/store/paneChat.ts
index 6a48217dd3..2859667946 100644
--- a/dodaios/ui/web/frontend/src/store/paneChat.ts
+++ b/dodaios/ui/web/frontend/src/store/paneChat.ts
@@ -682,6 +682,7 @@ export function createPaneChatStore(options: PaneChatStoreOptions) {
},
// Approvals never come out of a transcript — the CLI asks in its own TUI.
decide: async () => undefined,
+ saveApprovalRule: async () => undefined,
answerQuestion: async () => undefined,
skipQuestion: async () => undefined,
resolvePlan: async () => undefined,
diff --git a/tests/unit/agent_chat/test_approval_card.py b/tests/unit/agent_chat/test_approval_card.py
new file mode 100644
index 0000000000..3b3d3a4d93
--- /dev/null
+++ b/tests/unit/agent_chat/test_approval_card.py
@@ -0,0 +1,669 @@
+"""The approval action card: one card for every approval source, rules from the card.
+
+Every source of an approval (the ToolExecutor bridge behind the brain runner
+and the MCP gateway, the API loop, Claude Code's stdin protocol, ACP
+``session/request_permission`` from Hermes/OpenClaw) ends in
+``AgentChatService._ask``. These tests drive each source with fakes and check
+the same card fields arrive and the same decisions resolve it; then the rules a
+card saves, and that ``society.approvals.decide`` keeps its order.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from dodaios.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_ref
+from dodaios.agent_chat.approval_card import describe_call, request_detail, rule_offer
+from dodaios.agent_chat.service import AgentChatService
+from dodaios.agent_chat.store import AgentChatStore
+from dodaios.core.bus import EventBus
+from dodaios.core.events import ActionApprovalRequired, ActionApproved, ActionProposed
+from dodaios.society import approvals as society_approvals
+from dodaios.society.approvals import Verdict, apply_rule, card_rule, decide, rule_text
+from dodaios.society.capabilities import CapabilityKind, CapabilityRow
+from dodaios.ui.web.agent_chat_routes import router
+
+SECRETS = (
+ "hunter2-correct-horse-battery",
+ # Built at runtime so no credential-shaped literal sits in the source.
+ "sk" + "-proj-" + "q7" * 18,
+ "gh" + "p_" + "Z9" * 20,
+ "xa" + "i-" + "k3" * 16,
+)
+
+
+async def _next(q: asyncio.Queue, kind: str, budget_s: float = 5.0) -> dict[str, Any]:
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + budget_s
+ while True:
+ ev = await asyncio.wait_for(q.get(), timeout=max(0.01, deadline - loop.time()))
+ if ev["kind"] == kind:
+ return ev
+
+
+def _service(tmp_path: Path, *, surface: str = "jarvis", session_id: str | None = None):
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.store.create_session(
+ provider="claude-api",
+ model="m",
+ effort="medium",
+ cwd=str(tmp_path),
+ permission_mode="ask",
+ surface=surface,
+ session_id=session_id,
+ )
+ return svc, session
+
+
+# ------------------------------------------------------------------ display
+
+
+ ("name", "args", "kind", "app", "caution"),
+ [
+ # Brain runner / ToolExecutor bridge: the registry's bare tool name.
+ ("gmail", {"action": "send", "to": "[email protected]"}, "connector", "Gmail", "data_leaves"),
+ # The MCP gateway: this app's own server, under either name.
+ (
+ "mcp__dodaios__google_calendar",
+ {"action": "delete"},
+ "connector",
+ "Google Calendar",
+ "irreversible",
+ ),
+ ("mcp__jarvis__github", {"action": "list"}, "connector", "GitHub", ""),
+ # Another MCP server's tool: that server is the source.
+ ("mcp__notion__create_page", {"title": "x"}, "connector", "Notion", ""),
+ # The API loop's folder tools.
+ ("RunCommand", {"command": "rm -rf build"}, "terminal", "", "irreversible"),
+ ("Write", {"file_path": "a.txt", "content": "x"}, "files", "", ""),
+ # Claude Code over stdin.
+ (
+ "Bash",
+ {"command": "git push --force", "description": "Publish"},
+ "terminal",
+ "",
+ "irreversible",
+ ),
+ ("Bash", {"command": "sudo chmod 777 /etc"}, "terminal", "", "security"),
+ ("Bash", {"command": "git push origin main"}, "terminal", "", "data_leaves"),
+ ("ExitPlanMode", {"plan": "1. x"}, "plan", "", ""),
+ # ACP request_permission (Hermes / OpenClaw): a title-like name.
+ ("execute", {"command": "ls"}, "terminal", "", ""),
+ ("society_browser", {"url": "https://example.com/a"}, "browser", "", ""),
+ ("click", {"x": 1}, "computer", "", ""),
+ ],
+)
+def test_every_source_maps_onto_the_same_card_fields(name, args, kind, app, caution):
+ card = describe_call(name, args, "summary", cwd="C:/work")
+ assert card["source"]["kind"] == kind
+ assert card["source"].get("app", "") == app or kind not in ("connector",)
+ assert card["caution"] == caution
+ if kind in ("terminal", "files"):
+ assert card["where"] == "C:/work"
+ if kind == "plan":
+ assert card["detail"] == "" and card["rule"] is None
+
+
+def test_the_card_carries_the_agents_reason_and_the_site():
+ assert describe_call("Bash", {"command": "npm i", "description": "Install deps"})["why"] == (
+ "Install deps"
+ )
+ assert describe_call("society_browser", {"url": "https://mail.example.com/x"})["where"] == (
+ "mail.example.com"
+ )
+ connector = describe_call("gmail", {"action": "send"})
+ assert connector["source"] == {"kind": "connector", "app": "Gmail", "verb": "send"}
+ # A shell command is never a verb a rule could name.
+ assert "verb" not in describe_call("society_shell", {"command": "rm -rf x"})["source"]
+
+
+def test_secrets_never_reach_the_disclosure():
+ args = {
+ "user": "ada",
+ "password": SECRETS[0],
+ "api_key": SECRETS[1],
+ "nested": {"auth_token": SECRETS[2], "headers": {"Authorization": f"Bearer {SECRETS[3]}"}},
+ "note": f"use {SECRETS[1]} please",
+ "max_tokens": 400,
+ }
+ card = describe_call("mcp__acme__login", args, "Sign in")
+ for secret in SECRETS:
+ assert secret not in json.dumps(card)
+ assert "ada" in card["detail"] and "400" in card["detail"]
+ command = request_detail({}, f"curl -H 'Authorization: Bearer {SECRETS[3]}' https://x")
+ assert SECRETS[3] not in command
+ why = describe_call("Bash", {"command": "x", "description": f"api_key={SECRETS[1]}"})["why"]
+ assert SECRETS[1] not in why
+
+
+def test_describe_never_raises(monkeypatch: pytest.MonkeyPatch):
+ from dodaios.agent_chat import approval_card
+
+ assert describe_call("x", None, "")["source"]["kind"] == "connector" # type: ignore[arg-type]
+ weird = describe_call("tool", {"command": object()})
+ assert weird["source"]["kind"] in ("tool", "connector", "terminal")
+
+ def broken(*_a: Any) -> dict[str, Any]:
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(approval_card, "_describe", broken)
+ assert describe_call("Bash", {"command": "ls"}) == {}
+
+
+def test_rule_offers_per_surface():
+ assert rule_offer("jarvis", "gmail", {}, None) == {
+ "scopes": ["chat"],
+ "chat": "tool",
+ "app": "Gmail",
+ }
+ assert rule_offer("agent", "Bash", {}, None) == {"scopes": ["chat"], "chat": "all"}
+ assert rule_offer("society", "Bash", {}, None) == {"scopes": [], "chat": "runtime"}
+ own = {
+ "capability": "plugin:gmail",
+ "app": "Gmail",
+ "verb": "send",
+ "pattern": "plugin:gmail:send",
+ "broad": "plugin:gmail",
+ }
+ assert rule_offer("society", "gmail", {}, own)["scopes"] == ["agent", "chat"]
+
+
+# ------------------------------------------------------------ every source
+
+
+def test_the_api_loop_and_stdin_shapes_ask_on_the_same_card(tmp_path: Path):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path)
+ q = svc.subscribe(session.session_id)
+ for name, args, answer in (
+ ("RunCommand", {"command": "echo hi"}, "allow"),
+ ("Bash", {"command": "rm -rf build", "description": "Clean"}, "deny"),
+ ("mcp__dodaios__gmail", {"action": "send", "password": SECRETS[0]}, "allow"),
+ ):
+ asking = asyncio.create_task(svc._ask(session.session_id, "t1", "c1", name, args, name)) # noqa: SLF001
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert {"source", "where", "why", "caution", "detail", "rule"} <= payload.keys()
+ assert SECRETS[0] not in payload["detail"]
+ assert svc.resolve_approval(session.session_id, payload["approval_id"], answer)
+ assert await asyncio.wait_for(asking, 2) == answer
+ resolved = (await _next(q, "approval_resolved"))["payload"]
+ assert resolved["decision"] == answer
+
+ asyncio.run(scenario())
+
+
+def test_the_bridge_and_the_mcp_gateway_ask_on_the_same_card(tmp_path: Path):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path)
+ q = svc.subscribe(session.session_id)
+ bus = EventBus()
+ bridge = ChatApprovalBridge(bus)
+ approved: list[ActionApproved] = []
+
+ async def seen(event: ActionApproved) -> None:
+ approved.append(event)
+
+ bus.subscribe(ActionApproved, seen)
+ ref = approval_ref(session.session_id)
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=session.session_id,
+ turn_id="t1",
+ stance="ask",
+ always_allowed=svc.always_allowed(session.session_id),
+ ask=lambda call_id, name, args, summary: svc._ask( # noqa: SLF001
+ session.session_id, "t1", call_id, name, args, summary
+ ),
+ ),
+ )
+ proposed = ActionProposed(tool_name="gmail", args={"action": "send", "to": "[email protected]"})
+ await bus.publish(proposed)
+ await bus.publish(
+ ActionApprovalRequired(trace_id=proposed.trace_id, tool_name="gmail", approval_ref=ref)
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert payload["source"] == {"kind": "connector", "app": "Gmail", "verb": "send"}
+ assert payload["caution"] == "data_leaves"
+ svc.resolve_approval(
+ session.session_id, payload["approval_id"], "allow_always", scope="chat"
+ )
+ notice = (await _next(q, "notice"))["payload"]
+ assert notice["kind"] == "approval_rule" and notice["scope"] == "chat"
+ await asyncio.sleep(0.05)
+ assert approved and approved[-1].approved_by == "user"
+ # The chat-scoped "always" now answers the bridge without a card.
+ assert "gmail" in svc.always_allowed(session.session_id)
+ again = ActionProposed(tool_name="gmail", args={"action": "send"})
+ await bus.publish(again)
+ await bus.publish(
+ ActionApprovalRequired(trace_id=again.trace_id, tool_name="gmail", approval_ref=ref)
+ )
+ await asyncio.sleep(0.05)
+ assert approved[-1].trace_id == again.trace_id
+ assert svc.pending_approvals(session.session_id) == []
+
+ asyncio.run(scenario())
+
+
+def test_acp_request_permission_asks_on_the_same_card(tmp_path: Path):
+ from dodaios.agent_runtimes.acp import AcpTurn
+
+ async def scenario() -> None:
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ q = svc.subscribe(session.session_id)
+
+ class _Io:
+ async def write(self, frame: dict[str, Any]) -> None:
+ pass
+
+ async def emit(self, event: dict[str, Any]) -> None:
+ pass
+
+ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:
+ return await svc._ask(session.session_id, "t1", call_id, name, args, summary) # noqa: SLF001
+
+ turn = AcpTurn(turn_id="t1", cwd=str(tmp_path), prompt_text="x")
+ params = {
+ "toolCall": {
+ "toolCallId": "tc1",
+ "title": "rm -rf build",
+ "kind": "execute",
+ "rawInput": {"command": "rm -rf build"},
+ },
+ "options": [
+ {"kind": "allow_once", "optionId": "o1"},
+ {"kind": "allow_always", "optionId": "o2"},
+ {"kind": "reject_once", "optionId": "o3"},
+ ],
+ }
+ answering = asyncio.create_task(turn._permission(params, _Io())) # noqa: SLF001
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert payload["source"]["kind"] == "terminal"
+ assert payload["caution"] == "irreversible"
+ # A runtime's own tool: its "always" stays the runtime's to remember.
+ assert payload["rule"] == {"scopes": [], "chat": "runtime"}
+ svc.resolve_approval(session.session_id, payload["approval_id"], "allow_always")
+ assert await asyncio.wait_for(answering, 2) == {"outcome": "selected", "optionId": "o2"}
+
+ asyncio.run(scenario())
+
+
+def test_a_card_without_extras_still_asks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ from dodaios.agent_chat import approval_card
+
+ def broken(*_a: Any, **_k: Any) -> dict[str, Any]:
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(approval_card, "rule_offer", broken)
+
+ async def scenario() -> None:
+ svc, session = _service(tmp_path)
+ q = svc.subscribe(session.session_id)
+ asking = asyncio.create_task(svc._ask(session.session_id, "t1", "c1", "Bash", {}, "ls")) # noqa: SLF001
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert payload["name"] == "Bash" and "source" not in payload
+ svc.resolve_approval(session.session_id, payload["approval_id"], "deny")
+ assert await asyncio.wait_for(asking, 2) == "deny"
+
+ asyncio.run(scenario())
+
+
+# ------------------------------------------------------------ rules
+
+
+class _Roster:
+ def __init__(self, agent: Any) -> None:
+ self.agent = agent
+
+ async def get(self, agent_id: str) -> Any:
+ return self.agent if agent_id == self.agent.agent_id else None
+
+ async def update(self, agent_id: str, fields: dict[str, Any]) -> Any:
+ self.agent = SimpleNamespace(**{**vars(self.agent), **fields})
+ return self.agent
+
+
+class _Runtime:
+ def __init__(self, agent: Any) -> None:
+ self.roster = _Roster(agent)
+ self.cached: Any = None
+
+ def catalog(self) -> list[CapabilityRow]:
+ return [
+ CapabilityRow(
+ id="plugin:gmail",
+ kind=CapabilityKind.PLUGIN,
+ label="Gmail",
+ one_liner="",
+ risk_tier="ask",
+ connected=True,
+ tool_name="gmail",
+ )
+ ]
+
+ def cache_agent(self, agent: Any) -> None:
+ self.cached = agent
+
+
+def _agent(**rules: list[str]) -> Any:
+ return SimpleNamespace(
+ agent_id="ada",
+ approval_rules={
+ "require_approval": rules.get("require", []),
+ "always_allow": rules.get("always", []),
+ },
+ approval_mode=None,
+ permission_ceiling="monitor",
+ )
+
+
+def society_runtime(monkeypatch: pytest.MonkeyPatch):
+ from dodaios.society import runtime as runtime_mod
+
+ rt = _Runtime(_agent())
+ monkeypatch.setattr(runtime_mod, "current_runtime", lambda: rt)
+ return rt
+
+
+def test_card_rule_only_for_the_agents_own_tools(society_runtime):
+ assert card_rule("gmail", {"action": "send"}) == {
+ "capability": "plugin:gmail",
+ "app": "Gmail",
+ "verb": "send",
+ "pattern": "plugin:gmail:send",
+ "broad": "plugin:gmail",
+ }
+ assert card_rule("mcp__dodaios__gmail", {})["pattern"] == "plugin:gmail" # type: ignore[index]
+ assert card_rule("Bash", {"command": "ls"}) is None
+ assert card_rule("mcp__notion__create_page", {}) is None
+
+
+def test_rule_text_and_apply_rule():
+ assert rule_text("always_allow", "Gmail", "send") == "Always allow send with Gmail"
+ assert rule_text("require_approval", "Gmail") == "Ask first before Gmail"
+ rules = apply_rule(
+ {"require_approval": ["plugin:gmail:send"], "always_allow": []},
+ "always_allow",
+ "plugin:gmail:send",
+ )
+ assert rules == {"require_approval": [], "always_allow": ["plugin:gmail:send"]}
+ back = apply_rule(rules, "require_approval", "plugin:gmail:send")
+ assert back == {"require_approval": ["plugin:gmail:send"], "always_allow": []}
+ with pytest.raises(ValueError):
+ apply_rule(rules, "never", "x")
+
+
+def test_an_always_saved_on_the_agent_auto_allows_the_next_call(tmp_path: Path, society_runtime):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ q = svc.subscribe(session.session_id)
+ asking = asyncio.create_task(
+ svc._ask(session.session_id, "t1", "c1", "gmail", {"action": "send"}, "Send") # noqa: SLF001
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert payload["rule"]["scopes"] == ["agent", "chat"]
+ assert payload["rule"]["pattern"] == "plugin:gmail:send"
+ svc.resolve_approval(
+ session.session_id,
+ payload["approval_id"],
+ "allow_always",
+ scope="agent",
+ breadth="action",
+ )
+ assert await asyncio.wait_for(asking, 2) == "allow_always"
+ resolved = (await _next(q, "approval_resolved"))["payload"]
+ assert resolved["scope"] == "agent"
+ notice = (await _next(q, "notice"))["payload"]
+ assert notice["kind"] == "approval_rule" and notice["pattern"] == "plugin:gmail:send"
+ agent = society_runtime.roster.agent
+ assert agent.approval_rules["always_allow"] == ["plugin:gmail:send"]
+ assert society_runtime.cached is agent
+ # The session's own stance is untouched: the rule lives on the agent.
+ assert svc.store.get_session(session.session_id).permission_mode == "ask" # type: ignore[union-attr]
+ # The next matching call runs without a card; another verb still asks.
+ assert decide(agent, "plugin:gmail", "ask", verb="send") is Verdict.RUN
+ assert decide(agent, "plugin:gmail", "ask", verb="delete") is Verdict.QUEUE
+
+ asyncio.run(scenario())
+
+
+def test_an_agent_rule_for_one_action_is_not_widened_by_the_bridge(
+ tmp_path: Path, society_runtime
+):
+ """"Only send with Gmail" saved on the agent: the chat must not then wave
+ every Gmail action through (the bridge's own chat-wide "always")."""
+
+ async def scenario() -> None:
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ sid = session.session_id
+ q = svc.subscribe(sid)
+ bus = EventBus()
+ bridge = svc._bridge_for(bus) # noqa: SLF001 — wires the service's hook
+ assert bridge is not None
+ approved: list[ActionApproved] = []
+
+ async def seen(event: ActionApproved) -> None:
+ approved.append(event)
+
+ bus.subscribe(ActionApproved, seen)
+ ref = approval_ref(sid)
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=sid,
+ turn_id="t1",
+ stance="ask",
+ always_allowed=svc.always_allowed(sid),
+ ask=lambda call_id, name, args, summary: svc._ask( # noqa: SLF001
+ sid, "t1", call_id, name, args, summary
+ ),
+ ),
+ )
+ send = ActionProposed(tool_name="gmail", args={"action": "send"})
+ await bus.publish(send)
+ await bus.publish(
+ ActionApprovalRequired(trace_id=send.trace_id, tool_name="gmail", approval_ref=ref)
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(
+ sid, payload["approval_id"], "allow_always", scope="agent", breadth="action"
+ )
+ await _next(q, "notice")
+ await asyncio.sleep(0.05)
+ assert approved and approved[-1].trace_id == send.trace_id
+ assert society_runtime.roster.agent.approval_rules["always_allow"] == ["plugin:gmail:send"]
+ assert "gmail" not in svc.always_allowed(sid)
+ # Another Gmail action still reaches the card.
+ delete = ActionProposed(tool_name="gmail", args={"action": "delete"})
+ await bus.publish(delete)
+ await bus.publish(
+ ActionApprovalRequired(trace_id=delete.trace_id, tool_name="gmail", approval_ref=ref)
+ )
+ again = (await _next(q, "approval_required"))["payload"]
+ assert again["source"]["verb"] == "delete"
+ svc.resolve_approval(sid, again["approval_id"], "deny")
+ await asyncio.sleep(0.05)
+
+ asyncio.run(scenario())
+
+
+def test_a_chat_always_still_covers_the_tool(tmp_path: Path):
+ """Without an agent rule the bridge keeps remembering the tool for the chat."""
+ svc, session = _service(tmp_path)
+ bridge = svc._bridge_for(EventBus()) # noqa: SLF001
+ assert bridge is not None
+ assert bridge.chat_keeps_always(session.session_id, "gmail") is True
+
+
+def test_breadth_is_validated(tmp_path: Path):
+ svc, session = _service(tmp_path)
+ with pytest.raises(ValueError):
+ svc.resolve_approval(session.session_id, "a1", "allow_always", scope="agent", breadth="all")
+
+
+def test_a_rule_saved_after_the_fact(tmp_path: Path, society_runtime):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ sid = session.session_id
+ svc.store.append_event(
+ sid, {"kind": "turn_started", "ts_ms": 1, "payload": {"turn_id": "t1"}}
+ )
+ svc.store.append_event(
+ sid,
+ {
+ "kind": "approval_required",
+ "ts_ms": 2,
+ "payload": {
+ "turn_id": "t1",
+ "approval_id": "old",
+ "call_id": "c1",
+ "name": "gmail",
+ "input": {"action": "send"},
+ "summary": "Send",
+ },
+ },
+ )
+ svc.store.append_event(
+ sid,
+ {
+ "kind": "approval_resolved",
+ "ts_ms": 3,
+ "payload": {
+ "turn_id": "t1",
+ "approval_id": "old",
+ "decision": "expired",
+ },
+ },
+ )
+ rule = await svc.save_approval_rule(
+ sid, "old", kind="always_allow", scope="agent", breadth="app"
+ )
+ assert rule["pattern"] == "plugin:gmail"
+ assert society_runtime.roster.agent.approval_rules["always_allow"] == ["plugin:gmail"]
+ undo = await svc.save_approval_rule(
+ sid, "old", kind="require_approval", scope="agent", breadth="app"
+ )
+ assert undo["pattern"] == "plugin:gmail"
+ assert society_runtime.roster.agent.approval_rules == {
+ "require_approval": ["plugin:gmail"],
+ "always_allow": [],
+ }
+ last = svc.store.list_events(sid)[-1]
+ assert last["kind"] == "notice" and last["payload"]["rule_kind"] == "require_approval"
+ with pytest.raises(KeyError):
+ await svc.save_approval_rule(sid, "never-shown", kind="always_allow", scope="agent")
+
+ asyncio.run(scenario())
+
+
+def test_decide_keeps_its_order_after_card_rules():
+ """Regression: the card writes patterns; it never changes how they are read."""
+ allowed = _agent(always=["plugin:gmail:send"])
+ assert decide(allowed, "plugin:gmail", "ask", verb="send") is Verdict.RUN
+ # An explicit "ask first" still wins over a standing yes.
+ both = _agent(require=["plugin:gmail:*"], always=["plugin:gmail:send"])
+ assert decide(both, "plugin:gmail", "ask", verb="send") is Verdict.QUEUE
+ # Always ask ignores a standing yes.
+ assert decide(allowed, "plugin:gmail", "ask", verb="send", approval_mode="always_ask") is (
+ Verdict.QUEUE
+ )
+ # A standing yes never lifts a blocked tool class.
+ assert decide(allowed, "plugin:gmail", "block", verb="send") is Verdict.BLOCK
+
+
+def test_still_asks_reports_a_broader_ask_first(tmp_path: Path, society_runtime):
+ society_runtime.roster.agent = _agent(require=["plugin:gmail:*"])
+
+ async def scenario() -> None:
+ rule = await society_approvals.save_card_rule(
+ "society:ada", "gmail", {"action": "send"}, kind="always_allow"
+ )
+ assert rule is not None and rule["still_asks"] is True
+
+ asyncio.run(scenario())
+
+
+# ------------------------------------------------------------ routes
+
+
+def _app(tmp_path: Path) -> FastAPI:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = AgentChatService(AgentChatStore(":memory:"))
+ return app
+
+
+def test_the_rule_route(tmp_path: Path):
+ app = _app(tmp_path)
+ svc: AgentChatService = app.state.agent_chat
+ with TestClient(app) as client:
+ jarvis = svc.store.create_session(
+ provider="claude-api", model="m", effort="medium", cwd=str(tmp_path), surface="jarvis"
+ ).session_id
+ coding = svc.store.create_session(
+ provider="claude-api", model="m", effort="medium", cwd=str(tmp_path), surface="agent"
+ ).session_id
+ for sid in (jarvis, coding):
+ svc.store.append_event(
+ sid,
+ {
+ "kind": "approval_required",
+ "ts_ms": 2,
+ "payload": {
+ "turn_id": "t1",
+ "approval_id": "a1",
+ "call_id": "c1",
+ "name": "gmail",
+ "input": {},
+ "summary": "s",
+ },
+ },
+ )
+ url = "/api/agent-chat/sessions/{}/approvals/{}/rule"
+ ok = client.post(url.format(jarvis, "a1"), json={"kind": "always_allow", "scope": "chat"})
+ assert ok.status_code == 200 and ok.json()["rule"]["pattern"] == "gmail"
+ assert "gmail" in svc.always_allowed(jarvis)
+ # A coding chat's "always" would silence the whole chat: never after the fact.
+ refused = client.post(
+ url.format(coding, "a1"), json={"kind": "always_allow", "scope": "chat"}
+ )
+ assert refused.status_code == 409
+ assert (
+ client.post(
+ url.format(jarvis, "zz"), json={"kind": "always_allow", "scope": "chat"}
+ ).status_code
+ == 404
+ )
+ assert (
+ client.post(
+ url.format(jarvis, "a1"), json={"kind": "never", "scope": "chat"}
+ ).status_code
+ == 400
+ )
+ assert (
+ client.post(
+ url.format(jarvis, "a1"), json={"kind": "always_allow", "scope": "x"}
+ ).status_code
+ == 400
+ )
+ bad_scope = client.post(
+ f"/api/agent-chat/sessions/{jarvis}/approvals/a1",
+ json={"decision": "allow_always", "scope": "planet"},
+ )
+ assert bad_scope.status_code == 400
+ bad_breadth = client.post(
+ f"/api/agent-chat/sessions/{jarvis}/approvals/a1",
+ json={"decision": "allow_always", "scope": "agent", "breadth": "planet"},
+ )
+ assert bad_breadth.status_code == 400