AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): approval rules can hold for one chat, one Expert, or the whole team (#14931)
Reinier van der Leereacbcd0ad2be
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.pyindex 22ebe6afd3..18aef6abbf 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py@@ -166,6 +166,13 @@ class ReviewItem(BaseModel):"the chat instead of asking."),)+ chat_rule_scope: Literal["chat", "expert", "team"] = Field(+ default="chat",+ description=(+ "Where chat_rule holds: this chat, every chat with this chat's "+ "Expert (or Otto), or every Expert on the user's team."+ ),+ )@field_validator("reviewed_data")@classmethoddiff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.pyindex 0942e8bbec..e3f3c354ac 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py@@ -1,4 +1,5 @@import datetime+from types import SimpleNamespacefrom typing import AsyncGeneratorimport httpx@@ -1423,10 +1424,13 @@ async def test_an_answer_on_a_chat_card_wakes_that_chat(@pytest.mark.asyncio(loop_scope="session")[email protected]("scope", ["chat", "expert", "team"])async def test_an_approved_chat_card_sets_the_rule_it_asked_for(client: httpx.AsyncClient,mocker: pytest_mock.MockerFixture,sample_pending_review: PendingHumanReviewModel,+ test_user_id: str,+ scope: str,) -> None:"""The rule lands on the subject the gate stored with the held call."""review = sample_pending_review.model_copy(@@ -1460,6 +1464,11 @@ async def test_an_approved_chat_card_sets_the_rule_it_asked_for()mocker.patch(f"{routes}.wake_for_held_calls")set_rule = mocker.patch("backend.copilot.gate.chat_rules.set_rule")+ set_scoped_rule = mocker.patch("backend.copilot.gate.chat_rules.set_scoped_rule")+ mocker.patch(+ "backend.copilot.gate.chat_rules.get_chat_session_metadata",+ return_value=SimpleNamespace(expert_id="frankie"),+ )response = await client.post("/api/review/action",@@ -1469,6 +1478,7 @@ async def test_an_approved_chat_card_sets_the_rule_it_asked_for("node_exec_id": "test_node_123","approved": True,"chat_rule": "allow",+ "chat_rule_scope": scope,}]},@@ -1476,3 +1486,10 @@ async def test_an_approved_chat_card_sets_the_rule_it_asked_for(assert response.status_code == 200set_rule.assert_awaited_once_with("s1", "mcp:h/t", "allow")+ if scope == "chat":+ set_scoped_rule.assert_not_called()+ else:+ expert = "frankie" if scope == "expert" else None+ set_scoped_rule.assert_awaited_once_with(+ scope, test_user_id, expert, "mcp:h/t", "allow"+ )diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.pyindex 5a9ae0597b..146a946413 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py@@ -359,9 +359,11 @@ async def process_review_action(if chat_session_id is not None and chat_rule_keys:await set_chat_rules(chat_session_id,+ user_id,updated_reviews,{review.node_exec_id: review.chat_rule for review in request.reviews},chat_rule_keys,+ {review.node_exec_id: review.chat_rule_scope for review in request.reviews},)# A held call finishes on its own: the answer starts the chat's next turn.diff --git a/autogpt_platform/backend/backend/copilot/gate/__init__.py b/autogpt_platform/backend/backend/copilot/gate/__init__.pyindex aa4a8c8d8c..d78b1a1c9b 100644--- a/autogpt_platform/backend/backend/copilot/gate/__init__.py+++ b/autogpt_platform/backend/backend/copilot/gate/__init__.py@@ -130,7 +130,10 @@ async def check_action(if review is not None and review.status == ReviewStatus.REJECTED:await review_store.consume(review_id, user_id)await chat_rules.set_ask(- session_id, await held.rule_key(session_id, review_id, tool_name)+ session_id,+ await held.rule_key(session_id, review_id, tool_name),+ user_id,+ session.expert_id,)return Decision(allowed=False, reason=_REJECTED)if review is not None and review.status == ReviewStatus.WAITING:@@ -146,15 +149,17 @@ async def check_action(mode = resolve_mode(session)# Only a subject that can be parked can carry a rule, so reads and# workspace work skip the Redis round trip.- rule = (- await chat_rules.rule_for(session_id, rule_key) if effect in _PARKABLE else None+ hit = (+ await chat_rules.rule_for(session_id, rule_key, user_id, session.expert_id)+ if effect in _PARKABLE+ else None)+ rule = hit.rule if hit else None# A judge rule covers irreversible subjects too: the user chose the supervisor.verdict = _RULE_VERDICTS[rule] if rule else verdict_for_effect(mode, effect)reason_kind: review_store.ReasonKind- if rule in ("ask", "unreadable"):- reason = chat_rules.DECLINED if rule == "ask" else chat_rules.UNREADABLE- reason_kind = "rule"+ if hit and rule in ("ask", "unreadable"):+ reason, reason_kind = hit.reason, "rule"elif verdict is Verdict.RUN:return ALLOWelif verdict is Verdict.ASK and subject is not None and subject.reason:diff --git a/autogpt_platform/backend/backend/copilot/gate/chat_rules.py b/autogpt_platform/backend/backend/copilot/gate/chat_rules.pyindex e7832bade3..63936af622 100644--- a/autogpt_platform/backend/backend/copilot/gate/chat_rules.py+++ b/autogpt_platform/backend/backend/copilot/gate/chat_rules.py@@ -1,25 +1,34 @@-"""Chat-scoped rules: the user's own word on a subject for the rest of the chat.+"""Chat rules: the user's own word on a subject from now on.A rejection sets ``ask``; a card answered with a rule sets ``allow`` or-``judge``. A subject holds one rule at a time and the latest answer replaces it.+``judge``. A rule holds in its chat, or wider when the user picks a scope: every+chat with that Expert (or with Otto), or every Expert on their team. The+narrowest rule on record decides, and the latest answer replaces a rule."""import logging+from datetime import UTC, date, datetimefrom typing import Literal, Mapping, get_argsfrom prisma.enums import ReviewStatus+from pydantic import BaseModel, ConfigDictfrom backend.api.features.graph_executions.review.model import PendingHumanReviewModel+from backend.copilot.constants import AUTOPILOT_NAME+from backend.copilot.model import ChatSessionInfo, get_chat_session_metadatafrom backend.data.redis_client import get_redis_asynclogger = logging.getLogger(__name__)ChatRule = Literal["allow", "judge", "ask"]_RULES: dict[str, ChatRule] = {rule: rule for rule in get_args(ChatRule)}+Scope = Literal["chat", "expert", "team"]# Outlives any chat anyone is still in; dead chats expire out of Redis._TTL_SECONDS = 90 * 24 * 60 * 60_ASK_KEY = "copilot:gate:ask:"+# Otto's own chats have no expert id; their rules share one key.+_OTTO = "otto"DECLINED = "You declined this action earlier in this chat."# An outage asks rather than runs, but must not claim the user said no.@@ -29,10 +38,49 @@ UNREADABLE = ()-async def set_ask(session_id: str, rule_key: str) -> None:+class RuleHit(BaseModel):+ model_config = ConfigDict(frozen=True)++ rule: ChatRule | Literal["unreadable"]+ scope: Scope = "chat"+ since: date | None = None+ otto: bool = False++ @property+ def reason(self) -> str:+ if self.rule == "unreadable":+ return UNREADABLE+ if self.scope == "chat" or self.since is None:+ return DECLINED+ when = f"{self.since.day} {self.since:%b}"+ if self.scope == "team":+ return f"You declined this for every Expert on your team on {when}."+ who = AUTOPILOT_NAME if self.otto else "this Expert"+ return f"You declined this in every chat with {who} on {when}."+++async def set_ask(+ session_id: str, rule_key: str, user_id: str, expert_id: str | None+) -> None:"""Only the user's answer on a card replaces an ask, so re-proposing the- call with a space added to its arguments cannot buy a fresh verdict."""+ call with a space added to its arguments cannot buy a fresh verdict.++ A rejection also revokes every wider rule that would have run the call.+ """await set_rule(session_id, rule_key, "ask")+ for scope in ("expert", "team"):+ key = _scoped_key(scope, user_id, expert_id, rule_key)+ try:+ redis = await get_redis_async()+ held = await redis.get(key) is not None+ except Exception:+ logger.warning(+ f"Gate could not check {scope} rules for user {user_id}",+ exc_info=True,+ )+ continue+ if held:+ await _set_scoped(key, "ask")async def set_rule(session_id: str, rule_key: str, rule: ChatRule) -> None:@@ -46,46 +94,106 @@ async def set_rule(session_id: str, rule_key: str, rule: ChatRule) -> None:)+async def set_scoped_rule(+ scope: Literal["expert", "team"],+ user_id: str,+ expert_id: str | None,+ rule_key: str,+ rule: ChatRule,+) -> None:+ await _set_scoped(_scoped_key(scope, user_id, expert_id, rule_key), rule)++async def set_answer_rules(session_id: str,+ user_id: str,answered: Mapping[str, PendingHumanReviewModel],rules: Mapping[str, ChatRule | None],subject_keys: Mapping[str, str],+ scopes: Mapping[str, Scope] | None = None,) -> None:- """The rule each approved card asked for, on the subject it named.+ """The rule each approved card asked for, on the subject it named, at the+ scope the user picked.``subject_keys`` come from the held calls the gate stored, so a click canonly ever rule on a subject the server put on a card."""+ scopes = scopes or {}+ chat: ChatSessionInfo | None = Nonefor review_id, rule in rules.items():row = answered.get(review_id)key = subject_keys.get(review_id)- if rule and key and row is not None and row.status == ReviewStatus.APPROVED:- await set_rule(session_id, key, rule)+ if not (rule and key and row is not None):+ continue+ if row.status != ReviewStatus.APPROVED:+ continue+ await set_rule(session_id, key, rule)+ scope = scopes.get(review_id, "chat")+ if scope == "team":+ await set_scoped_rule("team", user_id, None, key, rule)+ elif scope == "expert":+ chat = chat or await get_chat_session_metadata(session_id, user_id)+ # An unknown chat must not rule for Otto's chats instead.+ if chat is not None:+ await set_scoped_rule("expert", user_id, chat.expert_id, key, rule)async def rule_for(- session_id: str, rule_key: str-) -> ChatRule | Literal["unreadable"] | None:- """``unreadable`` asks like ``ask`` but must not claim the user said no."""+ session_id: str, rule_key: str, user_id: str, expert_id: str | None+) -> RuleHit | None:+ """The narrowest rule on record: this chat's, then the Expert's, then the+ team's. ``unreadable`` asks like ``ask`` but must not claim the user said no."""try:redis = await get_redis_async()raw = await redis.get(_key(session_id, rule_key))+ if raw is not None:+ # Rows written before rules had decisions hold "1", which meant ask.+ return RuleHit(rule=_RULES.get(_text(raw), "ask"))+ for scope in ("expert", "team"):+ raw = await redis.get(_scoped_key(scope, user_id, expert_id, rule_key))+ if raw is not None:+ rule, _, since = _text(raw).partition(" ")+ return RuleHit(+ rule=_RULES.get(rule, "ask"),+ scope=scope,+ since=date.fromisoformat(since),+ otto=expert_id is None,+ )except Exception:logger.warning(f"Gate could not read chat rules for session {session_id}; ""assuming the subject asks",exc_info=True,)- return "unreadable"- if raw is None:- return None- value = raw.decode() if isinstance(raw, bytes) else str(raw)- # Rows written before rules had decisions hold "1", which meant ask.- return _RULES.get(value, "ask")+ return RuleHit(rule="unreadable")+ return None+++async def _set_scoped(key: str, rule: ChatRule) -> None:+ today = datetime.now(UTC).date().isoformat()+ try:+ redis = await get_redis_async()+ await redis.setex(key, _TTL_SECONDS, f"{rule} {today}")+ except Exception:+ logger.warning(f"Gate could not persist a scoped {rule} rule", exc_info=True)def _key(session_id: str, rule_key: str) -> str:# A flag per (session, subject): the cluster client's set operations are# not typed as awaitable.return f"{_ASK_KEY}{session_id}:{rule_key}"+++def _scoped_key(+ scope: Literal["expert", "team"],+ user_id: str,+ expert_id: str | None,+ rule_key: str,+) -> str:+ if scope == "team":+ return f"{_ASK_KEY}team:{user_id}:{rule_key}"+ return f"{_ASK_KEY}expert:{user_id}:{expert_id or _OTTO}:{rule_key}"+++def _text(raw: bytes | str) -> str:+ return raw.decode() if isinstance(raw, bytes) else str(raw)diff --git a/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py b/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.pyindex 7c36e44573..00658c307a 100644--- a/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/chat_rules_test.py@@ -1,3 +1,4 @@+from datetime import datefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patch@@ -31,10 +32,11 @@ def _row(status: ReviewStatus) -> SimpleNamespace:async def test_an_approved_card_rules_on_the_subject_it_named(redis):await chat_rules.set_answer_rules(- "s", {"a": _row(ReviewStatus.APPROVED)}, {"a": "allow"}, {"a": "mcp:h/t"}+ "s", "u", {"a": _row(ReviewStatus.APPROVED)}, {"a": "allow"}, {"a": "mcp:h/t"})- assert await chat_rules.rule_for("s", "mcp:h/t") == "allow"- assert await chat_rules.rule_for("s", "mcp:h/other") is None+ assert await _rule("s", "mcp:h/t") == "allow"+ assert await _rule("s", "mcp:h/other") is None+ assert await _rule("other-chat", "mcp:h/t") is None@pytest.mark.parametrize(@@ -47,27 +49,76 @@ async def test_an_approved_card_rules_on_the_subject_it_named(redis):],)async def test_only_an_approved_subject_card_sets_a_rule(redis, status, keys):- await chat_rules.set_answer_rules("s", {"a": _row(status)}, {"a": "allow"}, keys)+ await chat_rules.set_answer_rules(+ "s", "u", {"a": _row(status)}, {"a": "allow"}, keys, {"a": "team"}+ )assert redis.data == {}async def test_a_later_answer_replaces_the_rule(redis):- await chat_rules.set_ask("s", "mcp:h/t")+ await chat_rules.set_ask("s", "mcp:h/t", "u", None)await chat_rules.set_rule("s", "mcp:h/t", "judge")- assert await chat_rules.rule_for("s", "mcp:h/t") == "judge"+ assert await _rule("s", "mcp:h/t") == "judge"async def test_a_rule_written_before_decisions_existed_still_asks():store = _Redis({"copilot:gate:ask:s:bash_exec": "1"})with patch.object(chat_rules, "get_redis_async", AsyncMock(return_value=store)):- assert await chat_rules.rule_for("s", "bash_exec") == "ask"+ assert await _rule("s", "bash_exec") == "ask"async def test_an_unreadable_store_asks():with patch.object(chat_rules, "get_redis_async", AsyncMock(side_effect=ConnectionError)):- assert await chat_rules.rule_for("s", "mcp:h/t") == "unreadable"+ assert await _rule("s", "mcp:h/t") == "unreadable"+++ "narrow, wide", [("chat", "expert"), ("chat", "team"), ("expert", "team")]+)[email protected]("narrow_rule, wide_rule", [("ask", "allow"), ("allow", "ask")])+async def test_the_narrowest_rule_decides(redis, narrow, wide, narrow_rule, wide_rule):+ await _set(wide, wide_rule)+ await _set(narrow, narrow_rule)+ assert await _rule("s", "mcp:h/t", "frankie") == narrow_rule+++async def test_an_expert_rule_holds_only_in_that_experts_chats(redis):+ await _set("expert", "allow")+ assert await _rule("other-chat", "mcp:h/t", "frankie") == "allow"+ assert await _rule("other-chat", "mcp:h/t", "maria") is None+ assert await _rule("other-chat", "mcp:h/t", None) is None+++async def test_a_rejection_revokes_every_wider_rule_that_would_have_run_it(redis):+ await _set("expert", "allow")+ await _set("team", "judge")+ await chat_rules.set_ask("s", "mcp:h/t", "u", "frankie")++ assert await _rule("s", "mcp:h/t", "frankie") == "ask"+ assert await _rule("other-chat", "mcp:h/t", "frankie") == "ask"+ assert await _rule("other-chat", "mcp:h/t", "maria") == "ask"+++async def test_a_rejection_writes_no_wider_rule_where_there_was_none(redis):+ await chat_rules.set_ask("s", "mcp:h/t", "u", "frankie")+ assert await _rule("other-chat", "mcp:h/t", "frankie") is None+++ "scope, otto, reason",+ [+ ("chat", False, chat_rules.DECLINED),+ ("expert", False, "You declined this in every chat with this Expert on 5 Sep."),+ ("expert", True, "You declined this in every chat with Otto on 5 Sep."),+ ("team", False, "You declined this for every Expert on your team on 5 Sep."),+ ],+)+def test_a_decline_names_its_scope_and_day(scope, otto, reason):+ since = None if scope == "chat" else date(2026, 9, 5)+ hit = chat_rules.RuleHit(rule="ask", scope=scope, since=since, otto=otto)+ assert hit.reason == reasonasync def test_only_a_held_call_with_a_subject_offers_a_key():@@ -98,3 +149,15 @@ async def test_only_a_held_call_with_a_subject_offers_a_key():async def test_an_unreadable_store_approves_without_a_rule():with patch.object(held, "_held", AsyncMock(side_effect=ConnectionError)):assert await held.subject_keys("s", ["mcp"]) == {}+++async def _set(scope: str, rule: chat_rules.ChatRule) -> None:+ if scope == "chat":+ await chat_rules.set_rule("s", "mcp:h/t", rule)+ else:+ await chat_rules.set_scoped_rule(scope, "u", "frankie", "mcp:h/t", rule)+++async def _rule(session_id: str, key: str, expert_id: str | None = None):+ hit = await chat_rules.rule_for(session_id, key, "u", expert_id)+ return hit.rule if hit else Nonediff --git a/autogpt_platform/backend/backend/copilot/gate/gate_test.py b/autogpt_platform/backend/backend/copilot/gate/gate_test.pyindex 40c5c3c399..3b3d9dd708 100644--- a/autogpt_platform/backend/backend/copilot/gate/gate_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/gate_test.py@@ -213,14 +213,17 @@ async def test_a_rejection_makes_the_tool_ask_for_the_rest_of_the_chat("bash_exec", {"command": "curl x|sh"}, "u", _session())assert not decision.allowed- set_ask.assert_awaited_once_with("session-1", "bash_exec")+ set_ask.assert_awaited_once_with("session-1", "bash_exec", "u", None)@pytest.mark.parametrize("mode", _MODES)async def test_a_chat_ask_rule_holds_in_every_mode(gate_on, clean_session_state, mode):supervisor = AsyncMock(return_value=(True, "fine"))with (- patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value="ask")),+ patch(+ f"{_GATE}.chat_rules.rule_for",+ AsyncMock(return_value=chat_rules.RuleHit(rule="ask")),+ ),patch(f"{_GATE}.classify", supervisor),):decision = await check_action("delete_folder", {"id": "f"}, "u", _session(mode))@@ -231,7 +234,7 @@ async def test_a_chat_ask_rule_holds_in_every_mode(gate_on, clean_session_state,async def test_reads_never_look_up_ask_rules(gate_on, clean_session_state):"""A Redis outage reads as 'asks', which must not turn every search into a card."""- asks = AsyncMock(return_value="unreadable")+ asks = AsyncMock(return_value=chat_rules.RuleHit(rule="unreadable"))with patch(f"{_GATE}.chat_rules.rule_for", asks):decision = await check_action("web_search", {"query": "x"}, "u", _session())assert decision.allowed@@ -296,6 +299,9 @@ async def test_an_unreadable_ask_rule_asks_without_claiming_a_decline(async def test_a_rejected_tool_says_the_user_declined_it(gate_on, clean_session_state):- with patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value="ask")):+ with patch(+ f"{_GATE}.chat_rules.rule_for",+ AsyncMock(return_value=chat_rules.RuleHit(rule="ask")),+ ):decision = await check_action("delete_folder", {"id": "f"}, "u", _session())assert decision.reason == chat_rules.DECLINEDdiff --git a/autogpt_platform/backend/backend/copilot/gate/held.py b/autogpt_platform/backend/backend/copilot/gate/held.pyindex a0bd54ad28..7cb3fd8cb5 100644--- a/autogpt_platform/backend/backend/copilot/gate/held.py+++ b/autogpt_platform/backend/backend/copilot/gate/held.py@@ -338,7 +338,12 @@ async def _outcome(return await answered_read(user_id, row)if row.status == ReviewStatus.REJECTED:await review_store.consume(call.review_id, user_id)- await chat_rules.set_ask(session.session_id, call.rule_key or call.tool_name)+ await chat_rules.set_ask(+ session.session_id,+ call.rule_key or call.tool_name,+ user_id,+ session.expert_id,+ )return "rejected", ("Nothing ran: the user declined this action. Do not retry it or ""reach the same effect another way."diff --git a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py b/autogpt_platform/backend/backend/copilot/gate/held_db_test.pyindex 775f5962fa..5013dd5a99 100644--- a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/held_db_test.py@@ -414,7 +414,9 @@ async def test_a_rejection_never_runs_and_the_tool_asks_from_then_on(assert post_tool.runs == []assert "declined" in delivered[0].contentassert delivered[0].metadata["held_call"]["outcome"] == "rejected"- assert await chat_rules.rule_for(session.session_id, _TOOL) == "ask"+ assert await chat_rules.rule_for(+ session.session_id, _TOOL, test_user_id, None+ ) == chat_rules.RuleHit(rule="ask")@pytest.mark.asyncio(loop_scope="session")diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.pyindex 9c545d1c55..e89aad59ab 100644--- a/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py@@ -26,9 +26,14 @@ _GITHUB = "mcp:api.githubcopilot.com"_OPEN_WORLD = "https://mcp.example.com/mcp"-def _session(mode: AutopilotMode = "auto") -> ChatSession:+def _session(+ mode: AutopilotMode = "auto",+ session_id: str = "session-1",+ expert_id: str | None = None,+) -> ChatSession:return ChatSession(- session_id="session-1",+ session_id=session_id,+ expert_id=expert_id,user_id="user-1",usage=[],started_at=datetime.now(UTC),@@ -162,6 +167,80 @@ async def test_a_chat_allow_covers_that_tool_and_no_other_on_the_host(gate, ran)ran.assert_awaited_once()+ "scope, same_expert_runs, other_expert_runs",+ [("chat", False, False), ("expert", True, False), ("team", True, True)],+)+async def test_a_rule_reaches_the_chats_its_scope_names(+ gate, ran, scope, same_expert_runs, other_expert_runs+):+ maria = _session(session_id="chat-a", expert_id="maria")+ assert _is_held(await _call(maria, _OPEN_WORLD, "do_thing", {"n": 1}))+ await _answer_with_rule(gate, "allow", maria, scope)++ maria_again = _session(session_id="chat-a2", expert_id="maria")+ max_ = _session(session_id="chat-b", expert_id="max")+ held = _is_held(await _call(maria_again, _OPEN_WORLD, "do_thing", {"n": 2}))+ assert held != same_expert_runs+ held = _is_held(await _call(max_, _OPEN_WORLD, "do_thing", {"n": 3}))+ assert held != other_expert_runs+++async def test_an_expert_rule_covers_otto_only_from_an_otto_chat(gate, ran):+ otto = _session(session_id="chat-o")+ assert _is_held(await _call(otto, _OPEN_WORLD, "do_thing", {"n": 1}))+ await _answer_with_rule(gate, "allow", otto, "expert")++ assert not _is_held(+ await _call(_session(session_id="chat-o2"), _OPEN_WORLD, "do_thing", {"n": 2})+ )+ maria = _session(session_id="chat-a", expert_id="maria")+ assert _is_held(await _call(maria, _OPEN_WORLD, "do_thing", {"n": 3}))++[email protected]("wide", ["expert", "team"])+async def test_a_chat_ask_beats_a_wider_allow(gate, ran, wide):+ maria = _session(session_id="chat-a", expert_id="maria")+ assert _is_held(await _call(maria, _OPEN_WORLD, "do_thing", {"n": 1}))+ subject = gate.open_review.await_args.args[6]+ await _answer_with_rule(gate, "allow", maria, wide)+ maria_again = _session(session_id="chat-a2", expert_id="maria")+ await chat_rules.set_rule("chat-a2", subject.key, "ask")++ assert _is_held(await _call(maria_again, _OPEN_WORLD, "do_thing", {"n": 2}))+ assert not _is_held(await _call(maria, _OPEN_WORLD, "do_thing", {"n": 3}))+++async def test_a_rejection_revokes_the_expert_and_team_rules_that_ran_it(gate, ran):+ max_ = _session(session_id="chat-b", expert_id="max")+ assert _is_held(await _call(max_, _OPEN_WORLD, "do_thing", {"n": 1}))+ subject = gate.open_review.await_args.args[6]+ await _answer_with_rule(gate, "allow", max_, "expert")+ await chat_rules.set_scoped_rule("team", "user-1", None, subject.key, "allow")++ max_again = _session(session_id="chat-b2", expert_id="max")+ gate.find_review.return_value = SimpleNamespace(status=ReviewStatus.REJECTED)+ with patch(f"{_GATE}.held.rule_key", AsyncMock(return_value=subject.key)):+ assert _is_held(await _call(max_again, _OPEN_WORLD, "do_thing", {"n": 2}))+ gate.find_review.return_value = None++ for chat, reason in [+ (+ _session(session_id="chat-b3", expert_id="max"),+ "in every chat with this Expert",+ ),+ (+ _session(session_id="chat-c", expert_id="frankie"),+ "for every Expert on your team",+ ),+ ]:+ assert _is_held(await _call(chat, _OPEN_WORLD, "do_thing", {"n": 3}))+ assert reason in gate.open_review.await_args.args[5]+ # The chat the rule was given in keeps its own word.+ assert not _is_held(await _call(max_, _OPEN_WORLD, "do_thing", {"n": 4}))+ ran.assert_awaited_once()++async def test_a_chat_judge_sends_the_next_call_to_the_supervisor(gate, ran):session = _session("ask_first")assert _is_held(await _call(session, _OPEN_WORLD, "do_thing", {"n": 1}))@@ -235,13 +314,28 @@ async def test_listing_a_servers_tools_never_asks(gate, ran):gate.open_review.assert_not_awaited()-async def _answer_with_rule(gate, rule: chat_rules.ChatRule) -> None:+async def _answer_with_rule(+ gate,+ rule: chat_rules.ChatRule,+ session: ChatSession | None = None,+ scope: chat_rules.Scope = "chat",+) -> None:"""What the approve endpoint does for the card the gate just opened."""+ session = session or _session()subject = gate.open_review.await_args.args[6]row = SimpleNamespace(status=ReviewStatus.APPROVED)- await chat_rules.set_answer_rules(- "session-1", {"r": row}, {"r": rule}, {"r": subject.key}- )+ chat = SimpleNamespace(expert_id=session.expert_id)+ with patch(+ f"{_GATE}.chat_rules.get_chat_session_metadata", AsyncMock(return_value=chat)+ ):+ await chat_rules.set_answer_rules(+ session.session_id,+ "user-1",+ {"r": row},+ {"r": rule},+ {"r": subject.key},+ {"r": scope},+ )@pytest.mark.parametrize(diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.pyindex 243b1f0f37..994e2049b5 100644--- a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py@@ -239,7 +239,7 @@ async def test_a_rejection_asks_for_the_subject_not_the_tool(gate, ran):patch(f"{_GATE}.review_store.review_id_for", return_value="x"),):await _run_capability(_session(), GetWikipediaSummaryBlock().id, {"topic": "x"})- set_ask.assert_awaited_once_with("session-1", "block:abc")+ set_ask.assert_awaited_once_with("session-1", "block:abc", "user-1", None)async def test_the_gate_off_resolves_no_subject():diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsxindex 20ede2cc98..08b2004308 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx@@ -97,7 +97,11 @@ export const BlockCard: Story = {export const WorkflowRun: Story = { args: queueOf([workflow()]) };// The Approve menu: the chat rules the server allows on this subject.-export const RuleMenu: Story = { args: queueOf([mcpTool()]) };+export const RuleMenu: Story = {+ args: { ...queueOf([mcpTool()]), expertName: "Frankie" },+};++export const RuleMenuWithOtto: Story = { args: queueOf([mcpTool()]) };export const BlockChainRow: StoryObj = {render: () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsxindex 1d03c4a63e..5b47451560 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx@@ -17,13 +17,15 @@ import { useApprovalQueue } from "./useApprovalQueue";interface Props {// Oldest first, as the gate raised them.items: ApprovalItem[];+ // The chat's Expert, or null in a chat with Otto.+ expertName?: string | null;onAnswered: () => void;}// From this many cards up, each collapses to one line.export const COMPACT_FROM = 4;-export function ApprovalQueue({ items, onAnswered }: Props) {+export function ApprovalQueue({ items, expertName = null, onAnswered }: Props) {const queue = useApprovalQueue({ items, onAnswered });const { pending, receipts } = queue;if (pending.length === 0 && receipts.length === 0) return null;@@ -83,7 +85,10 @@ export function ApprovalQueue({ items, onAnswered }: Props) {item={item}status={queue.statusOf(item.reviewId)}failed={queue.hasFailed(item.reviewId)}- onApprove={(rule) => queue.answer([item], true, rule)}+ expertName={expertName}+ onApprove={(rule, scope) =>+ queue.answer([item], true, rule, scope)+ }onReject={() => queue.answer([item], false)}/>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsxindex c74b074296..b438e55ef0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx@@ -163,8 +163,10 @@ test("the approve menu offers the rules the server allows", async () => {await userEvent.click(await screen.findByRole("button", { name: "More ways to approve" }),);- expect(await screen.findByText("Approve for this chat")).toBeDefined();- expect(screen.queryByText(/judge from now on/)).toBeNull();+ expect(+ await screen.findByText("Approve Gmail Send from now on"),+ ).toBeDefined();+ expect(screen.queryByText(/^Let Otto judge/)).toBeNull();expect(screen.queryByText(/Always allow/)).toBeNull();});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsxindex 8a93f81830..fab5bc83a4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/chatRule.test.tsx@@ -29,33 +29,47 @@ function serve(return sent;}-function renderQueue() {+function renderQueue(expertName: string | null = "Frankie") {render(<CopilotChatActionsProvider onSend={vi.fn()} onBackendTurn={vi.fn()}>- <CopilotPendingReviews chatSessionId={CHAT_SESSION} />+ <CopilotPendingReviews+ chatSessionId={CHAT_SESSION}+ expertName={expertName}+ /></CopilotChatActionsProvider>,);}+async function openMenu() {+ await userEvent.click(+ await screen.findByRole("button", { name: "More ways to approve" }),+ );+}++const MAIL = "Gmail Send";+const MCP = "create_issue on mcp.linear.app";+test.each([- ["Approve for this chat", "allow", "a block", mail("m1")],- ["Let Otto judge from now on", "judge", "a block", mail("m1")],- ["Approve for this chat", "allow", "an MCP tool", mcpTool("m1")],- ["Let Otto judge from now on", "judge", "an MCP tool", mcpTool("m1")],+ [`Approve ${MAIL} from now on`, "allow", mail("m1")],+ [`Let Otto judge ${MAIL} from now on`, "judge", mail("m1")],+ [`Approve ${MCP} from now on`, "allow", mcpTool("m1")],+ [`Let Otto judge ${MCP} from now on`, "judge", mcpTool("m1")],])(- "choosing %s approves the call and sets the %s rule on %s",- async (item, rule, _subject, review) => {+ "choosing %s approves the call and sets the %s rule for the Expert by default",+ async (item, rule, review) => {const sent = serve(review);renderQueue();- await userEvent.click(- await screen.findByRole("button", { name: "More ways to approve" }),- );+ await openMenu();await userEvent.click(await screen.findByText(item));await waitFor(() => expect(sent).toHaveLength(1));expect(sent[0].reviews).toEqual([- expect.objectContaining({ approved: true, chat_rule: rule }),+ expect.objectContaining({+ approved: true,+ chat_rule: rule,+ chat_rule_scope: "expert",+ }),]);},);@@ -67,7 +81,73 @@ test("a plain approve sets no rule", async () => {await userEvent.click(await screen.findByRole("button", { name: "Approve" }));await waitFor(() => expect(sent).toHaveLength(1));- expect(sent[0].reviews).toEqual([+ expect(sent[0].reviews[0]).toEqual(expect.objectContaining({ approved: true, chat_rule: null }),- ]);+ );+ expect(sent[0].reviews[0]).not.toHaveProperty("chat_rule_scope");});++test.each([+ ["Frankie", "Frankie, every chat"],+ [null, "Otto, every chat"],+])(+ "the scope picker starts on the chat's own Expert (%s)",+ async (expertName, label) => {+ serve();+ renderQueue(expertName);++ await openMenu();+ const scope = await screen.findByRole("menuitemradio", { name: label });+ expect(scope.getAttribute("aria-checked")).toBe("true");+ expect(+ screen+ .getByRole("menuitemradio", { name: "This chat" })+ .getAttribute("aria-checked"),+ ).toBe("false");+ },+);++test.each([+ [+ "This chat",+ "chat",+ "Frankie won't ask again for this in this chat",+ "A check decides each time it runs in this chat, and asks you only when it isn't sure",+ ],+ [+ "Frankie, every chat",+ "expert",+ "Frankie won't ask again for this in any chat",+ "A check decides each time Frankie runs it, in any chat, and asks you only when it isn't sure",+ ],+ [+ "Every Expert on my team",+ "team",+ "No Expert on your team will ask again for this",+ "A check decides each time any Expert on your team runs it, and asks you only when it isn't sure",+ ],+])(+ "picking %s words both actions for that scope and sends it",+ async (label, scope, allowDetail, judgeDetail) => {+ const sent = serve();+ renderQueue("Frankie");++ await openMenu();+ await userEvent.click(+ await screen.findByRole("menuitemradio", { name: label }),+ );+ expect(await screen.findByText(allowDetail)).toBeDefined();+ expect(screen.getByText(judgeDetail)).toBeDefined();+ // Otto is the supervisor in every Expert's chat.+ expect(+ screen.getByText(`Let Otto judge ${MAIL} from now on`),+ ).toBeDefined();+ expect(screen.queryByText(/Let Frankie judge/)).toBeNull();+ await userEvent.click(screen.getByText(`Approve ${MAIL} from now on`));++ await waitFor(() => expect(sent).toHaveLength(1));+ expect(sent[0].reviews).toEqual([+ expect.objectContaining({ chat_rule: "allow", chat_rule_scope: scope }),+ ]);+ },+);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsxindex be529050f2..3e79069d4c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx@@ -6,6 +6,7 @@ import { ApprovalFields } from "@/components/organisms/ApprovalFields/ApprovalFiimport {type ApprovalItem,type ChatRule,+ type RuleScope,isBare,isHeldRead,reasonLine,@@ -21,7 +22,8 @@ interface Props {item: ApprovalItem;status: CardStatus;failed: boolean;- onApprove: (rule?: ChatRule) => void;+ expertName: string | null;+ onApprove: (rule?: ChatRule, scope?: RuleScope) => void;onReject: () => void;}@@ -29,6 +31,7 @@ export function ApprovalCard({item,status,failed,+ expertName,onApprove,onReject,}: Props) {@@ -42,6 +45,7 @@ export function ApprovalCard({<ApproveSplitButtonlabel={read ? `Release to ${AUTOPILOT_NAME}` : "Approve"}subjectName={item.subject.name}+ expertName={expertName}rules={read ? [] : item.chatRulesAllowed}loading={status === "approving"}disabled={busy}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApproveSplitButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApproveSplitButton.tsxindex b47ce8858c..d6664a06a1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApproveSplitButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApproveSplitButton.tsx@@ -1,5 +1,6 @@"use client";+import { useState } from "react";import { ArrowDown01Icon } from "@hugeicons/core-free-icons";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";@@ -7,39 +8,36 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/molecules/DropdownMenu/DropdownMenu";import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";-import type { ChatRule } from "../../helpers";+import type { ChatRule, RuleScope } from "../../helpers";interface Props {label: string;subjectName: string;+ expertName: string | null;rules: ChatRule[];loading: boolean;disabled: boolean;- onApprove: (rule?: ChatRule) => void;+ onApprove: (rule?: ChatRule, scope?: RuleScope) => void;}-const RULE_COPY: Record<ChatRule, (subject: string) => [string, string]> = {- allow: (subject) => [- "Approve for this chat",- `${subject} runs without asking until this chat ends`,- ],- judge: () => [- `Let ${AUTOPILOT_NAME} judge from now on`,- "A check decides each time and asks you only when it isn't sure",- ],-};-export function ApproveSplitButton({label,subjectName,+ expertName,rules,loading,disabled,onApprove,}: Props) {+ const [scope, setScope] = useState<RuleScope>("expert");+ const who = expertName ?? AUTOPILOT_NAME;const main = (<Buttonsize="small"@@ -72,13 +70,13 @@ export function ApproveSplitButton({<Icon icon={ArrowDown01Icon} size={14} aria-hidden /></Button></DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-72">+ <DropdownMenuContent align="start" className="w-80">{rules.map((rule) => {- const [title, detail] = RULE_COPY[rule](subjectName);+ const [title, detail] = ruleCopy(rule, scope, subjectName, who);return (<DropdownMenuItemkey={rule}- onSelect={() => onApprove(rule)}+ onSelect={() => onApprove(rule, scope)}className="flex flex-col items-start gap-0.5 py-2"><span className="text-sm text-zinc-900">{title}</span>@@ -86,8 +84,62 @@ export function ApproveSplitButton({</DropdownMenuItem>);})}+ <DropdownMenuSeparator />+ <DropdownMenuLabel className="text-xs font-normal text-zinc-500">+ Applies to+ </DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={scope}+ onValueChange={(value) => setScope(value as RuleScope)}+ >+ {SCOPES.map((option) => (+ <DropdownMenuRadioItem+ key={option}+ value={option}+ // Picking a scope keeps the menu open so the action can follow.+ onSelect={(event) => event.preventDefault()}+ className="text-sm text-zinc-900"+ >+ {scopeLabel(option, who)}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup></DropdownMenuContent></DropdownMenu></div>);}++const SCOPES: RuleScope[] = ["chat", "expert", "team"];++function scopeLabel(scope: RuleScope, who: string) {+ if (scope === "chat") return "This chat";+ if (scope === "expert") return `${who}, every chat`;+ return "Every Expert on my team";+}++// The supervisor is always Otto, whichever Expert's chat the card is in.+function ruleCopy(+ rule: ChatRule,+ scope: RuleScope,+ subject: string,+ who: string,+): [string, string] {+ if (rule === "allow") {+ const detail = {+ chat: `${who} won't ask again for this in this chat`,+ expert: `${who} won't ask again for this in any chat`,+ team: "No Expert on your team will ask again for this",+ }[scope];+ return [`Approve ${subject} from now on`, detail];+ }+ const runs = {+ chat: "each time it runs in this chat",+ expert: `each time ${who} runs it, in any chat`,+ team: "each time any Expert on your team runs it",+ }[scope];+ return [+ `Let ${AUTOPILOT_NAME} judge ${subject} from now on`,+ `A check decides ${runs}, and asks you only when it isn't sure`,+ ];+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.tsindex b37e45f171..ae2e69b6d3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts@@ -13,6 +13,7 @@ import { asObject, str } from "../ToolChain/resultHelpers";export type ReasonKind = "mode" | "subject" | "supervisor" | "rule" | "content";export type ChatRule = "allow" | "judge";+export type RuleScope = "chat" | "expert" | "team";export interface ApprovalItem {reviewId: string;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.tsindex 5343d45e8a..e979b8ce70 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts@@ -2,7 +2,12 @@ import { useContext, useEffect, useRef, useState } from "react";import { useProcessReviews } from "@/hooks/useProcessReviews";import { HeldOutcomesContext } from "../ChatMessagesContainer/HeldOutcomesContext";import type { CardStatus } from "./components/ApprovalCard/ApprovalCard";-import { type ApprovalItem, type ChatRule, isHeldRead } from "./helpers";+import {+ type ApprovalItem,+ type ChatRule,+ type RuleScope,+ isHeldRead,+} from "./helpers";export interface Receipt {item: ApprovalItem;@@ -45,6 +50,7 @@ export function useApprovalQueue({ items, onAnswered }: Args) {batch: ApprovalItem[],approved: boolean,rule?: ChatRule,+ scope?: RuleScope,) {const ids = batch.map((item) => item.reviewId);setFailed((prev) => prev.filter((id) => !ids.includes(id)));@@ -62,6 +68,7 @@ export function useApprovalQueue({ items, onAnswered }: Args) {node_exec_id: item.reviewId,approved,chat_rule: approved ? (rule ?? null) : null,+ ...(approved && rule && scope ? { chat_rule_scope: scope } : {}),})),batch.map((item) => item.scope),);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 01bb82f057..9bd5e531f6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -848,6 +848,7 @@ export function ChatMessagesContainer({chatSessionId={sessionID}pollWhileEmpty={reviewTarget?.kind === "chat"}refetchKey={countHeldCalls(messages)}+ expertName={expertIdentity?.name ?? null}/>)}{!readOnly &&diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex 065848ecb2..57410623b5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -1530,6 +1530,7 @@ describe("ChatMessagesContainer — pending reviews", () => {chatSessionId: "sess-123",pollWhileEmpty,refetchKey,+ expertName: null,});afterEach(() => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsxindex 24f1260628..be89952e83 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx@@ -13,7 +13,12 @@ import { useCopilotPendingReviews } from "./useCopilotPendingReviews";type Props =| { graphExecId: string; graphId?: string }- | { chatSessionId: string; pollWhileEmpty?: boolean; refetchKey?: number };+ | {+ chatSessionId: string;+ pollWhileEmpty?: boolean;+ refetchKey?: number;+ expertName?: string | null;+ };/*** Renders the chat's pending reviews, or those of an agent run it started:@@ -23,6 +28,7 @@ type Props =export function CopilotPendingReviews(props: Props) {const { onSend, onBackendTurn } = useCopilotChatActions();const graphExecId = "graphExecId" in props ? props.graphExecId : "";+ const expertName = "expertName" in props ? props.expertName : null;const { pendingReviews, refetch } = useCopilotPendingReviews(props);const heldCalls = pendingReviews@@ -66,7 +72,11 @@ export function CopilotPendingReviews(props: Props) {return (<div className="flex flex-col gap-2 py-2 empty:hidden">- <ApprovalQueue items={heldCalls} onAnswered={handleHeldCallAnswered} />+ <ApprovalQueue+ items={heldCalls}+ expertName={expertName}+ onAnswered={handleHeldCallAnswered}+ />{otherReviews.length > 0 && (<PendingReviewsListreviews={otherReviews}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex d12809e6a6..386a5d6840 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -28653,6 +28653,13 @@],"title": "Chat Rule","description": "AutoPilot cards naming a subject only: once approved, the subject runs ('allow') or goes to the supervisor ('judge') for the rest of the chat instead of asking."+ },+ "chat_rule_scope": {+ "type": "string",+ "enum": ["chat", "expert", "team"],+ "title": "Chat Rule Scope",+ "description": "Where chat_rule holds: this chat, every chat with this chat's Expert (or Otto), or every Expert on the user's team.",+ "default": "chat"}},"type": "object",