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.

fix(agents): safe seat defaults, starter name field, Always-allow rule editor, short paths (#927)

Ruben Lütke4467b6383b8e
diff --git a/dodaios/agent_chat/approval_card.py b/dodaios/agent_chat/approval_card.py
index bb4819dc36..9165583a99 100644
--- a/dodaios/agent_chat/approval_card.py
+++ b/dodaios/agent_chat/approval_card.py
@@ -23,14 +23,23 @@ event has none of them and the card falls back to the tool name and summary.
``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).
+ the card offers no "Always allow" at all (a plan). ``rule.narrow``
+ lists the narrower chat rules this call allows (:func:`narrow_options`):
+ only this folder, only this exact command.
+``brief`` the summary as the card's one-line outcome shows it: paths inside
+ the chat's folder relative to it, the home folder as ``~``
+ (:func:`display_paths`). The full path stays in ``detail``.
+
+``where`` and ``why`` are shortened the same way.
"""
from __future__ import annotations
import json
import logging
+import os
import re
+from pathlib import Path
from typing import Any, Final
from urllib.parse import urlparse
@@ -161,17 +170,159 @@ def _describe(
verb = action_verb(args)
if kind == "connector" and verb:
source = {**source, "verb": verb}
+ if rule is not None and kind != "plan":
+ narrow = narrow_options(kind, args, cwd)
+ if narrow:
+ rule = {**rule, "narrow": narrow}
fields: dict[str, Any] = {
"source": source,
- "where": _where(kind, args, cwd),
- "why": _why(args),
+ "where": display_paths(_where(kind, args, cwd), cwd),
+ "why": display_paths(_why(args), cwd),
"caution": caution_of(kind, command, verb),
"detail": "" if kind == "plan" else request_detail(args, command),
"rule": None if kind == "plan" else rule,
+ "brief": display_paths(redact_secrets(summary or ""), cwd)[:_LINE_CHARS],
}
return fields
+# ------------------------------------------------------------ paths as shown
+
+_SEP: Final[str] = r"[\\/]"
+_PATH_END: Final[str] = r"(?=[\\/]|$|[\s\"'`)\],;:])"
+
+
+def _path_pattern(folder: str) -> re.Pattern[str] | None:
+ """``folder`` as a regex that accepts either slash (and any case on Windows)."""
+ text = folder.strip()
+ parts = [p for p in re.split(r"[\\/]+", text) if p]
+ if not parts:
+ return None
+ body = (_SEP + "+").join(re.escape(p) for p in parts)
+ lead = _SEP if text[:1] in ("\\", "/") else ""
+ flags = re.IGNORECASE if os.name == "nt" or re.match(r"^[A-Za-z]:", text) else 0
+ return re.compile(lead + body + _PATH_END, flags)
+
+
+def _same_folder(a: str, b: str) -> bool:
+ return os.path.normcase(os.path.normpath(a)) == os.path.normcase(os.path.normpath(b))
+
+
+def display_paths(text: str, cwd: str = "", home: str | None = None) -> str:
+ """``text`` with paths shortened for the card's visible lines.
+
+ A path inside the chat's folder reads relative to it (``src/app.py``), the
+ home folder reads as ``~``. Display only: the stored input, the request
+ detail and every policy keep the full path.
+ """
+ if not text:
+ return text
+ out = text
+ folder = (cwd or "").strip().rstrip("\\/")
+ home_dir = (home if home is not None else str(Path.home())).strip().rstrip("\\/")
+ if len(folder) > 3 and not (home_dir and _same_folder(folder, home_dir)):
+ inside = _path_pattern(folder)
+ if inside is not None:
+ # "<cwd>/src/x" -> "src/x"; the folder alone stays and is shortened below.
+ out = re.sub(inside.pattern + _SEP + r"+(?=\S)", "", out, flags=inside.flags)
+ if len(home_dir) > 3:
+ at_home = _path_pattern(home_dir)
+ if at_home is not None:
+ out = at_home.sub("~", out)
+ return out
+
+
+#: The argument names a file tool passes its path in.
+_PATH_KEYS: Final[tuple[str, ...]] = (
+ "file_path",
+ "path",
+ "filePath",
+ "notebook_path",
+ "target_file",
+)
+_NARROW_COMMAND_CHARS: Final[int] = 400
+
+
+def _call_paths(args: dict[str, Any]) -> list[str]:
+ return [v.strip() for k in _PATH_KEYS if isinstance(v := args.get(k), str) and v.strip()]
+
+
+def _absolute(path: str, cwd: str) -> str:
+ raw = Path(path)
+ if not raw.is_absolute() and cwd:
+ raw = Path(cwd) / raw
+ return os.path.normpath(str(raw))
+
+
+def _holds_home(folder: str, home: str | None = None) -> bool:
+ """Whether ``folder`` is the home folder or one above it: far too wide to
+ read as "only this folder"."""
+ home_dir = home if home is not None else str(Path.home())
+ if not home_dir:
+ return False
+ root = os.path.normcase(os.path.normpath(folder))
+ try:
+ return os.path.commonpath([root, os.path.normcase(os.path.normpath(home_dir))]) == root
+ except ValueError: # another drive
+ return False
+
+
+def narrow_options(
+ kind: str, args: dict[str, Any], cwd: str = "", home: str | None = None
+) -> list[dict[str, str]]:
+ """The narrower chat rules a card may save for this call.
+
+ ``folder``: this tool, for files inside the folder of the path it touches
+ (never the home folder itself or one above it).
+ ``command``: this exact command, nothing else. ``value`` is what a later
+ call is matched against; ``label`` is how the card shows it.
+ """
+ out: list[dict[str, str]] = []
+ if kind == "files":
+ paths = _call_paths(args)
+ if paths:
+ folder = os.path.dirname(_absolute(paths[0], cwd))
+ if folder and folder != os.path.dirname(folder) and not _holds_home(folder, home):
+ shown = display_paths(folder, cwd, home)
+ out.append({"kind": "folder", "value": folder, "label": shown[:_LINE_CHARS]})
+ elif kind == "terminal":
+ command = " ".join(_command_text(args).split())
+ if command and len(command) <= _NARROW_COMMAND_CHARS:
+ label = display_paths(redact_secrets(command), cwd)[:_LINE_CHARS]
+ out.append({"kind": "command", "value": command, "label": label})
+ return out
+
+
+def narrow_tool(name: str) -> str:
+ """The tool name a narrow chat rule is saved under and matched against."""
+ return own_cli_tool(name) or name
+
+
+def narrow_matches(rule: dict[str, str], name: str, args: dict[str, Any], cwd: str = "") -> bool:
+ """Whether a saved narrow chat rule covers this call (same tool, same reach)."""
+ if str(rule.get("tool") or "").lower() != narrow_tool(name).lower():
+ return False
+ value = str(rule.get("value") or "")
+ if not value:
+ return False
+ if rule.get("kind") == "command":
+ return " ".join(_command_text(args).split()) == value
+ if rule.get("kind") == "folder":
+ paths = _call_paths(args)
+ if not paths:
+ return False
+ root = os.path.normcase(os.path.normpath(value))
+ for path in paths:
+ full = os.path.normcase(_absolute(path, cwd))
+ try:
+ if os.path.commonpath([root, full]) != root:
+ return False
+ except ValueError: # another drive
+ return False
+ return True
+ return False
+
+
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)
@@ -350,7 +501,11 @@ __all__ = [
"app_label",
"caution_of",
"describe_call",
+ "display_paths",
"mask_secrets",
+ "narrow_matches",
+ "narrow_options",
+ "narrow_tool",
"request_detail",
"rule_offer",
"source_of",
diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.py
index 67d817c444..e3caf8d69a 100644
--- a/dodaios/agent_chat/service.py
+++ b/dodaios/agent_chat/service.py
@@ -171,6 +171,9 @@ DECISIONS: tuple[str, ...] = ("allow", "allow_always", "deny")
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")
+#: How narrow a chat rule from the card is: only this folder, only this command
+#: (approval_card.narrow_options). Empty: the whole tool, as before.
+RULE_NARROWS: tuple[str, ...] = ("folder", "command")
class SessionBusy(RuntimeError):
@@ -494,8 +497,12 @@ class AgentChatService:
# 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]] = {}
+ # ``(scope, breadth, narrow)`` as the card's rule editor sent it.
+ self._approval_choice: dict[str, tuple[str, str, str]] = {}
+ # Narrow chat rules from the card ("only this folder", "only this
+ # command"), per session: a matching call runs without a card. They
+ # live as long as the app runs, like the chat's other "always".
+ self._narrow_rules: dict[str, list[dict[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).
@@ -2122,6 +2129,9 @@ class AgentChatService:
) -> str:
# The same tool call asked again after a restart answers on the card
# the person already sees (_hold_unanswered_approvals).
+ if self._narrow_allows(session_id, name, args):
+ # The person's own narrow rule from an earlier card covers this call.
+ return "allow"
held = self._unanswered.pop((session_id, turn_id, call_id), "") if call_id else ""
approval_id = held if held and held not in self._approvals else uuid.uuid4().hex
loop = asyncio.get_running_loop()
@@ -2179,19 +2189,36 @@ class AgentChatService:
if decision == "allow_always":
session = self.store.get_session(session_id)
if choice is not None and session is not None:
+ scope, breadth, narrow = choice
try:
saved = await self._rule_from_card(
- session, approval_id, turn_id, name, args, "always_allow", *choice
+ session,
+ approval_id,
+ turn_id,
+ name,
+ args,
+ "always_allow",
+ scope,
+ breadth,
+ narrow,
)
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 narrow:
+ # Only the narrow rule was asked for: the runtime that
+ # asked must not widen it to the whole tool.
+ return "allow"
if choice[0] == "agent":
from .approval_bridge import _bare
self._ruled_on_agent.setdefault(session_id, set()).add(_bare(name))
return decision
+ if narrow:
+ # A narrow rule that could not be saved never widens to the
+ # whole tool or the whole chat: this call runs once.
+ return "allow"
handled = False
hook = kit_for(session.surface).session_always_allow if session is not None else None
if hook is not None:
@@ -2203,7 +2230,10 @@ class AgentChatService:
log.warning("agent chat: always-allow hook failed for %s", name, exc_info=True)
if handled:
pass
- elif session is not None and session.surface == "jarvis":
+ elif session is not None and session.surface in ("jarvis", "society"):
+ # A society chat whose tool no agent rule governs (a runtime's
+ # own Edit or Bash) stops asking for that one tool, never for
+ # the whole chat.
self._always_allowed.setdefault(session_id, set()).add(name)
else:
self.store.update_session(session_id, permission_mode="auto")
@@ -2224,22 +2254,28 @@ class AgentChatService:
*,
scope: str = "",
breadth: str = "",
+ narrow: 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."""
+ lives (the card's rule editor), ``narrow`` how far a chat rule reaches;
+ 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 narrow and narrow not in RULE_NARROWS:
+ raise ValueError(f"narrow must be one of {RULE_NARROWS}")
+ if narrow and scope != "chat":
+ raise ValueError("a narrow rule lives in this chat")
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")
+ self._approval_choice[approval_id] = (scope, breadth or "action", narrow)
fut.set_result(decision)
return True
@@ -2274,6 +2310,7 @@ class AgentChatService:
kind: str,
scope: str,
breadth: str,
+ narrow: str = "",
) -> dict[str, Any] | None:
"""Save the rule a card asked for and note it on the card; ``None`` if none fits.
@@ -2286,7 +2323,9 @@ class AgentChatService:
from .approval_card import app_label
rule: dict[str, Any] | None = None
- if scope == "agent" and session.surface == "society":
+ if narrow:
+ rule = self._narrow_rule_from_card(session, name, args or {}, kind, scope, narrow)
+ elif scope == "agent" and session.surface == "society":
from dodaios.society.approvals import save_card_rule
rule = await save_card_rule(
@@ -2316,11 +2355,65 @@ class AgentChatService:
"app": rule.get("app", ""),
"verb": rule.get("verb", ""),
"still_asks": bool(rule.get("still_asks")),
+ **(
+ {"narrow": rule["narrow"], "target": rule.get("target", "")}
+ if rule.get("narrow")
+ else {}
+ ),
},
),
)
return rule
+ def _narrow_rule_from_card(
+ self,
+ session: Any,
+ name: str,
+ args: dict[str, Any],
+ kind: str,
+ scope: str,
+ narrow: str,
+ ) -> dict[str, Any] | None:
+ """Remember "only this folder" / "only this command" for this chat."""
+ from .approval_card import app_label, narrow_options, narrow_tool, source_of
+
+ if kind != "always_allow" or scope != "chat":
+ return None
+ cwd = str(session.cwd or "")
+ offered = narrow_options(source_of(name, args)["kind"], args, cwd)
+ match = next((o for o in offered if o["kind"] == narrow), None)
+ if match is None:
+ return None
+ # The same name narrow_matches compares against later.
+ bare = narrow_tool(name)
+ rules = self._narrow_rules.setdefault(session.session_id, [])
+ entry = {"tool": bare, "kind": narrow, "value": match["value"]}
+ if entry not in rules:
+ rules.append(entry)
+ return {
+ "kind": kind,
+ "pattern": f"{narrow}:{match['value']}",
+ "app": app_label(bare),
+ "verb": "",
+ "narrow": narrow,
+ "target": match["label"],
+ }
+
+ def _narrow_allows(self, session_id: str, name: str, args: dict[str, Any]) -> bool:
+ """Whether a narrow chat rule saved from an earlier card covers this call."""
+ rules = self._narrow_rules.get(session_id)
+ if not rules:
+ return False
+ from .approval_card import narrow_matches
+
+ session = self.store.get_session(session_id)
+ cwd = str(session.cwd or "") if session is not None else ""
+ try:
+ return any(narrow_matches(rule, name, args or {}, cwd) for rule in rules)
+ except Exception: # noqa: BLE001 — no match: the card asks as usual
+ log.warning("agent chat: narrow rule check failed for %s", name, exc_info=True)
+ return False
+
async def save_approval_rule(
self,
session_id: str,
@@ -2329,12 +2422,15 @@ class AgentChatService:
kind: str,
scope: str,
breadth: str = "action",
+ narrow: str = "",
) -> dict[str, Any]:
"""A rule from a card already answered (or expired): "Allow every
time", "Check with me every 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}")
+ if narrow and narrow not in RULE_NARROWS:
+ raise ValueError(f"narrow must be one of {RULE_NARROWS}")
session = self.store.get_session(session_id)
if session is None:
raise KeyError(session_id)
@@ -2358,6 +2454,7 @@ class AgentChatService:
kind,
scope,
breadth,
+ narrow,
)
if rule is None:
raise LookupError("no rule fits this card")
diff --git a/dodaios/society/surface.py b/dodaios/society/surface.py
index 1e055ce17f..ea58b4bad1 100644
--- a/dodaios/society/surface.py
+++ b/dodaios/society/surface.py
@@ -553,14 +553,19 @@ async def remember_always_allow(session: Any, tool_name: str, args: dict[str, An
"""The card's "Always allow" on a society session writes the agent's OWN
rule (``approval_rules.always_allow``: ``capability`` or ``capability:verb``)
instead of flipping the session to auto. Returns False when this is not a
- society session or the tool has no capability id, so the caller falls back.
+ society session or the tool is not one the agent's own rules govern (a
+ runtime's own ``Edit`` or ``Bash`` has no catalog row: writing
+ ``plugin:edit`` for it would read as a rule and govern nothing), so the
+ caller falls back.
"""
+ from .approvals import card_rule
+
rt = current_runtime()
agent_id = agent_id_of(getattr(session, "session_id", "") or "")
if rt is None or agent_id is None:
return False
cap_id = capability_id_for_tool(tool_name)
- if cap_id is None:
+ if cap_id is None or card_rule(tool_name, args or {}) is None:
return False
agent = await rt.roster.get(agent_id)
if agent is None:
diff --git a/dodaios/ui/web/agent_chat_routes.py b/dodaios/ui/web/agent_chat_routes.py
index bf8b825a5d..70ca2ef711 100644
--- a/dodaios/ui/web/agent_chat_routes.py
+++ b/dodaios/ui/web/agent_chat_routes.py
@@ -79,6 +79,7 @@ from dodaios.agent_chat.permissions import (
from dodaios.agent_chat.service import (
DECISIONS,
RULE_BREADTHS,
+ RULE_NARROWS,
RULE_SCOPES,
AgentChatService,
NoSuchSession,
@@ -279,12 +280,16 @@ class ApprovalBody(BaseModel):
#: Where an "Always allow" lives (the card's rule chooser); empty = as before.
scope: str = ""
breadth: str = ""
+ #: A narrower chat rule: ``folder`` (only this folder) or ``command``
+ #: (only this exact command); empty = the whole tool.
+ narrow: str = ""
class ApprovalRuleBody(BaseModel):
kind: str
scope: str
breadth: str = "action"
+ narrow: str = ""
class CredentialBody(BaseModel):
@@ -1378,8 +1383,19 @@ async def resolve_approval(
raise HTTPException(
status_code=400, detail=f"breadth must be one of {list(RULE_BREADTHS)}"
)
+ if body.narrow and body.narrow not in RULE_NARROWS:
+ raise HTTPException(
+ status_code=400, detail=f"narrow must be one of {list(RULE_NARROWS)}"
+ )
+ if body.narrow and body.scope != "chat":
+ raise HTTPException(status_code=400, detail="a narrow rule needs scope chat")
ok = svc.resolve_approval(
- session_id, approval_id, body.decision, scope=body.scope, breadth=body.breadth
+ session_id,
+ approval_id,
+ body.decision,
+ scope=body.scope,
+ breadth=body.breadth,
+ narrow=body.narrow,
)
if not ok:
if await svc.close_stale_approval(session_id, approval_id):
@@ -1408,7 +1424,12 @@ async def save_approval_rule(
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
+ session_id,
+ approval_id,
+ kind=body.kind,
+ scope=body.scope,
+ breadth=body.breadth,
+ narrow=body.narrow,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
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
index 28e8f59ee9..5428a6b36e 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.test.tsx
@@ -133,9 +133,12 @@ describe("the approval action card", () => {
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");
+ // Even an old card never saves on the first click: the editor asks first.
await act(async () => { fireEvent.click(screen.getByTestId("action-card-always")); });
- expect(onDecide).toHaveBeenCalledWith("a1", "allow_always");
+ expect(onDecide).not.toHaveBeenCalled();
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow this");
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-rule-save")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always", { scope: "chat", breadth: "action" });
});
it("says why an answer was not sent and lets the person try again", async () => {
@@ -147,6 +150,114 @@ describe("the approval action card", () => {
});
});
+const EDIT_CARD = {
+ source: { kind: "files" }, where: "~\\Desktop\\proj", why: "", caution: "",
+ detail: "{\n \"file_path\": \"C:\\\\Users\\\\Ada\\\\Desktop\\\\proj\\\\src\\\\app.py\"\n}",
+ brief: "Edit src\\app.py",
+ rule: { scopes: [], chat: "runtime", narrow: [{ kind: "folder", label: "src" }] },
+};
+
+function editAsking(): AgentChatEvent[] {
+ return [
+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "Edit", input: { file_path: "C:\\Users\\Ada\\Desktop\\proj\\src\\app.py" } }),
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "Edit",
+ input: { file_path: "C:\\Users\\Ada\\Desktop\\proj\\src\\app.py" },
+ summary: "Edit C:\\Users\\Ada\\Desktop\\proj\\src\\app.py", ...EDIT_CARD,
+ }),
+ ];
+}
+
+describe("Always allow as a rule editor", () => {
+ it("never saves on the first click, and Cancel saves nothing", async () => {
+ const { onDecide } = drawTurn(editAsking());
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-always")); });
+ expect(onDecide).not.toHaveBeenCalled();
+ expect(screen.getByTestId("action-card-rule")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("action-card-rule-cancel"));
+ expect(screen.queryByTestId("action-card-rule")).toBeNull();
+ expect(onDecide).not.toHaveBeenCalled();
+ expect(screen.getByTestId("action-card-allow")).toBeTruthy();
+ });
+
+ it("offers this folder first and saves it only on Save", async () => {
+ const { onDecide } = drawTurn(editAsking());
+ fireEvent.click(screen.getByTestId("action-card-always"));
+ expect(screen.getByRole("radio", { name: "Only this folder" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow changes to files in src");
+ expect(screen.getByTestId("action-card-rule-where").textContent).toBe("Stops asking in this chat until the app restarts.");
+ fireEvent.click(screen.getByRole("radio", { name: "This whole tool" }));
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow this");
+ fireEvent.click(screen.getByRole("radio", { name: "Only this folder" }));
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-rule-save")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always", { scope: "chat", breadth: "action", narrow: "folder" });
+ });
+
+ it("offers this exact command on a terminal card", async () => {
+ const { onDecide } = drawTurn([
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "Bash", input: { command: "npm test" },
+ summary: "npm test", source: { kind: "terminal" }, where: "", why: "", caution: "", detail: "npm test",
+ rule: { scopes: ["chat"], chat: "all", narrow: [{ kind: "command", label: "npm test" }] },
+ }),
+ ]);
+ fireEvent.click(screen.getByTestId("action-card-always"));
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow the command npm test");
+ fireEvent.click(screen.getByRole("radio", { name: "Everything in this chat" }));
+ expect(screen.getByTestId("action-card-rule-text").textContent).toBe("Always allow everything in this chat");
+ expect(screen.getByTestId("action-card-rule-where").textContent).toBe("Stops asking for anything in this chat.");
+ fireEvent.click(screen.getByRole("radio", { name: "Only this command" }));
+ await act(async () => { fireEvent.click(screen.getByTestId("action-card-rule-save")); });
+ expect(onDecide).toHaveBeenCalledWith("a1", "allow_always", { scope: "chat", breadth: "action", narrow: "command" });
+ });
+
+ it("reads a saved narrow rule back on the outcome line", () => {
+ drawTurn([
+ ...editAsking(),
+ ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow_always", scope: "chat" }),
+ ev("notice", {
+ kind: "approval_rule", turn_id: "t1", approval_id: "a1", rule_kind: "always_allow", scope: "chat",
+ pattern: "folder:C:\\Users\\Ada\\Desktop\\proj\\src", app: "Edit", verb: "", still_asks: false,
+ narrow: "folder", target: "src",
+ }),
+ ]);
+ const outcome = screen.getByTestId("approval-outcome");
+ expect(outcome.textContent).toContain("Always allowed");
+ expect(screen.getByTestId("action-card-rule-saved").getAttribute("title"))
+ .toBe("Allowed in this chat: Always allow changes to files in src");
+ });
+});
+
+describe("paths on an approval card", () => {
+ it("shows them short on the card and on its outcome line, in full only in the details", () => {
+ const { rerender } = drawTurn(editAsking());
+ const card = screen.getByTestId("thread-approval");
+ expect(card.textContent).toContain("Edit src\\app.py");
+ expect(card.textContent).toContain("In ~\\Desktop\\proj");
+ expect(card.textContent).not.toContain("C:\\Users\\Ada");
+ fireEvent.click(screen.getByRole("button", { name: "Show details" }));
+ expect(screen.getByTestId("action-card-detail").textContent).toContain("Users");
+ rerender([...editAsking(), ev("approval_resolved", { turn_id: "t1", approval_id: "a1", decision: "allow" })]);
+ const outcome = screen.getByTestId("approval-outcome");
+ expect(outcome.textContent).toContain("Edit src\\app.py");
+ expect(outcome.textContent).not.toContain("C:\\Users\\Ada");
+ });
+
+ it("hides the home folder on an event written before the backend shortened paths", () => {
+ drawTurn([
+ ev("approval_required", {
+ turn_id: "t1", approval_id: "a1", call_id: "c1", name: "Write",
+ input: { file_path: "C:\\Users\\Ada\\notes.md", cwd: "C:\\Users\\Ada\\proj" },
+ summary: "Write C:\\Users\\Ada\\notes.md",
+ }),
+ ]);
+ const card = screen.getByTestId("thread-approval");
+ expect(card.textContent).toContain("Write ~\\notes.md");
+ expect(card.textContent).toContain("In ~\\proj");
+ expect(card.textContent).not.toContain("C:\\Users\\Ada");
+ });
+});
+
describe("Esc on an approval card", () => {
it("denies once, and only the newest open card", async () => {
const onDecide = vi.fn();
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
index c863e412be..b3261be1c9 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
@@ -8,8 +8,8 @@ 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 { approvalTitle, cardInfoOf, narrowSentence, outcomeLabel, outcomeTone, ruleSentence, savedRuleSentence, shownSummary, sourceLabel } from "./approvalCopy";
+import type { ApprovalCardInfo, ApprovalRuleOffer, RuleBreadth, RuleNarrow, 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. */
@@ -19,9 +19,10 @@ 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
+ * "Allow once" first (it answers at once); "Always allow" never saves on its
+ * own: it opens a small rule editor (the rule as a sentence; this agent or
+ * this chat; this action or the whole app, this folder or this command) and
+ * only its Save answers. 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 }) {
@@ -65,8 +66,8 @@ function subtitleLines(info: ApprovalCardInfo, approval: ApprovalState, title: s
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);
+ const what = shownSummary(info, approval.summary);
+ const repeatsCommand = kind === "terminal" && Boolean(info.detail) && info.detail.startsWith(approval.summary.trim());
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;
@@ -94,7 +95,6 @@ function OpenApproval({ block, approval, info, onDecide }: {
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) => {
@@ -130,8 +130,8 @@ function OpenApproval({ block, approval, info, onDecide }: {
: [
{ 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)),
+ id: "allow_always", label: t("action_card.always_allow_more"), tone: "secondary" as const,
+ onSelect: () => setChoosing(true),
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" },
@@ -162,39 +162,78 @@ function OpenApproval({ block, approval, info, onDecide }: {
</ActionCard>;
}
-/** "Make it a rule": where the "always" lives and how wide it reaches, read back as a sentence. */
+/** How far a chat rule reaches: one narrow option, or the whole tool / chat. */
+type Reach = RuleNarrow | "tool";
+
+/** The rule as one sentence, for the scope and reach picked in the editor. */
+export function editorSentence(offer: ApprovalRuleOffer, scope: RuleScope, breadth: RuleBreadth, reach: Reach, t: T): string {
+ if (scope === "agent") return ruleSentence("always_allow", offer.app, breadth === "action" ? offer.verb : "", t);
+ const narrow = reach === "tool" ? null : offer.narrow.find((option) => option.kind === reach);
+ if (narrow) return narrowSentence(narrow.kind, narrow.label, t);
+ if (offer.chat === "all") return t("action_card.rule.always_everything");
+ return ruleSentence("always_allow", offer.app, "", t);
+}
+
+function whereLine(offer: ApprovalRuleOffer, scope: RuleScope, reach: Reach, t: T): string {
+ if (scope === "agent") return t("action_card.rule.where_agent");
+ if (reach === "tool" && offer.chat === "all") return t("action_card.rule.chat_all");
+ return t("action_card.rule.where_chat");
+}
+
+/**
+ * "Always allow" as a small rule editor: the rule read back as a sentence,
+ * where it lives (this agent / this chat) and how far it reaches (one
+ * action or the whole app on the agent; only this folder or this command,
+ * or the whole tool, in the chat). Nothing is saved until Save; Cancel goes
+ * back to the card's three answers. The narrowest reach is picked first.
+ */
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");
+ // "This chat" is always possible: a runtime that remembers its own "always"
+ // remembers it for this chat, and a surface without its own memory stops
+ // asking in this chat (the sentence says which).
+ const scopes: RuleScope[] = offer.scopes.includes("agent") ? ["agent", "chat"] : ["chat"];
+ const [scope, setScope] = useState<RuleScope>(scopes[0]);
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);
+ const [reach, setReach] = useState<Reach>(offer.narrow[0]?.kind ?? "tool");
+ const sentence = editorSentence(offer, scope, breadth, reach, t);
+ const wideLabel = offer.chat === "all"
+ ? t("action_card.rule.reach_everything")
+ : offer.app ? fill(t("action_card.rule.breadth_app"), { app: offer.app }) : t("action_card.rule.reach_tool_plain");
+ const save = () => {
+ if (scope === "agent") onSave({ scope, breadth });
+ else onSave(reach === "tool" ? { scope, breadth: "action" } : { scope, breadth: "action", narrow: reach });
+ };
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}`) }))} />
+ options={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}
+ {scope === "chat" && offer.narrow.length ? <Segments label={t("action_card.rule.breadth_label")} value={reach} onChange={setReach}
+ options={[
+ ...offer.narrow.map((option) => ({ value: option.kind as Reach, label: t(`action_card.rule.reach_${option.kind}`) })),
+ { value: "tool" as Reach, label: wideLabel },
+ ]} /> : 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 className="mt-2.5 break-words 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" data-testid="action-card-rule-where">
+ {whereLine(offer, scope, reach, t)}
</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" })}>
+ onClick={save}>
{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 type="button" className="action-card-button" data-tone="tertiary" disabled={pending} onClick={onBack}
+ data-testid="action-card-rule-cancel">
+ {t("action_card.rule.cancel")}
</button>
</div>
</div>;
@@ -257,14 +296,14 @@ function SettledApproval({ block, approval, info }: { block: ToolBlock; approval
}
const savedText = saved
? saved.scope === "chat"
- ? fill(t("action_card.rule.saved_chat"), { app: saved.app || title })
+ ? fill(t("action_card.rule.saved_chat"), { app: saved.narrow && saved.target ? savedRuleSentence(saved, t) : 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,
+ detail: shownSummary(info, approval.summary) || 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")}
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
index c20172ec25..84d3fd11ed 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
@@ -4,6 +4,7 @@ import type { AgentChatEvent } from "@/lib/agentChatApi";
import { claimKeyboardTarget, TARGET_PRIORITY } from "./keyboardTarget";
import { maskedRequest, maskText } from "./redact";
import { parseApprovalCard, parseSavedRule } from "./approvalInfo";
+import { shortenHome } from "./approvalCopy";
let seq = 0;
const ev = (kind: string, payload: Record<string, unknown>): AgentChatEvent => ({ seq: ++seq, ts_ms: seq, kind, payload } as AgentChatEvent);
@@ -123,3 +124,28 @@ describe("the reducer and the card fields", () => {
expect(tl.pendingApprovals).toEqual([]);
});
});
+
+describe("short paths and narrow rules", () => {
+ it("shows the home folder as ~ and leaves other paths alone", () => {
+ const win = String.raw`Edit C:\Users\Ada\Desktop\a.py`;
+ expect(shortenHome(win)).toBe(String.raw`Edit ~\Desktop\a.py`);
+ expect(shortenHome("open c:/users/ada/notes.md")).toBe("open ~/notes.md");
+ expect(shortenHome("cat /home/bob/x.txt and /Users/eve")).toBe("cat ~/x.txt and ~");
+ expect(shortenHome(String.raw`C:\Users\Public\x`)).toBe(String.raw`C:\Users\Public\x`);
+ expect(shortenHome("/srv/home/bob")).toBe("/srv/home/bob");
+ expect(shortenHome("")).toBe("");
+ });
+
+ it("parses narrow options and a saved narrow rule, tolerating junk", () => {
+ const info = parseApprovalCard({
+ source: { kind: "files" }, brief: "Edit src/a.py",
+ rule: { scopes: [], chat: "runtime", narrow: [{ kind: "folder", label: "src" }, { kind: "disk", label: "x" }, "junk", { kind: "command" }] },
+ });
+ expect(info?.brief).toBe("Edit src/a.py");
+ expect(info?.rule?.narrow).toEqual([{ kind: "folder", label: "src" }]);
+ expect(parseApprovalCard({ source: { kind: "files" }, rule: { scopes: [] } })?.rule?.narrow).toEqual([]);
+ expect(parseSavedRule({ rule_kind: "always_allow", scope: "chat", narrow: "command", target: "npm test" }))
+ .toMatchObject({ narrow: "command", target: "npm test" });
+ expect(parseSavedRule({ rule_kind: "always_allow", scope: "chat", narrow: "planet" })?.narrow).toBeUndefined();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
index f3170837e9..1114b6b1b0 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
@@ -1,6 +1,6 @@
import { fill } from "@/i18n";
import type { ToolBlock } from "../reduce";
-import type { ApprovalCardInfo, ApprovalSourceKind, RuleBreadth, RuleKind, SavedApprovalRule } from "./approvalInfo";
+import type { ApprovalCardInfo, ApprovalSourceKind, RuleBreadth, RuleKind, RuleNarrow, SavedApprovalRule } from "./approvalInfo";
import { maskText, maskedRequest } from "./redact";
type T = (key: string) => string;
@@ -20,7 +20,7 @@ function humanize(raw: string): string {
*/
export function cardInfoOf(block: ToolBlock): ApprovalCardInfo {
const known = block.approval?.card;
- if (known) return { ...known, detail: maskText(known.detail) };
+ if (known) return { ...known, where: shortenHome(known.where), 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";
@@ -35,7 +35,7 @@ export function cardInfoOf(block: ToolBlock): ApprovalCardInfo {
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 where = (kind === "terminal" || kind === "files") && typeof input.cwd === "string" ? shortenHome(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 : "" },
@@ -43,8 +43,9 @@ export function cardInfoOf(block: ToolBlock): ApprovalCardInfo {
why,
caution: null,
detail: kind === "plan" ? "" : maskedRequest(block.input),
+ brief: "",
// 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: "" },
+ rule: kind === "plan" ? null : { scopes: [], chat: "", app: "", verb: "", pattern: "", broad: "", narrow: [] },
};
}
@@ -90,9 +91,37 @@ export function ruleSentence(kind: RuleKind, app: string, verb: string, t: T): s
}
export function savedRuleSentence(rule: SavedApprovalRule, t: T): string {
+ if (rule.narrow && rule.target) return narrowSentence(rule.narrow, rule.target, t);
return ruleSentence(rule.kind, rule.app, rule.verb, t);
}
+/** A narrow chat rule as the person reads it: "Always allow changes to files in src". */
+export function narrowSentence(narrow: RuleNarrow, target: string, t: T): string {
+ return narrow === "folder"
+ ? fill(t("action_card.rule.always_folder"), { folder: target })
+ : fill(t("action_card.rule.always_command"), { command: target });
+}
+
+/** A user-profile folder, Windows or POSIX; system profiles are left alone. */
+const WIN_HOME = /\b[A-Za-z]:[\\/]Users[\\/](?!(?:Public|Default|All Users)(?:[\\/]|$))[^\\/\s"'`]+(?=[\\/]|$|[\s"'`),;])/gi;
+const POSIX_HOME = /(^|[\s"'`(=:])\/(?:Users|home)\/(?!Shared(?:\/|$))[^/\s"'`]+(?=\/|$|[\s"'`),;])/g;
+
+/**
+ * `text` with the person's home folder shown as `~`: the card's visible
+ * lines never spell out the profile folder (the backend also makes paths
+ * relative to the workspace; this covers events written before it did). The
+ * full path stays in the details disclosure.
+ */
+export function shortenHome(text: string): string {
+ if (!text) return text;
+ return text.replace(WIN_HOME, "~").replace(POSIX_HOME, "$1~");
+}
+
+/** The summary a card shows: the backend's short-path brief, else the summary with `~`. */
+export function shownSummary(info: ApprovalCardInfo, summary: string): string {
+ return (info.brief || shortenHome(summary)).trim();
+}
+
/** 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
index 6bf879dc9e..5135a8f27e 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
@@ -13,6 +13,15 @@ export type RuleScope = "agent" | "chat";
export type RuleBreadth = "action" | "app";
export type RuleKind = "always_allow" | "require_approval";
+/** A narrower chat rule the call allows: only this folder, only this command. */
+export type RuleNarrow = "folder" | "command";
+
+export interface NarrowOption {
+ kind: RuleNarrow;
+ /** How the card shows it: a path relative to the workspace, or with `~`. */
+ label: string;
+}
+
/** What "Always allow" saves on this card. */
export interface ApprovalRuleOffer {
scopes: RuleScope[];
@@ -22,6 +31,8 @@ export interface ApprovalRuleOffer {
verb: string;
pattern: string;
broad: string;
+ /** Narrower chat rules this call allows; empty when the payload has none. */
+ narrow: NarrowOption[];
}
export interface ApprovalCardInfo {
@@ -32,6 +43,8 @@ export interface ApprovalCardInfo {
caution: ApprovalCaution | null;
/** The exact command or request, secrets masked by the backend. */
detail: string;
+ /** The summary with short paths (workspace-relative, `~` for home); "" on older events. */
+ brief: string;
/** `null`: the card offers no "Always allow" (a plan). */
rule: ApprovalRuleOffer | null;
}
@@ -45,11 +58,15 @@ export interface SavedApprovalRule {
verb: string;
/** A broader "ask first" rule keeps asking anyway. */
stillAsks: boolean;
+ /** A narrow chat rule: what it covers, as the card showed it. */
+ narrow?: RuleNarrow;
+ target?: string;
}
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 NARROWS = new Set<RuleNarrow>(["folder", "command"]);
const text = (v: unknown): string => (typeof v === "string" ? v : "");
const record = (v: unknown): Record<string, unknown> | null =>
@@ -66,6 +83,7 @@ export function parseApprovalCard(payload: Record<string, unknown>): ApprovalCar
why: text(payload.why),
caution: CAUTIONS.has(caution) ? caution : null,
detail: text(payload.detail),
+ brief: text(payload.brief),
rule: parseRuleOffer(payload.rule),
};
}
@@ -82,6 +100,14 @@ function parseRuleOffer(raw: unknown): ApprovalRuleOffer | null {
verb: text(rule.verb),
pattern: text(rule.pattern),
broad: text(rule.broad),
+ narrow: Array.isArray(rule.narrow)
+ ? rule.narrow.flatMap((raw) => {
+ const entry = record(raw);
+ const kind = text(entry?.kind) as RuleNarrow;
+ const label = text(entry?.label);
+ return NARROWS.has(kind) && label ? [{ kind, label }] : [];
+ })
+ : [],
};
}
@@ -96,5 +122,8 @@ export function parseSavedRule(payload: Record<string, unknown>): SavedApprovalR
app: text(payload.app),
verb: text(payload.verb),
stillAsks: payload.still_asks === true,
+ ...(NARROWS.has(text(payload.narrow) as RuleNarrow)
+ ? { narrow: text(payload.narrow) as RuleNarrow, target: text(payload.target) }
+ : {}),
};
}
diff --git a/dodaios/ui/web/frontend/src/components/society/create/AccessChoice.tsx b/dodaios/ui/web/frontend/src/components/society/create/AccessChoice.tsx
index 7415612e3a..a2604621cb 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/AccessChoice.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/AccessChoice.tsx
@@ -6,16 +6,19 @@
* message would fail.
*/
import { useId, useRef, type KeyboardEvent } from "react";
+import { TriangleAlert } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { blockedReasonKey, type AccessOption } from "./seatChoice";
-export function AccessChoice({ options, value, hint, disabled, onChange }: {
+export function AccessChoice({ options, value, hint, warn = false, disabled, onChange }: {
options: AccessOption[];
/** The picked kind; "" when no access can be picked. */
value: string;
/** The sentence under the group that explains the picked access. */
hint: string;
+ /** The picked access bills every use: the hint reads as a warning. */
+ warn?: boolean;
disabled: boolean;
onChange: (kind: string) => void;
}) {
@@ -73,7 +76,13 @@ export function AccessChoice({ options, value, hint, disabled, onChange }: {
);
})}
</div>
- {hint ? <p id={`${id}-hint`} className="text-xs text-muted-foreground">{hint}</p> : null}
+ {hint ? (
+ <p id={`${id}-hint`} className={cn("flex items-start gap-1.5 text-xs", warn ? "text-warning" : "text-muted-foreground")}
+ data-testid={warn ? "create-agent-access-cost" : undefined}>
+ {warn ? <TriangleAlert className="mt-px size-3.5 shrink-0" aria-hidden /> : null}
+ <span>{hint}</span>
+ </p>
+ ) : null}
{options.filter((entry) => entry.blocked).map((entry) => (
<p key={entry.kind} id={`${id}-blocked-${entry.kind}`} role="note" className="text-xs text-warning"
data-testid={`create-agent-access-blocked-${entry.kind}`}>
diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx
index c37fee7f82..7890e9735d 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx
@@ -382,3 +382,40 @@ describe("CreateAgentDialog: blank", () => {
expect(installCalls()).toHaveLength(0);
});
});
+
+describe("CreateAgentDialog: starter name and cost", () => {
+ test("names the agent in a labelled, optional field that falls back to the starter's name", async () => {
+ mount();
+ let pending!: Promise<{ agentId: string; name: string }>;
+ act(() => { pending = useCreateAgentDialog.getState().request({ mode: "starter" }) as Promise<{ agentId: string; name: string }>; });
+ fireEvent.click(await screen.findByTestId("starter-daily-briefing"));
+ const field = await screen.findByLabelText("agent_create.preview.name_label") as HTMLInputElement;
+ await waitFor(() => expect(field.value).toBe("Daily Briefing"));
+ expect(field.placeholder).toBe("Daily Briefing");
+ expect(screen.getByText("agent_create.quick.optional")).toBeTruthy();
+ fireEvent.change(field, { target: { value: " " } });
+ expect(screen.getByTestId("template-preview-title").textContent).toBe("Daily Briefing");
+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByTestId("create-agent-submit"));
+ await expect(pending).resolves.toMatchObject({ name: "Daily Briefing" });
+ expect(installCalls()[0]).toMatchObject({ starter_id: "daily-briefing", name: "Daily Briefing" });
+ });
+
+ test("a per-use seat is said in the Runs on line, without opening it", async () => {
+ mount();
+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });
+ await screen.findByTestId("create-agent-seat-summary");
+ const warning = await screen.findByTestId("create-agent-seat-cost");
+ expect(warning.textContent).toBe("society.create_agent.access_hint_api");
+ });
+
+ test("a plan or a local model starts first, and then nothing warns", async () => {
+ menu.options = [provider({}), provider({ id: "ollama", label: "Ollama", family: "ollama", keyless: true, curated_models: [] })];
+ menu.live = { ollama: [{ id: "qwen3:8b", label: "qwen3:8b" }] };
+ mount();
+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });
+ const summary = await screen.findByTestId("create-agent-seat-summary");
+ await waitFor(() => expect(summary.textContent).toContain("Ollama"));
+ expect(screen.queryByTestId("create-agent-seat-cost")).toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
index 795903975d..f5330680bc 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
@@ -105,7 +105,8 @@ describe("CreateAgentDialog", () => {
fireEvent.click(screen.getByTestId("create-agent-submit"));
await expect(pending).resolves.toBe(agent);
const choice = createAgent.mock.calls[0][0];
- expect(choice).toMatchObject({ name: "Scout", runtime: "hermes", provider: "openai", model: "gpt-5.5", accountId: "" });
+ // A local model beats a per-use API key as the first pick.
+ expect(choice).toMatchObject({ name: "Scout", runtime: "hermes", provider: "ollama", model: "qwen3:8b", accountId: "" });
expect(choice.companion.shape).toBeTruthy();
expect(useCreateAgentDialog.getState().open).toBe(false);
});
@@ -116,10 +117,11 @@ describe("CreateAgentDialog", () => {
act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
await screen.findByTestId("create-agent-provider");
expect(screen.getByTestId("create-agent-model")).toBeTruthy();
- expect(screen.getByRole("radio", { name: "society.create.kind_api" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.getByRole("radio", { name: "society.create.kind_local" }).getAttribute("aria-checked")).toBe("true");
+ expect(screen.queryByTestId("create-agent-access-cost")).toBeNull();
fireEvent.click(screen.getByTestId("create-agent-submit"));
await waitFor(() => expect(createAgent).toHaveBeenCalled());
- expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "jarvis", provider: "openai", model: "gpt-5.5" });
+ expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "jarvis", provider: "ollama", model: "qwen3:8b" });
});
test("Claude can run on the subscription or on the API key", async () => {
@@ -232,7 +234,49 @@ describe("CreateAgentDialog", () => {
await waitFor(() => expect(submit.disabled).toBe(false));
fireEvent.click(submit);
await waitFor(() => expect(createAgent).toHaveBeenCalled());
- expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "openclaw", provider: "openai" });
+ expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "openclaw", provider: "ollama" });
+ });
+
+ test("a Hermes agent starts on the ChatGPT plan, not on Claude's extra usage", async () => {
+ const CODEX = provider({
+ id: "openai-codex", label: "OpenAI Codex", family: "openai", runner: "codex-cli", cli_installed: true,
+ curated_models: [{ id: "gpt-5.5", label: "GPT-5.5" }],
+ });
+ runtimes.value = {
+ ...READY,
+ supported_providers: ["claude-api", "openai-codex"],
+ subscription_providers: ["openai-codex"],
+ login_providers: ["claude-api"],
+ access: { "claude-api": ["subscription", "api"] },
+ };
+ menu.options = [CLAUDE, CODEX];
+ menu.live = {};
+ createAgent.mockResolvedValue({ agentId: "agent-5" });
+ mount();
+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
+ fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.hermes" }));
+ await screen.findByTestId("create-agent-provider");
+ await waitFor(() => expect(screen.getByRole("radio", { name: "society.create.kind_subscription" }).getAttribute("aria-checked")).toBe("true"));
+ expect(screen.queryByTestId("create-agent-access-cost")).toBeNull();
+ fireEvent.click(screen.getByTestId("create-agent-submit"));
+ await waitFor(() => expect(createAgent).toHaveBeenCalled());
+ expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "hermes", provider: "openai-codex" });
+ });
+
+ test("a per-use seat is only the fallback, and says so in plain sight", async () => {
+ runtimes.value = {
+ ...READY,
+ supported_providers: ["claude-api"],
+ login_providers: ["claude-api"],
+ access: { "claude-api": ["subscription"] },
+ };
+ menu.options = [CLAUDE];
+ menu.live = {};
+ mount();
+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
+ fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.hermes" }));
+ const warning = await screen.findByTestId("create-agent-access-cost");
+ expect(warning.textContent).toBe("society.create_agent.access_extra_usage");
});
test("closing the dialog cancels the request quietly", async () => {
diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
index 4bdc439926..2633c5cc60 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
@@ -184,7 +184,8 @@ function CreateAgentDialog() {
if (mode === "starter" && starter && copy) {
const result = await installStarter({
starterId: starter.id,
- name: starterName,
+ // The name is optional: an emptied field keeps the starter's own.
+ name: starterName.trim() || copy.name,
tools: [...picked],
withRoutine: Boolean(starter.routine && routineOn),
seat: starterSeat(seat.pick, companion),
@@ -195,7 +196,7 @@ function CreateAgentDialog() {
if (mode === "import" && imported.template) {
const result = await installStarter({
template: imported.template,
- name: importName,
+ name: importName.trim() || imported.preview?.template?.name || "",
tools: [...importPicked],
seat: starterSeat(seat.pick, companion),
});
@@ -346,6 +347,7 @@ function CreateAgentDialog() {
<TemplatePreviewCard
icon={<StarterIcon name={starter.icon} />}
name={starterName}
+ defaultName={copy.name}
onNameChange={setStarterName}
outcome={copy.outcome}
summary={starter.summary}
@@ -375,6 +377,7 @@ function CreateAgentDialog() {
<TemplatePreviewCard
icon={<FileInput />}
name={importName}
+ defaultName={imported.preview.template.name}
onNameChange={setImportName}
outcome={imported.preview.template.title || t("agent_create.import.no_title")}
summary={imported.preview.summary}
diff --git a/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
index b7a9586e5e..c489cc2a16 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
@@ -7,7 +7,7 @@
* on any runtime and any provider exactly like a blank agent.
*/
import { useEffect, useMemo, useState } from "react";
-import { ChevronDown, Loader2, RefreshCw } from "lucide-react";
+import { ChevronDown, Loader2, RefreshCw, TriangleAlert } from "lucide-react";
import { BrandedSelect } from "@/components/ui/select";
import { AgentMark } from "@/components/agentic/AgentMark";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
@@ -21,7 +21,7 @@ import { modelSeats, runtimeSeats } from "../chat/modelChoices";
import { useModelMenuData } from "../chat/useModelMenuData";
import { accountChoice, accountHint } from "./brainPicker";
import { AccessChoice } from "./AccessChoice";
-import { accessModels, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption } from "./seatChoice";
+import { accessModels, billedPerUse, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption } from "./seatChoice";
/** A model list this long gets a search field. */
const SEARCH_FROM = 12;
@@ -119,6 +119,11 @@ export function useCreateSeat() {
export type CreateSeat = ReturnType<typeof useCreateSeat>;
+/** The sentence that explains how the picked access pays. */
+function accessHint(t: (key: string) => string, option: AccessOption): string {
+ return t(option.extraUsage ? "society.create_agent.access_extra_usage" : `society.create_agent.access_hint_${option.kind}`);
+}
+
/** The full choice: runtime cards, provider, access, login and model. */
export function SeatFields({ seat, disabled }: { seat: CreateSeat; disabled: boolean }) {
const t = useT();
@@ -164,7 +169,8 @@ export function SeatFields({ seat, disabled }: { seat: CreateSeat; disabled: boo
<AccessChoice
options={chosen.options}
value={option?.kind ?? ""}
- hint={option ? t(option.extraUsage ? "society.create_agent.access_extra_usage" : `society.create_agent.access_hint_${option.kind}`) : ""}
+ hint={option ? accessHint(t, option) : ""}
+ warn={billedPerUse(option)}
disabled={disabled}
onChange={seat.setAccess}
/>
@@ -261,6 +267,13 @@ export function SeatSummary({ seat, disabled }: { seat: CreateSeat; disabled: bo
<ChevronDown className={cn("size-3.5 transition-transform duration-200 motion-reduce:transition-none", open && "rotate-180")} aria-hidden />
</span>
</button>
+ {billedPerUse(option) && option ? (
+ // Billed per use: said in plain sight, not only behind "Change".
+ <p className="flex items-start gap-1.5 border-t border-border px-3 py-2 text-xs text-warning" data-testid="create-agent-seat-cost">
+ <TriangleAlert className="mt-px size-3.5 shrink-0" aria-hidden />
+ <span>{accessHint(t, option)}</span>
+ </p>
+ ) : null}
{open || blocked ? (
<div className="border-t border-border px-3 py-4">
<SeatFields seat={seat} disabled={disabled} />
diff --git a/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx b/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx
index f8c5e9bf74..2e7852a7de 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx
@@ -23,6 +23,9 @@ export interface PreviewRoutine {
interface Props {
icon: ReactNode;
name: string;
+ /** The starter's or template's own name: the field starts with it, and an
+ * emptied field falls back to it. */
+ defaultName?: string;
onNameChange: (name: string) => void;
outcome: string;
summary: TemplateSummary;
@@ -75,21 +78,30 @@ export function TemplatePreviewCard(props: Props) {
{props.icon}
</span>
<div className="flex min-w-0 flex-1 flex-col gap-1">
- <label htmlFor={nameId} className="sr-only">{t("agent_create.preview.name_label")}</label>
- <Input
- id={nameId}
- value={props.name}
- maxLength={40}
- onChange={(event) => props.onNameChange(event.target.value)}
- disabled={props.disabled}
- data-testid="template-preview-name"
- className="h-9 border-transparent bg-transparent px-2 -mx-2 text-lg font-semibold text-foreground-strong hover:border-border focus-visible:border-accent"
- />
+ <h2 className="truncate text-lg font-semibold text-foreground-strong" data-testid="template-preview-title">
+ {props.name.trim() || props.defaultName || t("agent_create.preview.name_label")}
+ </h2>
<p className="text-sm text-foreground-secondary">{props.outcome}</p>
{props.note}
</div>
</header>
+ <div className="flex flex-col gap-1.5 text-sm">
+ <span className="flex items-baseline justify-between gap-2">
+ <label htmlFor={nameId} className="font-medium">{t("agent_create.preview.name_label")}</label>
+ <span className="text-xs text-foreground-faint">{t("agent_create.quick.optional")}</span>
+ </span>
+ <Input
+ id={nameId}
+ value={props.name}
+ maxLength={40}
+ onChange={(event) => props.onNameChange(event.target.value)}
+ placeholder={props.defaultName}
+ disabled={props.disabled}
+ data-testid="template-preview-name"
+ />
+ </div>
+
<section aria-label={t("agent_create.preview.brings")} className="flex flex-col gap-2">
<h3 className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("agent_create.preview.brings")}</h3>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
diff --git a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
index 6e3027a160..ef86e66fbc 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
+++ b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
@@ -8,7 +8,9 @@ import type { BrainSeat } from "./brainPicker";
import {
accessModels,
API_KEY_ACCOUNT,
+ billedPerUse,
blockedReasonKey,
+ costRank,
defaultModel,
pickableOption,
providerChoices,
@@ -113,8 +115,35 @@ describe("providerChoices", () => {
expect(choice.options.map((o) => [o.kind, o.accountId])).toEqual([["subscription", ""]]);
});
- it("lists providers with a subscription before key-only and local ones", () => {
- expect(providerChoices([ollama, openai, claude]).map((c) => c.id)).toEqual(["claude", "openai", "ollama"]);
+ it("lists a plan first, then a local model, then anything billed per use", () => {
+ expect(providerChoices([ollama, openai, claude]).map((c) => c.id)).toEqual(["claude", "ollama", "openai"]);
+ });
+
+ it("never starts a Hermes / OpenClaw agent on Claude's extra usage while a plan is connected", () => {
+ // Codex on ChatGPT reaches Hermes through the subscription gateway.
+ const seats = runtimeSeats([claude, codex, openai], ["claude-api", "openai-codex", "openai"], ["openai-codex"], ["claude-api"]);
+ const choices = providerChoices(seats, { "claude-api": ["api", "subscription"] }, true);
+ expect(choices[0].id).toBe("openai");
+ const picked = pickableOption(choices[0]);
+ expect([picked?.kind, picked?.seat.provider.id, billedPerUse(picked)]).toEqual(["subscription", "openai-codex", false]);
+ const claudeChoice = choices.find((c) => c.id === "claude")!;
+ expect(billedPerUse(pickableOption(claudeChoice))).toBe(true);
+ });
+
+ it("prefers a local model over a per-use one, and says when only per-use is left", () => {
+ const seats = runtimeSeats([claude, ollama], ["claude-api", "ollama"], [], ["claude-api"]);
+ const choices = providerChoices(seats, { "claude-api": ["subscription"] }, true);
+ expect(choices.map((c) => c.id)).toEqual(["ollama", "claude"]);
+ expect(costRank(pickableOption(choices[0])!)).toBe(1);
+ const only = providerChoices(runtimeSeats([claude], ["claude-api"], [], ["claude-api"]), { "claude-api": ["subscription"] }, true);
+ expect(billedPerUse(pickableOption(only[0]))).toBe(true);
+ });
+
+ it("picks a provider's cheapest open access unless one is asked for", () => {
+ const [choice] = providerChoices([codex, openai]);
+ expect(pickableOption(choice)?.kind).toBe("subscription");
+ expect(pickableOption(choice, "api")?.kind).toBe("api");
+ expect(billedPerUse(null)).toBe(false);
});
it("shows a refused Claude login with its reason but never picks it", () => {
diff --git a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.ts b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.ts
index cf81fe8756..d2f3dade75 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.ts
+++ b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.ts
@@ -118,16 +118,37 @@ export function blockedReasonKey(code: string): string {
: "society.create_agent.access_blocked";
}
-/** The access to use: ``kind`` when it can be picked, else the first that can. */
+/**
+ * What an access costs on top of what is already paid for: 0 a plan (a
+ * subscription billed to the plan), 1 a model on this machine, 2 billed per
+ * use (an API key, or Claude's login on Hermes / OpenClaw, which Anthropic
+ * charges as extra usage). A fresh agent never starts on a 2 while a 0 or a 1
+ * is connected.
+ */
+export function costRank(option: AccessOption): number {
+ if (option.kind === "subscription" && !option.extraUsage) return 0;
+ if (option.kind === "local") return 1;
+ return 2;
+}
+
+/** True when this access bills every use: the dialog then says so in plain sight. */
+export function billedPerUse(option: AccessOption | null): boolean {
+ return Boolean(option && costRank(option) === 2);
+}
+
+/** The access to use: ``kind`` when it can be picked, else the cheapest that can. */
export function pickableOption(choice: ProviderChoice | null, kind = ""): AccessOption | null {
const open = choice?.options.filter((option) => !option.blocked) ?? [];
- return open.find((option) => option.kind === kind) ?? open[0] ?? null;
+ const asked = open.find((option) => option.kind === kind);
+ if (asked) return asked;
+ return open.reduce<AccessOption | null>((best, option) => (!best || costRank(option) < costRank(best) ? option : best), null);
}
/**
- * The providers to offer, best access first: a provider with a subscription
- * comes before one with only an API key (a plan already paid for beats a
- * metered key — the maintainer's stated preference), then by name.
+ * The providers to offer, cheapest access first: a provider with a plan
+ * already paid for comes before a local model, and both before anything
+ * billed per use (an API key, a subscription charged as extra usage), then by
+ * name. The first entry is what a fresh agent starts on.
*/
export function providerChoices(
seats: BrainSeat[],
@@ -159,7 +180,7 @@ export function providerChoices(
}
// A provider whose every access is refused right now sorts last.
const best = (choice: ProviderChoice) => Math.min(
- ...choice.options.map((option) => (option.blocked ? 10 : 0) + KIND_ORDER[option.kind]));
+ ...choice.options.map((option) => (option.blocked ? 10 : 0) + costRank(option)));
return [...byBrand.values()]
.filter((choice) => choice.options.length > 0)
.map((choice) => ({ ...choice, options: [...choice.options].sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind]) }))
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index d9298fffb0..59525ebb4d 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -10783,7 +10783,15 @@
"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."
+ "save_failed": "Die Regel ließ sich nicht speichern.",
+ "always_folder": "Änderungen an Dateien in {folder} immer erlauben",
+ "always_command": "Den Befehl {command} immer erlauben",
+ "always_everything": "In diesem Chat alles immer erlauben",
+ "reach_folder": "Nur dieser Ordner",
+ "reach_command": "Nur dieser Befehl",
+ "reach_everything": "Alles in diesem Chat",
+ "reach_tool_plain": "Das ganze Werkzeug",
+ "cancel": "Abbrechen"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index a0262b0ea3..d80182ef6b 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -10783,7 +10783,15 @@
"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."
+ "save_failed": "Could not save the rule.",
+ "always_folder": "Always allow changes to files in {folder}",
+ "always_command": "Always allow the command {command}",
+ "always_everything": "Always allow everything in this chat",
+ "reach_folder": "Only this folder",
+ "reach_command": "Only this command",
+ "reach_everything": "Everything in this chat",
+ "reach_tool_plain": "This whole tool",
+ "cancel": "Cancel"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index b0473b2c0d..c775e4d32b 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -10783,7 +10783,15 @@
"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."
+ "save_failed": "No se pudo guardar la regla.",
+ "always_folder": "Permitir siempre cambios en archivos de {folder}",
+ "always_command": "Permitir siempre el comando {command}",
+ "always_everything": "Permitir siempre todo en este chat",
+ "reach_folder": "Solo esta carpeta",
+ "reach_command": "Solo este comando",
+ "reach_everything": "Todo en este chat",
+ "reach_tool_plain": "Toda la herramienta",
+ "cancel": "Cancelar"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index 4dd0dafccd..95d3e20aec 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -10783,7 +10783,15 @@
"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."
+ "save_failed": "Não foi possível salvar a regra.",
+ "always_folder": "Permitir sempre alterações a ficheiros em {folder}",
+ "always_command": "Permitir sempre o comando {command}",
+ "always_everything": "Permitir sempre tudo neste chat",
+ "reach_folder": "Só esta pasta",
+ "reach_command": "Só este comando",
+ "reach_everything": "Tudo neste chat",
+ "reach_tool_plain": "A ferramenta toda",
+ "cancel": "Cancelar"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 477907e855..11060b8888 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -10783,7 +10783,15 @@
"saved_chat": "已在此对话中允许:{app}",
"saved_short": "规则已保存",
"still_asks": "仍有更严格的规则会先询问。",
- "save_failed": "无法保存规则。"
+ "save_failed": "无法保存规则。",
+ "always_folder": "始终允许修改 {folder} 中的文件",
+ "always_command": "始终允许命令 {command}",
+ "always_everything": "在此聊天中始终允许一切",
+ "reach_folder": "仅此文件夹",
+ "reach_command": "仅此命令",
+ "reach_everything": "此聊天中的一切",
+ "reach_tool_plain": "整个工具",
+ "cancel": "取消"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
index 5b1e3cad29..8a83f581d0 100644
--- a/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/dodaios/ui/web/frontend/src/lib/agentChatApi.ts
@@ -599,6 +599,8 @@ export type ApprovalDecision = "allow" | "allow_always" | "deny";
export interface ApprovalRuleChoice {
scope: "agent" | "chat";
breadth?: "action" | "app";
+ /** A narrower chat rule: only this folder, only this exact command. */
+ narrow?: "folder" | "command";
}
function approvalUrl(sessionId: string, approvalId: string): string {
@@ -617,7 +619,7 @@ export async function resolveAgentChatApproval(
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
rule && decision === "allow_always"
- ? { decision, scope: rule.scope, breadth: rule.breadth ?? "action" }
+ ? { decision, scope: rule.scope, breadth: rule.breadth ?? "action", ...(rule.narrow ? { narrow: rule.narrow } : {}) }
: { decision },
),
}),
diff --git a/tests/unit/agent_chat/test_approval_card.py b/tests/unit/agent_chat/test_approval_card.py
index 3b3d3a4d93..708d6cbdb5 100644
--- a/tests/unit/agent_chat/test_approval_card.py
+++ b/tests/unit/agent_chat/test_approval_card.py
@@ -291,7 +291,10 @@ def test_acp_request_permission_asks_on_the_same_card(tmp_path: Path):
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"}
+ offer = payload["rule"]
+ assert (offer["scopes"], offer["chat"]) == ([], "runtime")
+ # ...and the card may still narrow it to this one command for this chat.
+ assert payload["rule"]["narrow"][0]["kind"] == "command"
svc.resolve_approval(session.session_id, payload["approval_id"], "allow_always")
assert await asyncio.wait_for(answering, 2) == {"outcome": "selected", "optionId": "o2"}
@@ -667,3 +670,244 @@ def test_the_rule_route(tmp_path: Path):
json={"decision": "allow_always", "scope": "agent", "breadth": "planet"},
)
assert bad_breadth.status_code == 400
+
+
+# ------------------------------------------------------------ narrow rules, short paths
+
+WIN_HOME = "C:\\Users\\Ada"
+WIN_CWD = "C:\\Users\\Ada\\Desktop\\proj"
+
+
+def test_display_paths_shortens_the_workspace_and_the_home_folder():
+ from dodaios.agent_chat.approval_card import display_paths
+
+ text = f"Edit {WIN_CWD}\\src\\a.py and C:/Users/ada/Downloads/x.txt"
+ assert display_paths(text, WIN_CWD, WIN_HOME) == "Edit src\\a.py and ~/Downloads/x.txt"
+ # The workspace itself reads from the home folder; no path, no change.
+ assert display_paths(WIN_CWD, WIN_CWD, WIN_HOME) == "~\\Desktop\\proj"
+ assert display_paths("echo hi", WIN_CWD, WIN_HOME) == "echo hi"
+ assert display_paths("/home/bob/code/x.py", "/home/bob/code", "/home/bob") == "x.py"
+ assert display_paths("cat /home/bob/notes.md", "", "/home/bob") == "cat ~/notes.md"
+ # A folder that only starts like the home folder is left alone.
+ assert display_paths("C:\\Users\\Adam\\x", "", WIN_HOME) == "C:\\Users\\Adam\\x"
+
+
+def test_narrow_options_and_matches():
+ from dodaios.agent_chat.approval_card import narrow_matches, narrow_options
+
+ folder = narrow_options("files", {"file_path": f"{WIN_CWD}\\src\\a.py"}, WIN_CWD)
+ assert folder == [{"kind": "folder", "value": f"{WIN_CWD}\\src", "label": "src"}] or (
+ # POSIX normpath keeps backslashes as part of the name; the label still shortens.
+ folder and folder[0]["kind"] == "folder"
+ )
+ command = narrow_options("terminal", {"command": "npm test"}, WIN_CWD)
+ assert command == [{"kind": "command", "value": "npm test", "label": "npm test"}]
+ assert narrow_options("connector", {"action": "send"}, WIN_CWD) == []
+ assert narrow_options("terminal", {"command": "x" * 500}, WIN_CWD) == []
+
+ rule = {"tool": "Bash", "kind": "command", "value": "npm test"}
+ assert narrow_matches(rule, "Bash", {"command": "npm test"})
+ assert not narrow_matches(rule, "Bash", {"command": "npm test && rm -rf /"})
+ assert not narrow_matches(rule, "RunCommand", {"command": "npm test"})
+
+
+def test_a_folder_rule_covers_only_that_folder(tmp_path: Path):
+ from dodaios.agent_chat.approval_card import narrow_matches
+
+ root = tmp_path / "src"
+ rule = {"tool": "Edit", "kind": "folder", "value": str(root)}
+ assert narrow_matches(rule, "Edit", {"file_path": str(root / "a" / "b.py")})
+ assert narrow_matches(rule, "Edit", {"file_path": "src/c.py"}, str(tmp_path))
+ assert not narrow_matches(rule, "Edit", {"file_path": str(tmp_path / "other.py")})
+ assert not narrow_matches(rule, "Edit", {"file_path": str(root / ".." / "escape.py")})
+ assert not narrow_matches(rule, "Write", {"file_path": str(root / "a.py")})
+ assert not narrow_matches(rule, "Edit", {})
+
+
+def test_the_card_shows_short_paths_and_offers_narrow_rules(tmp_path: Path):
+ target = tmp_path / "src" / "app.py"
+ fields = describe_call(
+ "Edit",
+ {"file_path": str(target), "old_string": "a", "new_string": "b"},
+ f"Edit {target}",
+ cwd=str(tmp_path),
+ rule={"scopes": ["chat"], "chat": "tool", "app": "Edit"},
+ )
+ assert str(tmp_path) not in fields["brief"]
+ assert fields["brief"].replace("\\", "/") == "Edit src/app.py"
+ # The full path stays in the disclosure.
+ assert str(target).replace("\\", "\\\\") in fields["detail"] or str(target) in fields["detail"]
+ narrow = fields["rule"]["narrow"]
+ assert narrow[0]["kind"] == "folder" and narrow[0]["value"] == str(target.parent)
+ assert narrow[0]["label"] == "src"
+ # A plan offers nothing; a connector offers no narrow rule.
+ assert describe_call("ExitPlanMode", {"plan": "x"}, rule={"scopes": []})["rule"] is None
+ gmail = describe_call("gmail", {"action": "send"}, rule={"scopes": ["chat"]})
+ assert "narrow" not in gmail["rule"]
+
+
+def test_a_narrow_command_rule_allows_only_that_command(tmp_path: Path):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path)
+ sid = session.session_id
+ q = svc.subscribe(sid)
+ asking = asyncio.create_task(
+ svc._ask(sid, "t1", "c1", "Bash", {"command": "npm test"}, "npm test") # noqa: SLF001
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ assert payload["rule"]["narrow"] == [
+ {"kind": "command", "value": "npm test", "label": "npm test"}
+ ]
+ assert svc.resolve_approval(
+ sid, payload["approval_id"], "allow_always", scope="chat", narrow="command"
+ )
+ # The runtime hears a plain yes: it must not widen the rule to the tool.
+ assert await asyncio.wait_for(asking, 2) == "allow"
+ resolved = (await _next(q, "approval_resolved"))["payload"]
+ assert resolved["decision"] == "allow_always" and resolved["scope"] == "chat"
+ notice = (await _next(q, "notice"))["payload"]
+ assert notice["narrow"] == "command" and notice["target"] == "npm test"
+ assert "Bash" not in svc.always_allowed(sid)
+ assert svc.store.get_session(sid).permission_mode == "ask" # type: ignore[union-attr]
+ # The same command runs without a card; another one still asks.
+ assert await svc._ask(sid, "t1", "c2", "Bash", {"command": "npm test"}, "") == "allow" # noqa: SLF001
+ other = asyncio.create_task(
+ svc._ask(sid, "t1", "c3", "Bash", {"command": "rm -rf dist"}, "") # noqa: SLF001
+ )
+ again = (await _next(q, "approval_required"))["payload"]
+ assert again["input"] == {"command": "rm -rf dist"}
+ svc.resolve_approval(sid, again["approval_id"], "deny")
+ assert await asyncio.wait_for(other, 2) == "deny"
+
+ asyncio.run(scenario())
+
+
+def test_a_narrow_folder_rule_allows_only_that_folder(tmp_path: Path):
+ async def scenario() -> None:
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ sid = session.session_id
+ q = svc.subscribe(sid)
+ inside = str(tmp_path / "docs" / "a.md")
+ asking = asyncio.create_task(
+ svc._ask(sid, "t1", "c1", "Edit", {"file_path": inside}, "") # noqa: SLF001
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(
+ sid, payload["approval_id"], "allow_always", scope="chat", narrow="folder"
+ )
+ assert await asyncio.wait_for(asking, 2) == "allow"
+ later = str(tmp_path / "docs" / "deep" / "b.md")
+ assert await svc._ask(sid, "t1", "c2", "Edit", {"file_path": later}, "") == "allow" # noqa: SLF001
+ outside = asyncio.create_task(
+ svc._ask(sid, "t1", "c3", "Edit", {"file_path": str(tmp_path / "x.md")}, "") # noqa: SLF001
+ )
+ again = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(sid, again["approval_id"], "deny")
+ assert await asyncio.wait_for(outside, 2) == "deny"
+
+ asyncio.run(scenario())
+
+
+def test_narrow_is_validated(tmp_path: Path):
+ svc, session = _service(tmp_path)
+ with pytest.raises(ValueError):
+ svc.resolve_approval(session.session_id, "a1", "allow_always", scope="chat", narrow="disk")
+ with pytest.raises(ValueError):
+ svc.resolve_approval(
+ session.session_id, "a1", "allow_always", scope="agent", narrow="folder"
+ )
+
+
+def test_an_always_without_a_choice_never_writes_a_rule_for_a_runtime_tool(
+ tmp_path: Path, society_runtime
+):
+ """An older client's bare "Always allow" on Claude's own Edit: no
+ ``plugin:edit`` on the agent, no chat-wide auto, only that tool in this chat."""
+
+ async def scenario() -> None:
+ from dodaios.society.surface import remember_always_allow
+
+ svc, session = _service(tmp_path, surface="society", session_id="society:ada")
+ sid = session.session_id
+ q = svc.subscribe(sid)
+ assert await remember_always_allow(session, "Edit", {"file_path": "a.py"}) is False
+ asking = asyncio.create_task(
+ svc._ask(sid, "t1", "c1", "Edit", {"file_path": "a.py"}, "") # noqa: SLF001
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(sid, payload["approval_id"], "allow_always")
+ assert await asyncio.wait_for(asking, 2) == "allow_always"
+ assert society_runtime.roster.agent.approval_rules["always_allow"] == []
+ assert "Edit" in svc.always_allowed(sid)
+ assert svc.store.get_session(sid).permission_mode == "ask" # type: ignore[union-attr]
+
+ asyncio.run(scenario())
+
+
+def test_the_route_takes_a_narrow_rule(tmp_path: Path):
+ app = _app(tmp_path)
+ svc: AgentChatService = app.state.agent_chat
+ session = svc.store.create_session(
+ provider="claude-api", model="m", effort="medium", cwd=str(tmp_path), surface="jarvis"
+ )
+ with TestClient(app) as client:
+ url = f"/api/agent-chat/sessions/{session.session_id}/approvals/a1"
+ bad = client.post(url, json={"decision": "allow_always", "scope": "chat", "narrow": "x"})
+ assert bad.status_code == 400
+ wrong_scope = client.post(
+ url, json={"decision": "allow_always", "scope": "agent", "narrow": "folder"}
+ )
+ assert wrong_scope.status_code == 400
+
+
+def test_a_narrow_rule_that_cannot_be_saved_never_widens(tmp_path: Path):
+ """"Only this folder" on a call that has no folder: this call runs once,
+ the tool and the chat keep asking."""
+
+ async def scenario() -> None:
+ svc, session = _service(tmp_path)
+ sid = session.session_id
+ q = svc.subscribe(sid)
+ asking = asyncio.create_task(
+ svc._ask(sid, "t1", "c1", "Bash", {"command": "npm test"}, "npm test") # noqa: SLF001
+ )
+ payload = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(
+ sid, payload["approval_id"], "allow_always", scope="chat", narrow="folder"
+ )
+ assert await asyncio.wait_for(asking, 2) == "allow"
+ assert "Bash" not in svc.always_allowed(sid)
+ assert svc.store.get_session(sid).permission_mode == "ask" # type: ignore[union-attr]
+ again = asyncio.create_task(
+ svc._ask(sid, "t1", "c2", "Bash", {"command": "npm test"}, "") # noqa: SLF001
+ )
+ card = (await _next(q, "approval_required"))["payload"]
+ svc.resolve_approval(sid, card["approval_id"], "deny")
+ assert await asyncio.wait_for(again, 2) == "deny"
+
+ asyncio.run(scenario())
+
+
+def test_a_narrow_rule_on_an_own_server_tool_matches_its_later_calls():
+ from dodaios.agent_chat.approval_card import narrow_matches, narrow_tool
+
+ rule = {"tool": narrow_tool("mcp__dodaios__shell"), "kind": "command", "value": "ls"}
+ assert narrow_matches(rule, "mcp__jarvis__shell", {"command": "ls"})
+ other = {"tool": narrow_tool("mcp__fs__shell"), "kind": "command", "value": "ls"}
+ assert narrow_matches(other, "mcp__fs__shell", {"command": "ls"})
+ assert not narrow_matches(other, "mcp__evil__shell", {"command": "ls"})
+
+
+def test_the_home_folder_is_never_offered_as_only_this_folder(tmp_path: Path):
+ from dodaios.agent_chat.approval_card import narrow_options
+
+ home = str(tmp_path / "home")
+ at_home = narrow_options("files", {"file_path": str(tmp_path / "home" / "x.txt")}, "", home)
+ assert at_home == []
+ above = narrow_options("files", {"file_path": str(tmp_path / "y.txt")}, "", home)
+ assert above == []
+ deeper = narrow_options(
+ "files", {"file_path": str(tmp_path / "home" / "proj" / "z.txt")}, "", home
+ )
+ assert deeper and deeper[0]["value"] == str(tmp_path / "home" / "proj")
+ assert deeper[0]["label"].replace("\\", "/") == "~/proj"