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(frontend/copilot): AutoPilot approval card and queue design update (#14885)
Reinier van der Leerd9d573d3729d
diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.pyindex fcd2d84995..dfc37c7021 100644--- a/autogpt_platform/backend/backend/api/features/home/attention.py+++ b/autogpt_platform/backend/backend/api/features/home/attention.py@@ -2,16 +2,19 @@ import jsonfrom datetime import datetime, timedelta, timezonefrom urllib.parse import quote+from pydantic import ValidationError+from backend.api.features.experts.models import Expertfrom backend.api.features.experts.spend_approval import is_spend_reviewfrom backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.briefing.outcome import as_utc, run_linkfrom backend.copilot.constants import AUTOPILOT_NAME+from backend.copilot.gate.review import GATE_NODE_PREFIX, GateReviewPayloadfrom backend.copilot.model import ChatSessionInfo, PendingQuestionfrom backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfofrom .helpers import setup_count, to_home_expert-from .models import HomeAction, HomeAttentionItem, HomeExpert+from .models import HomeAction, HomeAttentionItem, HomeExpert, HomeHeadline# Longest payload preview we return before clipping it with an ellipsis._PREVIEW_MAX = 140@@ -44,6 +47,8 @@ def compose_attention_items(def _review_attention(review: PendingHumanReviewModel, now: datetime) -> HomeAttentionItem:+ if gate := _gate_payload(review):+ return _gate_attention(review, gate, now)title = (review.actionor review.instructions@@ -73,6 +78,67 @@ def _review_attention()+def _gate_attention(+ review: PendingHumanReviewModel, gate: GateReviewPayload, now: datetime+) -> HomeAttentionItem:+ """A held AutoPilot call: the card's own headline and reason, and its inputs+ as the preview, because Home answers it without opening the chat."""+ created_at = as_utc(review.created_at)+ return HomeAttentionItem(+ id=f"approval-{review.node_exec_id}",+ kind="approval",+ priority=("high" if now - created_at > timedelta(hours=24) else "normal"),+ title=gate.headline.text,+ headline=HomeHeadline(ask=gate.headline.ask, object=gate.headline.object),+ description=_gate_reason(gate),+ why_it_matters="Nothing runs until you approve it.",+ expert=_review_expert(review),+ created_at=created_at,+ preview=_clip(+ " · ".join(+ f"{field.label}: {_preview_value(gate.arguments[field.key])}"+ for field in gate.fields+ if field.key != gate.headline.object_key+ and gate.arguments.get(field.key) not in (None, "", [], {})+ )+ )+ or None,+ review=review,+ primary_action=HomeAction(label="Open chat", href=_review_link(review)),+ )+++def _gate_payload(review: PendingHumanReviewModel) -> GateReviewPayload | None:+ if not review.node_exec_id.startswith(GATE_NODE_PREFIX):+ return None+ try:+ return GateReviewPayload.model_validate(review.payload)+ except ValidationError:+ # A row written before the payload carried a headline.+ return None+++def _gate_reason(gate: GateReviewPayload) -> str:+ if gate.reason_kind == "supervisor" and gate.reason:+ return f"Not sure this is safe: {gate.reason}"+ if gate.reason_kind in ("subject", "rule", "content") and gate.reason:+ return gate.reason+ return f"{AUTOPILOT_NAME} is waiting for your approval."+++def _preview_value(value: object) -> str:+ """As the card shows it: a list of names joined, never a Python repr."""+ if isinstance(value, str):+ return value+ if isinstance(value, list) and all(+ isinstance(v, (str, int, float)) and not isinstance(v, bool) for v in value+ ):+ return ", ".join(str(v) for v in value)+ if isinstance(value, bool):+ return "Yes" if value else "No"+ return json.dumps(value, default=str, ensure_ascii=False)++def _waiting_on(review: PendingHumanReviewModel) -> str:if review.session_id:return AUTOPILOT_NAMEdiff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.pyindex db129f537e..3dab33cd2b 100644--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py@@ -1,9 +1,12 @@from datetime import datetime, timedelta, timezone+import pytestfrom prisma.enums import ReviewStatusfrom backend.api.features.experts.models import Expert, ExpertWorkflowReffrom backend.api.features.graph_executions.review.model import PendingHumanReviewModel+from backend.copilot.constants import AUTOPILOT_NAME+from backend.copilot.gate.review import node_id_for, review_payloadfrom backend.copilot.model import ChatSessionInfo, ChatSessionMetadata, PendingQuestionfrom backend.executor.scheduler import GraphExecutionJobInfo@@ -457,3 +460,88 @@ def test_a_workflow_review_without_a_name_still_says_workflow() -> None:)assert item.description == "A workflow is waiting for your approval."+++def _gate_review(**payload_overrides) -> PendingHumanReviewModel:+ payload = review_payload(+ "create_folder",+ {"name": "Q3 reports", "color": "blue"},+ reason="Ask First is on for this chat.",+ reason_kind="mode",+ )+ payload.update(payload_overrides)+ return _review(NOW - timedelta(hours=1), node_exec_id="rid").model_copy(+ update={+ "node_exec_id": f"{node_id_for('create_folder')}:abc",+ "graph_exec_id": "copilot-session-s1",+ "session_id": "s1",+ "payload": payload,+ "instructions": "Create folder “Q3 reports”",+ }+ )+++def _one(review: PendingHumanReviewModel):+ [item] = compose_attention_items(+ now=NOW, experts=[], reviews=[review], schedules=[], credits_balance=None+ )+ return item+++def test_a_held_call_reads_as_its_card_on_home() -> None:+ item = _one(_gate_review())++ assert item.title == "Create folder “Q3 reports”"+ assert item.headline is not None+ assert (item.headline.ask, item.headline.object) == ("Create folder", "Q3 reports")+ # The mode's own reason is the chat's, not this call's.+ assert item.description == f"{AUTOPILOT_NAME} is waiting for your approval."+ # The headline already names it.+ assert item.preview == "Color: blue"+ assert item.primary_action is not None+ assert item.primary_action.label == "Open chat"+ assert item.primary_action.href == "/copilot?sessionId=s1"+++ "kind, expected",+ [+ ("supervisor", "Not sure this is safe: it deletes data"),+ ("rule", "it deletes data"),+ ("mode", f"{AUTOPILOT_NAME} is waiting for your approval."),+ ],+)+def test_home_shows_a_reason_only_when_it_is_about_the_call(kind, expected) -> None:+ item = _one(_gate_review(reason="it deletes data", reason_kind=kind))+ assert item.description == expected+++def test_a_graph_row_keeps_its_workflow_copy() -> None:+ item = _one(_review(NOW - timedelta(hours=1)))++ assert item.title == "Send the prepared message"+ assert item.preview == '{"recipient": "[email protected]"}'+ assert item.primary_action is not None+ assert item.primary_action.label == "Review"+++def test_a_gate_row_from_before_the_headline_falls_back() -> None:+ review = _gate_review().model_copy(+ update={"payload": {"tool": "create_folder", "arguments": {}}}+ )+ item = _one(review)+ assert item.title == "Create folder “Q3 reports”"+ assert item.headline is None+ assert item.primary_action is not None+ assert item.primary_action.label == "Review"+++def test_home_previews_lists_and_flags_as_the_card_does() -> None:+ review = _gate_review(+ arguments={"to": ["[email protected]", "[email protected]"], "notify": True},+ fields=[+ {"key": "to", "label": "To"},+ {"key": "notify", "label": "Notify"},+ ],+ )+ assert _one(review).preview == "To: [email protected], [email protected] · Notify: Yes"diff --git a/autogpt_platform/backend/backend/api/features/home/models.py b/autogpt_platform/backend/backend/api/features/home/models.pyindex 927c734ff0..0a0519f85b 100644--- a/autogpt_platform/backend/backend/api/features/home/models.py+++ b/autogpt_platform/backend/backend/api/features/home/models.py@@ -19,11 +19,18 @@ class HomeAction(BaseModel):href: str+class HomeHeadline(BaseModel):+ ask: str+ object: str | None = None++class HomeAttentionItem(BaseModel):id: strkind: Literal["approval", "setup", "paused", "credits", "question"]priority: Literal["high", "normal"]title: str+ # A held call's action and its object, which the row sets like the card does.+ headline: HomeHeadline | None = Nonedescription: strwhy_it_matters: strexpert: HomeExpert | None = Nonediff --git a/autogpt_platform/backend/backend/copilot/gate/__init__.py b/autogpt_platform/backend/backend/copilot/gate/__init__.pyindex 449a6464c3..d1fff49c02 100644--- a/autogpt_platform/backend/backend/copilot/gate/__init__.py+++ b/autogpt_platform/backend/backend/copilot/gate/__init__.py@@ -120,13 +120,16 @@ async def check_action(mode = resolve_mode(session)verdict = verdict_for(mode, tool_name)+ reason_kind: review_store.ReasonKindif rule_reason := await chat_rules.ask_reason(session_id, tool_name):- reason = rule_reason+ reason, reason_kind = rule_reason, "rule"elif verdict is Verdict.RUN:return ALLOWelif verdict is Verdict.ASK:reason = _ASK_FIRST if mode == "ask_first" else _OUTWARD+ reason_kind = "mode"else:+ reason_kind = "supervisor"allowed, reason = await classify(tool_name=tool_name,args=args,@@ -137,17 +140,28 @@ async def check_action(call = held.HeldCall(review_id=review_id, tool_name=tool_name, tool_call_id=tool_call_id, args=args)- return await _park(call, user_id, session, reason)+ return await _park(call, user_id, session, reason, reason_kind)async def _park(- call: held.HeldCall, user_id: str, session: ChatSession, reason: str+ call: held.HeldCall,+ user_id: str,+ session: ChatSession,+ reason: str,+ reason_kind: review_store.ReasonKind,) -> Decision:"""Cards queue per chat: the call is kept so its answer can finish it."""if not await held.remember(session.session_id, call):return Decision(allowed=False, reason=_UNRECORDABLE)if not await review_store.open_review(- call.review_id, user_id, session, call.tool_name, call.args, reason+ call.review_id,+ user_id,+ session,+ call.tool_name,+ call.args,+ reason,+ reason_kind=reason_kind,+ tool_call_id=call.tool_call_id,):await held.forget(session.session_id, call.review_id)return Decision(allowed=False, reason=_UNRECORDABLE)diff --git a/autogpt_platform/backend/backend/copilot/gate/headline.py b/autogpt_platform/backend/backend/copilot/gate/headline.pynew file mode 100644index 0000000000..d5e2d52a41--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/gate/headline.py@@ -0,0 +1,83 @@+"""How a held call is named to the user: the one table the card, the chain row,+Home and the channels all read, so none of them can word it differently."""++from typing import Any++from pydantic import BaseModel++# Tool -> (the action, the arguments that name its object, first match wins).+# Every tool the gate can hold; built from our registry, never from the reason.+_ASK: dict[str, tuple[str, tuple[str, ...]]] = {+ "bash_exec": ("Run a command in the sandbox", ()),+ "browser_act": ("Act on the open page", ()),+ "post_to_chat_platform": ("Post a message", ()),+ "edit_chat_platform_message": ("Edit a posted message", ()),+ "create_agent": ("Create an agent", ()),+ "customize_agent": ("Customize an agent", ()),+ "edit_agent": ("Edit an agent", ()),+ "fix_agent_graph": ("Fix an agent", ()),+ "enter_agent_building_mode": ("Start building an agent", ()),+ "create_folder": ("Create folder", ("name",)),+ "update_folder": ("Update folder", ("name",)),+ "move_folder": ("Move a folder", ()),+ "delete_folder": ("Delete a folder", ()),+ "move_agents_to_folder": ("Move agents into a folder", ()),+ "update_preset": ("Update preset", ("name",)),+ "delete_preset": ("Delete a preset", ()),+ "schedule_followup": ("Schedule a follow-up", ("name",)),+ "schedule_routine": ("Schedule a routine", ("title",)),+ "pause_schedule": ("Pause a schedule", ()),+ "resume_schedule": ("Resume a schedule", ()),+ "delete_schedule": ("Delete a schedule", ()),+ "setup_agent_webhook_trigger": ("Set up the trigger", ("name",)),+ "create_feature_request": ("File a feature request", ("title",)),+ "hire_expert": ("Hire", ("name",)),+ "raise_expert": ("Create teammate", ("name",)),+ "update_expert": ("Update teammate", ("name",)),+ "update_expert_soul": ("Change how this teammate works", ()),+ "confirm_expert_change": ("Confirm the team change", ()),+ "confirm_expert_soul_update": ("Confirm the teammate change", ()),+ "install_expert_workflow": ("Give a teammate a workflow", ()),+ "remove_expert_workflow": ("Take a workflow from a teammate", ()),+ "grant_expert_credential": ("Give a teammate an account", ()),+ "revoke_expert_credential": ("Take an account from a teammate", ()),+ "delegate_to_expert": ("Hand a task to a teammate", ()),+ "handoff_to_expert": ("Hand this chat to a teammate", ()),+ "message_session": ("Message another chat", ()),+ "run_sub_session": ("Start a subtask", ()),+ "delete_skill": ("Delete skill", ("name",)),+ "delete_workspace_file": ("Delete file", ("path",)),+ "memory_forget_confirm": ("Forget memories", ()),+}+_MAX_OBJECT_CHARS = 60+++class Headline(BaseModel):+ ask: str+ object: str | None = None+ # The argument the object came from, which the card does not list again.+ object_key: str | None = None++ @property+ def text(self) -> str:+ return f"{self.ask} “{self.object}”" if self.object else self.ask+++def headline_for(tool_name: str, args: dict[str, Any]) -> Headline:+ ask, keys = _ASK.get(tool_name, (f"Run {tool_name.replace('_', ' ')}", ()))+ for key in keys:+ value = args.get(key)+ if isinstance(value, str) and value.strip():+ name = " ".join(value.split())+ if len(name) > _MAX_OBJECT_CHARS:+ name = name[: _MAX_OBJECT_CHARS - 1] + "…"+ # The card hides the argument only when the headline shows all of it.+ shown_whole = name == value+ return Headline(+ ask=ask, object=name, object_key=key if shown_whole else None+ )+ return Headline(ask=ask)+++def gated_tools() -> frozenset[str]:+ return frozenset(_ASK)diff --git a/autogpt_platform/backend/backend/copilot/gate/held.py b/autogpt_platform/backend/backend/copilot/gate/held.pyindex 047ffe9e61..4815d28850 100644--- a/autogpt_platform/backend/backend/copilot/gate/held.py+++ b/autogpt_platform/backend/backend/copilot/gate/held.py@@ -13,7 +13,7 @@ import jsonimport loggingimport uuidfrom datetime import UTC, datetime-from typing import TYPE_CHECKING, Any, Callable, Iterable+from typing import TYPE_CHECKING, Any, Callable, Iterable, Literalfrom prisma.enums import ReviewStatusfrom pydantic import BaseModel, Field, ValidationError@@ -44,6 +44,8 @@ _KEY = "copilot:gate:held:"# 100,000-character output cap plus the wrapper), so nothing is cut here._MAX_RESULT_CHARS = 120_000+Outcome = Literal["approved", "rejected", "expired", "closed", "unknown"]+WAKE_MESSAGE = "I answered an action that was waiting for my approval."_RESEND = ("Nothing ran: the approved action's details were lost before it could run. "@@ -239,14 +241,14 @@ async def _deliver() -> PendingMessage:from backend.copilot.tools import get_tool- output = await _outcome(user_id, session, call, get_tool(call.tool_name))+ outcome, output = await _outcome(user_id, session, call, get_tool(call.tool_name))try:- return _result_row(call, cap(output))+ return _result_row(call, cap(output), outcome)except Exception:# The outcome is known and may be a refusal; only the engine's cut# failed, so deliver it trimmed rather than let recovery guess.logger.warning(f"Could not cap held result {call.review_id}", exc_info=True)- return _result_row(call, output[: _MAX_RESULT_CHARS // 2])+ return _result_row(call, output[: _MAX_RESULT_CHARS // 2], outcome)async def _recover(@@ -268,11 +270,12 @@ async def _recover("The approved action may have run, but its result was lost before it ""reached you. Tell the user, and check the outcome before relying ""on it.",+ "unknown",)]-def _result_row(call: HeldCall, output: str) -> PendingMessage:+def _result_row(call: HeldCall, output: str, outcome: Outcome) -> PendingMessage:return HeldResult(content=(f'<held_call_result tool="{call.tool_name}" '@@ -284,6 +287,8 @@ def _result_row(call: HeldCall, output: str) -> PendingMessage:"review_id": call.review_id,"tool_name": call.tool_name,"tool_call_id": call.tool_call_id,+ # The chain row shows the answer without parsing the text.+ "outcome": outcome,}},)@@ -291,39 +296,39 @@ def _result_row(call: HeldCall, output: str) -> PendingMessage:async def _outcome(user_id: str, session: ChatSession, call: HeldCall, tool: "BaseTool | None"-) -> str:+) -> tuple[Outcome, str]:rows = await review_db().get_reviews_by_node_exec_ids([call.review_id], user_id)row = rows.get(call.review_id)if row is None or row.status == ReviewStatus.WAITING:- return "Nothing ran: this card is no longer open."+ return "closed", "Nothing ran: this card is no longer open."if row.status == ReviewStatus.REJECTED:await review_store.consume(call.review_id, user_id)await chat_rules.set_ask(session.session_id, call.tool_name)- return (+ return "rejected", ("Nothing ran: the user declined this action. Do not retry it or ""reach the same effect another way.")approved_at = row.reviewed_at or row.updated_at or row.created_atif datetime.now(UTC) - approved_at > review_store.APPROVAL_TTL:await review_store.consume(call.review_id, user_id)- return (+ return "expired", ("Nothing ran: the approval expired an hour after it was given. ""Propose the call again if it is still needed.")if call.lost:await review_store.consume(call.review_id, user_id)- return _RESEND+ return "closed", _RESENDif tool is None:await review_store.consume(call.review_id, user_id)- return "Nothing ran: this tool no longer exists."+ return "closed", "Nothing ran: this tool no longer exists."# The gate finds the approval for exactly these arguments and spends it.result = await tool.execute(user_id, session, call.tool_call_id, **call.args)# With the flag switched off since, the gate ran it without spending the# approval; spend it here so no later identical call rides on it.await review_store.consume(call.review_id, user_id)if isinstance(result.output, str):- return result.output- return json.dumps(result.output, default=str)+ return "approved", result.output+ return "approved", json.dumps(result.output, default=str)async def _restore(@@ -359,7 +364,8 @@ def _from_row(return HeldCall(review_id=row.node_exec_id,tool_name=tool_name,- tool_call_id="",+ # The card keeps the call's id, so the late result still finds its row.+ tool_call_id=str(payload.get("tool_call_id") or ""),args=args if intact else {},held_at=row.created_at,lost=not intact,diff --git a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py b/autogpt_platform/backend/backend/copilot/gate/held_db_test.pyindex 90890cd221..a37c26f21c 100644--- a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/held_db_test.py@@ -170,6 +170,7 @@ async def test_an_approval_runs_the_call_with_its_stored_arguments(assert len(delivered) == 1assert "posted hello team" in delivered[0].contentassert 'tool_call_id="call-1"' in delivered[0].content+ assert delivered[0].metadata["held_call"]["outcome"] == "approved"assert await _row(review_id, test_user_id) is None@@ -230,6 +231,8 @@ async def test_an_approval_whose_held_call_was_lost_runs_from_the_card(assert post_tool.runs == [{"text": "from the card"}]assert "posted from the card" in delivered.content+ # The card kept the call's id, so the chain row still finds its result.+ assert delivered.metadata["held_call"]["tool_call_id"] == "call-1"assert await _row(review_id, test_user_id) is None@@ -246,6 +249,7 @@ async def test_a_lost_held_call_the_card_cannot_rebuild_asks_for_a_resend(assert post_tool.runs == []assert "send the request again" in delivered.content+ assert delivered.metadata["held_call"]["outcome"] == "closed"assert await _row(review_id, test_user_id) is None@@ -331,6 +335,7 @@ async def test_a_failure_after_the_approval_was_spent_says_it_may_have_run([delivered] = await held.resolve_answered(test_user_id, session)assert "may have run" in delivered.content+ assert delivered.metadata["held_call"]["outcome"] == "unknown"assert await held.answered(test_user_id, session.session_id) == []@@ -388,6 +393,7 @@ async def test_a_stale_approval_delivers_a_refusal_not_a_run(assert post_tool.runs == []assert "expired" in delivered[0].content+ assert delivered[0].metadata["held_call"]["outcome"] == "expired"assert await _row(review_id, test_user_id) is None@@ -407,6 +413,7 @@ async def test_a_rejection_never_runs_and_the_tool_asks_from_then_on(assert post_tool.runs == []assert "declined" in delivered[0].content+ assert delivered[0].metadata["held_call"]["outcome"] == "rejected"assert await chat_rules.ask_reason(session.session_id, _TOOL) == chat_rules.DECLINED@@ -442,3 +449,20 @@ async def test_an_answer_on_an_idle_chat_starts_its_turn(dispatch.assert_awaited_once()assert dispatch.await_args.kwargs["message"] == held.WAKE_MESSAGE++[email protected](loop_scope="session")+async def test_the_chain_row_and_the_card_name_the_call_alike(+ setup_test_user, test_user_id, gate_on, post_tool+):+ """The tool output labels the chain row; the row's payload heads the card."""+ session = await _new_session(test_user_id, "ask_first")++ result = await post_tool.execute(test_user_id, session, "call-9", text="hi")++ output = json.loads(result.output)+ row = await _row(output["review_id"], test_user_id)+ assert row is not None+ assert output["type"] == "approval_required"+ assert (output["ask"], output["object"]) == ("Post a message", None)+ assert row.payload["headline"]["ask"] == output["ask"]diff --git a/autogpt_platform/backend/backend/copilot/gate/policy.py b/autogpt_platform/backend/backend/copilot/gate/policy.pyindex 58ddcd200e..6ed6057390 100644--- a/autogpt_platform/backend/backend/copilot/gate/policy.py+++ b/autogpt_platform/backend/backend/copilot/gate/policy.py@@ -5,6 +5,7 @@ decision here must hold even if it always answered "allow"."""from enum import Enum+from typing import Anyfrom backend.copilot.model import AutopilotMode@@ -175,6 +176,18 @@ _MODE_VERDICTS: dict[AutopilotMode, dict[Effect, Verdict]] = {}+# Deletes that destroy data no restore path brings back. A folder delete is not+# one: its agents move to the root and its rows are only flagged deleted.+_IRREVERSIBLE = frozenset({"delete_schedule", "delete_skill", "delete_workspace_file"})+++def is_irreversible(tool_name: str, args: dict[str, Any]) -> bool:+ if tool_name == "memory_forget_confirm":+ # The default retracts the memory; only a hard delete destroys it.+ return args.get("hard_delete") is True+ return tool_name in _IRREVERSIBLE++def effect_for(tool_name: str) -> Effect:# A tool nobody classified is a platform edit: judged in Auto, asked in Ask First.return _EFFECTS.get(tool_name, Effect.PLATFORM)diff --git a/autogpt_platform/backend/backend/copilot/gate/review.py b/autogpt_platform/backend/backend/copilot/gate/review.pyindex acc5e57f6b..8e3d9c94f5 100644--- a/autogpt_platform/backend/backend/copilot/gate/review.py+++ b/autogpt_platform/backend/backend/copilot/gate/review.py@@ -3,17 +3,18 @@``run_block`` already parks sensitive block executions in ``PendingHumanReview``under a ``copilot-session-<id>`` key, and the chat renders every such row via``extractGraphExecId`` -> ``CopilotPendingReviews``. Writing the same shape for-a tool call inherits the card, the Home "Needs You" row, the awaiting-review-alert, and the approve/reject endpoint without new UI.+a tool call inherits the Home "Needs You" row, the awaiting-review alert and+the approve/reject endpoint; the payload carries what the approval card reads."""import hashlibimport jsonimport loggingfrom datetime import UTC, datetime, timedelta-from typing import Any+from typing import Any, Literalfrom prisma.enums import ReviewStatus+from pydantic import BaseModelfrom backend.copilot.constants import (COPILOT_NODE_EXEC_ID_SEPARATOR,@@ -26,19 +27,58 @@ from backend.copilot.model import ChatSessionfrom backend.copilot.sharing.models import _redact_secret_keysfrom backend.data.db_accessors import review_db+from .headline import Headline, headline_for+from .policy import DEFAULT_MODE, effect_for, is_irreversible+logger = logging.getLogger(__name__)# Keep the stored payload small: @@agptfile: references are expanded before the# tool handler runs, so an argument can arrive holding a whole file._MAX_ARG_CHARS = 4_000+GATE_NODE_PREFIX = f"{COPILOT_NODE_PREFIX}gate-"++ReasonKind = Literal["mode", "subject", "supervisor", "rule", "spend", "content"]+++class Subject(BaseModel):+ kind: str = "tool"+ key: str+ name: str+ effect: str+ irreversible: bool = False+++class FieldLabel(BaseModel):+ key: str+ label: str+++class GateReviewPayload(BaseModel):+ """What the approval card, Home and the channels render: never the raw call."""++ tool: str+ arguments: dict[str, Any]+ clipped: list[str] = []+ fields: list[FieldLabel] = []+ tool_call_id: str = ""+ turn: int = 0+ mode: str | None = None+ subject: Subject+ reason: str = ""+ reason_kind: ReasonKind = "mode"+ # The gate records no chat-scoped rule yet, so none is offered.+ chat_rules_allowed: list[Literal["allow", "judge"]] = []+ headline: Headline++# An approval must not run a call long after the user gave it; the answered# card's turn normally runs it within seconds.APPROVAL_TTL = timedelta(hours=1)def node_id_for(tool_name: str) -> str:- return f"{COPILOT_NODE_PREFIX}gate-{tool_name}"+ return f"{GATE_NODE_PREFIX}{tool_name}"def review_id_for(@@ -59,31 +99,39 @@ def review_id_for(return f"{node_id_for(tool_name)}{COPILOT_NODE_EXEC_ID_SEPARATOR}{digest}"-def review_payload(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:- """Nest the arguments one level down, and redact secret-shaped keys."""+def review_payload(+ tool_name: str,+ args: dict[str, Any],+ *,+ reason: str = "",+ reason_kind: ReasonKind = "mode",+ mode: str | None = None,+ tool_call_id: str = "",+ turn: int = 0,+) -> dict[str, Any]:redacted = _redact_secret_keys(args)# Per value, never the whole blob: a long first argument must not push# the one that matters off the card while the approval still binds it.per_value = max(200, _MAX_ARG_CHARS // max(1, len(redacted)))shown = {key: _clip(value, per_value) for key, value in redacted.items()}- return {"tool": tool_name, "arguments": shown}---def instructions_for(tool_name: str, reason: str) -> str:- """Compose the card headline ourselves rather than trusting the reason.-- ``PendingReviewsList`` uses ``instructions`` AS the headline, so a model- that controls the reason controls the framing the approver reads; leading- with a name from our own registry keeps the identity trustworthy.-- ``PendingReviewCard`` discards any instructions containing "Block" — a- hard-coded discriminator for HITL block reviews — so a capital B is- lower-cased rather than stripped, which would mangle the sentence.- """- cleaned = " ".join(reason.split())[:200].strip(" :—-") or "needs your approval"- label = tool_name.replace("_", " ")- label = label[:1].upper() + label[1:]- return f"{label} — {cleaned}".replace("Block", "block")+ return GateReviewPayload(+ tool=tool_name,+ arguments=shown,+ clipped=[key for key in shown if shown[key] is not redacted[key]],+ fields=_field_labels(tool_name, shown),+ tool_call_id=tool_call_id,+ turn=turn,+ mode=mode,+ subject=Subject(+ key=tool_name,+ name=_label(tool_name),+ effect=effect_for(tool_name).value,+ irreversible=is_irreversible(tool_name, args),+ ),+ reason=" ".join(reason.split())[:300],+ reason_kind=reason_kind,+ headline=headline_for(tool_name, args),+ ).model_dump()async def find_decision(@@ -137,15 +185,26 @@ async def open_review(tool_name: str,args: dict[str, Any],reason: str,+ reason_kind: ReasonKind = "mode",+ tool_call_id: str = "",) -> bool:"""Park the call for approval. False means nothing was recorded."""try:+ payload = review_payload(+ tool_name,+ args,+ reason=reason,+ reason_kind=reason_kind,+ mode=session.metadata.autopilot_mode or DEFAULT_MODE,+ tool_call_id=tool_call_id,+ turn=sum(1 for m in session.messages if m.role == "user"),+ )await review_db().get_or_create_human_review(user_id=user_id,node_exec_id=review_id,chat_session_id=session.session_id,- input_data=review_payload(tool_name, args),- message=instructions_for(tool_name, reason),+ input_data=payload,+ message=headline_for(tool_name, args).text,editable=False,organization_id=session.organization_id,team_id=session.team_id,@@ -160,6 +219,33 @@ async def open_review(return False+def _label(tool_name: str) -> str:+ label = tool_name.replace("_", " ")+ return label[:1].upper() + label[1:]+++def _field_labels(tool_name: str, shown: dict[str, Any]) -> list[FieldLabel]:+ """Labels and order from the tool's own input schema, required first."""+ from backend.copilot.tools import get_tool # imports the gate++ tool = get_tool(tool_name)+ schema = tool.parameters if tool else {}+ props = schema.get("properties") or {}+ required = [k for k in schema.get("required") or [] if k in props]+ order = required + [k for k in props if k not in required]+ order += [k for k in shown if k not in order]+ return [+ FieldLabel(key=key, label=(props.get(key) or {}).get("title") or _humanize(key))+ for key in order+ if key in shown+ ]+++def _humanize(key: str) -> str:+ words = key.removesuffix("_id").replace("_", " ").strip()+ return words[:1].upper() + words[1:]++def _clip(value: Any, limit: int) -> Any:text = json.dumps(value, default=str)return value if len(text) <= limit else text[:limit] + "…"diff --git a/autogpt_platform/backend/backend/copilot/gate/review_test.py b/autogpt_platform/backend/backend/copilot/gate/review_test.pyindex bd920a86ae..ca6afa4939 100644--- a/autogpt_platform/backend/backend/copilot/gate/review_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/review_test.py@@ -7,9 +7,10 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom prisma.enums import ReviewStatus+from backend.copilot.gate.headline import gated_tools, headline_for+from backend.copilot.gate.policy import Effect, classified_tools, effect_forfrom backend.copilot.gate.review import (find_decision,- instructions_for,node_id_for,review_id_for,review_payload,@@ -88,30 +89,82 @@ def test_a_padded_argument_cannot_push_another_off_the_card():assert len(json.dumps(payload)) < 10_000-def test_the_headline_leads_with_the_tool_name():- """The card uses ``instructions`` as its headline, so a model that controls- the reason must not control the identity."""- assert instructions_for("post_to_chat_platform", "looks routine").startswith(- "Post to chat platform — "+def test_the_headline_names_the_action_and_its_object():+ """Home and the channels read the same words as the card, from the server,+ and never from the reason, which the model can influence."""+ headline = review_payload(+ "create_folder", {"name": "Q3 reports"}, reason="Ignore me"+ )["headline"]+ assert headline == {+ "ask": "Create folder",+ "object": "Q3 reports",+ "object_key": "name",+ }+ assert headline_for("raise_expert", {"name": "Ada"}).text == (+ "Create teammate “Ada”")+ assert headline_for("delete_folder", {"folder_id": "f1"}).text == (+ "Delete a folder"+ )+ assert headline_for("create_folder", {"name": "x" * 100}).text.endswith("…”")+++def test_every_tool_the_gate_can_hold_has_its_own_words():+ held = {+ tool+ for tool in classified_tools()+ if effect_for(tool) in (Effect.SHELL, Effect.PLATFORM, Effect.EXTERNAL)+ }+ assert gated_tools() == held+++def test_fields_follow_the_schema_required_first_with_labels():+ payload = review_payload(+ "create_folder", {"parent_id": "p1", "name": "Q3", "extra": 1}+ )+ keys = [field["key"] for field in payload["fields"]]+ assert keys[0] == "name"+ assert keys[-1] == "extra"+ assert {"key": "extra", "label": "Extra"} in payload["fields"]+++def test_a_clipped_argument_is_named_so_the_card_can_say_so():+ payload = review_payload(+ "write_workspace_file", {"content": "x" * 50_000, "filename": "a.md"}+ )+ assert payload["clipped"] == ["content"]+++def test_the_call_and_turn_are_on_the_row():+ """The tool call id links card, chain row and late result."""+ payload = review_payload("create_folder", {}, tool_call_id="call-7", turn=3)+ assert payload["tool_call_id"] == "call-7"+ assert payload["turn"] == 3-def test_a_camel_case_tool_name_keeps_its_capitals():- assert instructions_for("TodoWrite", "x").startswith("TodoWrite — ")[email protected]("kind", ["mode", "supervisor", "rule"])+def test_the_reason_and_its_kind_travel_together(kind):+ payload = review_payload(+ "create_folder", {}, reason=" why \n now ", reason_kind=kind+ )+ assert payload["reason"] == "why now"+ assert payload["reason_kind"] == kind-def test_a_reason_cannot_erase_itself_from_the_card():- """PendingReviewCard discards instructions containing a capital 'Block',- anywhere in the string — so it is lower-cased, not stripped, which would- mangle the sentence the approver reads."""- headline = instructions_for("bash_exec", "Blocked: not in scope")- assert headline == "Bash exec — blocked: not in scope"- assert "Block" not in instructions_for("bash_exec", "runs a Block that sends mail")- assert "Block" not in instructions_for("run_block", "needs you")+def test_the_subject_is_the_tool_until_l5a_names_one():+ payload = review_payload("post_to_chat_platform", {}, mode="auto")+ assert payload["subject"] == {+ "kind": "tool",+ "key": "post_to_chat_platform",+ "name": "Post to chat platform",+ "effect": "external",+ "irreversible": False,+ }+ assert payload["mode"] == "auto"-def test_an_empty_reason_still_produces_a_headline():- assert instructions_for("bash_exec", " ") == "Bash exec — needs your approval"+def test_no_rule_is_offered_before_the_gate_records_one():+ assert review_payload("create_folder", {})["chat_rules_allowed"] == []@pytest.mark.parametrize(@@ -138,3 +191,39 @@ async def test_an_approval_nobody_came_back_for_expires(status, age, expected):with patch("backend.copilot.gate.review.review_db", return_value=db):assert await find_decision("rid", "u1", "s1") == expectedassert db.delete_review_by_node_exec_id.await_count == (expected is None)+++ "path", ["a" * 100 + ".md", "two spaces.md", "line\nbreak.md"]+)+def test_an_argument_the_headline_shortens_stays_on_the_card(path):+ """The approval binds the whole value, so a headline that cannot show all+ of it must not hide the field that does."""+ headline = headline_for("delete_workspace_file", {"path": path})+ assert headline.object is not None+ assert headline.object_key is None+ assert headline_for("delete_workspace_file", {"path": "q3.md"}).object_key == (+ "path"+ )+++ "tool, args, irreversible",+ [+ ("delete_workspace_file", {"path": "q3.md"}, True),+ ("delete_skill", {"name": "invoice-chaser"}, True),+ ("delete_schedule", {"schedule_id": "s1"}, True),+ ("memory_forget_confirm", {"uuids": ["e1"], "hard_delete": True}, True),+ # Retracted, not destroyed.+ ("memory_forget_confirm", {"uuids": ["e1"]}, False),+ # Its agents move to the root; the folder rows are only flagged.+ ("delete_folder", {"folder_id": "f1"}, False),+ ("delete_preset", {"preset_id": "p1"}, False),+ ("revoke_expert_credential", {"expert_id": "e", "credential_id": "c"}, False),+ ("create_folder", {"name": "Q3"}, False),+ ],+)+def test_only_a_delete_that_destroys_data_is_marked_irreversible(+ tool, args, irreversible+):+ assert review_payload(tool, args)["subject"]["irreversible"] is irreversiblediff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.pyindex 3c6ffc5cd7..aa98eac5ed 100644--- a/autogpt_platform/backend/backend/copilot/tools/base.py+++ b/autogpt_platform/backend/backend/copilot/tools/base.py@@ -512,12 +512,17 @@ class BaseTool:session,"This action could not be checked against your approval ""settings, so nothing ran. Tell the user and stop.",+ args=kwargs,)if decision.allowed:return Nonereturn self._refusal(- tool_call_id, session, decision.reason, review_id=decision.review_id+ tool_call_id,+ session,+ decision.reason,+ review_id=decision.review_id,+ args=kwargs,)def _refusal(@@ -526,9 +531,12 @@ class BaseTool:session: ChatSession,reason: str,review_id: str | None = None,+ args: dict[str, Any] | None = None,) -> StreamToolOutputAvailable:from backend.copilot.gate import refusal_message+ from backend.copilot.gate.headline import headline_for+ headline = headline_for(self.name, args or {})return StreamToolOutputAvailable(toolCallId=tool_call_id,toolName=self.name,@@ -538,6 +546,8 @@ class BaseTool:tool_name=self.name,reason=reason,review_id=review_id,+ ask=headline.ask,+ object=headline.object,).model_dump_json(),success=False,)diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 6475f5e369..a6d8112f3a 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -1032,6 +1032,9 @@ class ApprovalRequiredResponse(ToolResponseBase):tool_name: strreason: strreview_id: str | None = None+ # The chain row's label, from the same table as the card's headline.+ ask: str | None = None+ object: str | None = Noneclass WebFetchResponse(ToolResponseBase):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.tsxnew file mode 100644index 0000000000..47c69aeed0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx@@ -0,0 +1,205 @@+import type { Meta, StoryObj } from "@storybook/nextjs";+import { delay, http, HttpResponse } from "msw";+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import type { MessagePart } from "../ChatMessagesContainer/helpers";+import type { HeldOutcome } from "../ChatMessagesContainer/heldCallRows";+import { ChainRowView } from "../ToolChain/ChainRowView";+import { applyHeldOutcome } from "../ToolChain/heldRow";+import { toChainRow } from "../ToolChain/helpers";+import { AttentionRow } from "../../../home/components/NeedsYou/components/AttentionRow";+import { ApprovalQueue } from "./ApprovalQueue";+import { toApprovalItem } from "./helpers";+import {+ deleteFolder,+ folder,+ heldReview,+ mail,+ shell,+} from "./__tests__/fixtures";++function answerAfter(ms: number, status = 200) {+ return http.post("*/api/review/action", async () => {+ await delay(ms);+ return status === 200+ ? HttpResponse.json({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ })+ : HttpResponse.json({ detail: "unavailable" }, { status });+ });+}++function queueOf(reviews: PendingHumanReviewModel[]) {+ return { items: reviews.map(toApprovalItem), onAnswered: () => undefined };+}++const meta: Meta<typeof ApprovalQueue> = {+ title: "Copilot/ApprovalQueue",+ component: ApprovalQueue,+ decorators: [+ (Story) => (+ <TooltipProvider>+ <div className="mx-auto w-full max-w-[42rem]">+ <Story />+ </div>+ </TooltipProvider>+ ),+ ],+ parameters: { msw: { handlers: [answerAfter(600_000)] } },+};++export default meta;+type Story = StoryObj<typeof ApprovalQueue>;++export const OneCard: Story = { args: queueOf([folder("a", "Q3 reports")]) };++export const TwoOnTheSameSubject: Story = {+ args: queueOf([folder("a", "Q3 reports", 6), folder("b", "Invoices", 5)]),+};++export const IrreversibleWithInputs: Story = { args: queueOf([mail()]) };++export const SupervisorCouldNotVouch: Story = { args: queueOf([shell()]) };++export const IdentifiedOnlyById: Story = {+ args: queueOf([deleteFolder("f1", "f-111"), deleteFolder("f2", "f-222")]),+};++export const FiveWaiting: Story = {+ args: queueOf([+ heldReview({+ id: "d",+ tool: "delete_skill",+ args: { name: "Old drafts" },+ fields: [{ key: "name", label: "Name" }],+ headline: {+ ask: "Delete skill",+ object: "Old drafts",+ object_key: "name",+ },+ mode: "auto",+ reason:+ "This action reaches outside the platform, so it needs your approval.",+ minutesAgo: 9,+ }),+ mail("m", []),+ shell(),+ folder("f", "Receipts"),+ deleteFolder("x", "f-333"),+ ]),+};++export const SendFailed: Story = {+ args: queueOf([folder("a", "Q3 reports")]),+ parameters: { msw: { handlers: [answerAfter(300, 503)] } },+};++export const Narrow: Story = {+ args: queueOf([mail(), folder("b", "Invoices")]),+ parameters: { viewport: { defaultViewport: "mobile1" } },+};++const HELD_PART = (id: string, name: string): MessagePart =>+ ({+ type: "tool-create_folder",+ state: "output-available",+ toolCallId: `call-${id}`,+ input: { name },+ output: {+ type: "approval_required",+ tool_name: "create_folder",+ review_id: `copilot-node-gate-create_folder:${id}`,+ ask: "Create folder",+ object: name,+ },+ }) as MessagePart;++const OUTCOMES = new Map<string, HeldOutcome>([+ ["call-b", { outcome: "approved", output: { message: "Created" } }],+ ["call-c", { outcome: "rejected", output: "" }],+ ["call-d", { outcome: "expired", output: "" }],+]);++export const ChainRows: StoryObj = {+ render: () => {+ const parts = [+ HELD_PART("a", "Receipts"),+ HELD_PART("b", "Q3 reports"),+ HELD_PART("c", "Invoices"),+ HELD_PART("d", "Old drafts"),+ {+ ...HELD_PART("e", "Archive"),+ output: {+ type: "approval_required",+ tool_name: "create_folder",+ review_id: null,+ ask: "Create folder",+ },+ } as MessagePart,+ ];+ const rows = parts.map((part, i) =>+ applyHeldOutcome(toChainRow(part, i)!, OUTCOMES),+ );+ return (+ <div className="flex flex-col">+ {rows.map((row, i) => (+ <ChainRowView+ key={row.key}+ row={row}+ isLast={i === rows.length - 1}+ />+ ))}+ </div>+ );+ },+};++function homeRow(+ title: string,+ description: string,+ action: string,+ headline?: { ask: string; object: string },+) {+ const review = folder("a", "Q3 reports");+ return (+ <div className="rounded-xl border border-zinc-200 bg-white">+ <AttentionRow+ item={{+ id: "approval-a",+ kind: "approval",+ priority: "normal",+ title,+ headline,+ description,+ why_it_matters: "Nothing runs until you approve it.",+ review,+ primary_action: { label: action, href: "/copilot?sessionId=s1" },+ }}+ isProcessing={false}+ onDecision={() => undefined}+ />+ </div>+ );+}++// What compose_attention_items returned for a gate row before and after this layer.+export const HomeRowBefore: StoryObj = {+ render: () =>+ homeRow(+ "Create folder — Ask First is on for this chat, so this action needs your approval.",+ "Otto is waiting for your approval.",+ "Review",+ ),+};++export const HomeRowAfter: StoryObj = {+ render: () =>+ homeRow(+ "Create folder “Q3 reports”",+ "Otto is waiting for your approval.",+ "Open chat",+ { ask: "Create folder", object: "Q3 reports" },+ ),+};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.tsxnew file mode 100644index 0000000000..1d03c4a63e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.tsx@@ -0,0 +1,110 @@+"use client";++import { ApprovalCard } from "./components/ApprovalCard/ApprovalCard";+import { CompactApprovalLine } from "./components/CompactApprovalLine";+import { QueueHeader } from "./components/QueueHeader";+import { ReceiptLine } from "./components/ReceiptLine";+import { RejectAllFooter } from "./components/RejectAllFooter";+import {+ type ApprovalItem,+ approvalCardId,+ canApproveAll,+ isBare,+ modeLine,+} from "./helpers";+import { useApprovalQueue } from "./useApprovalQueue";++interface Props {+ // Oldest first, as the gate raised them.+ items: ApprovalItem[];+ onAnswered: () => void;+}++// From this many cards up, each collapses to one line.+export const COMPACT_FROM = 4;++export function ApprovalQueue({ items, onAnswered }: Props) {+ const queue = useApprovalQueue({ items, onAnswered });+ const { pending, receipts } = queue;+ if (pending.length === 0 && receipts.length === 0) return null;++ const compact = pending.length >= COMPACT_FROM;+ const mode = pending.find((item) => item.mode)?.mode ?? null;+ const showModeLine = pending.some((item) => item.reasonKind === "mode");+ const approvable = canApproveAll(pending, compact) ? pending : null;+ const anyBusy = pending.some(+ (item) => queue.statusOf(item.reviewId) !== "idle",+ );++ return (+ <section+ aria-label="Waiting for you"+ className="overflow-hidden rounded-xl border border-zinc-200 bg-white"+ >+ <QueueHeader+ count={pending.length}+ mode={mode}+ approveAll={+ approvable+ ? {+ count: approvable.length,+ busy: anyBusy,+ onClick: () => queue.answer(approvable, true),+ }+ : null+ }+ />+ {showModeLine && pending.length > 0 && (+ <p className="border-b border-zinc-100 px-4 py-2 text-sm text-zinc-500">+ {modeLine(mode)}+ </p>+ )}+ <ol className="divide-y divide-zinc-100">+ {pending.map((item) => (+ <li+ key={item.reviewId}+ id={approvalCardId(item.reviewId)}+ tabIndex={-1}+ className="scroll-mb-24 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-zinc-300"+ >+ {compact &&+ queue.openId !== item.reviewId &&+ !queue.hasFailed(item.reviewId) ? (+ <CompactApprovalLine+ item={item}+ bare={isBare(item)}+ status={queue.statusOf(item.reviewId)}+ onOpen={() => queue.setOpenId(item.reviewId)}+ onApprove={() => queue.answer([item], true)}+ onReject={() => queue.answer([item], false)}+ />+ ) : (+ <ApprovalCard+ item={item}+ status={queue.statusOf(item.reviewId)}+ failed={queue.hasFailed(item.reviewId)}+ onApprove={(rule) => queue.answer([item], true, rule)}+ onReject={() => queue.answer([item], false)}+ />+ )}+ </li>+ ))}+ </ol>+ <ul aria-live="polite" className="divide-y divide-zinc-100">+ {receipts.map((receipt) => (+ <ReceiptLine key={receipt.item.reviewId} receipt={receipt} />+ ))}+ </ul>+ {pending.length >= 2 && (+ <RejectAllFooter+ count={pending.length}+ confirming={queue.confirmRejectAll}+ busy={anyBusy}+ onAsk={() => queue.setConfirmRejectAll(true)}+ onCancel={() => queue.setConfirmRejectAll(false)}+ onConfirm={() => queue.answer(pending, false)}+ />+ )}+ </section>+ );+}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.tsxnew file mode 100644index 0000000000..b9c9a6da61--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx@@ -0,0 +1,278 @@+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { expect, test, vi } from "vitest";+import { getPostV2ProcessReviewActionMockHandler200 } from "@/app/api/__generated__/endpoints/executions/executions.msw";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { server } from "@/mocks/mock-server";+import {+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { CopilotPendingReviews } from "../../CopilotPendingReviews/CopilotPendingReviews";+import {+ deleteFolder,+ folder,+ heldReview,+ mail,+ CHAT_SESSION,+ shell,+} from "./fixtures";++function serve(reviews: PendingHumanReviewModel[], status = 200) {+ server.use(+ http.get(`*/api/review/session/${CHAT_SESSION}`, () =>+ HttpResponse.json(reviews),+ ),+ status === 200+ ? getPostV2ProcessReviewActionMockHandler200({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ })+ : http.post("*/api/review/action", () =>+ HttpResponse.json({ detail: "boom" }, { status }),+ ),+ );+}++function renderQueue() {+ return render(+ <CopilotChatActionsProvider onSend={vi.fn()} onBackendTurn={vi.fn()}>+ <CopilotPendingReviews chatSessionId={CHAT_SESSION} />+ </CopilotChatActionsProvider>,+ );+}++async function queue() {+ return screen.findByRole("region", { name: "Waiting for you" });+}++test("the headline names the action and its argument is not repeated below", async () => {+ serve([+ heldReview({+ id: "a",+ tool: "create_folder",+ args: { name: "Q3 reports", color: "blue" },+ fields: [+ { key: "name", label: "Name" },+ { key: "color", label: "Color" },+ ],+ headline: {+ ask: "Create folder",+ object: "Q3 reports",+ object_key: "name",+ },+ }),+ ]);+ renderQueue();++ const heading = await screen.findByRole("heading", {+ name: "Create folder Q3 reports",+ });+ expect(heading).toBeDefined();+ expect(screen.getByText("Color")).toBeDefined();+ expect(screen.queryByText("Name")).toBeNull();+ expect(screen.getAllByText("Q3 reports")).toHaveLength(1);+});++test("a secret renders hidden, never its value", async () => {+ serve([mail()]);+ renderQueue();++ await queue();+ expect(screen.getByText("Api key")).toBeDefined();+ expect(screen.getByText("hidden")).toBeDefined();+ expect(screen.queryByText("[redacted]")).toBeNull();+});++test("the mode's reason is said once, in the header, and on no card", async () => {+ serve([folder("a", "Q3 reports"), folder("b", "Invoices")]);+ renderQueue();++ await queue();+ expect(+ screen.getAllByText(+ /Ask First is on, so Otto asks before he changes anything outside his workspace/,+ ),+ ).toHaveLength(1);+ expect(screen.queryByText(/so this action needs your approval/)).toBeNull();+});++test("approve-all is offered for two cards on the same subject", async () => {+ serve([folder("a", "Q3 reports"), folder("b", "Invoices")]);+ renderQueue();++ expect(+ await screen.findByRole("button", { name: "Approve both" }),+ ).toBeDefined();+});++test.each([+ ["a mixed pair", () => [folder("a", "Q3 reports"), shell()]],+ ["an irreversible pair", () => [mail("m1", []), mail("m2", [])]],+])("approve-all is not offered for %s", async (_name, reviews) => {+ serve(reviews());+ renderQueue();++ await queue();+ expect(+ screen.queryByRole("button", { name: /Approve (both|all)/ }),+ ).toBeNull();+});++test("from four cards up, a line with fields offers Review, not Approve", async () => {+ serve([+ folder("a", "One", 9),+ folder("b", "Two", 8),+ folder("c", "Three", 7),+ shell(),+ ]);+ renderQueue();++ await queue();+ const lines = screen.getAllByRole("listitem");+ const shellLine = lines.find((li) => within(li).queryByText(/sandbox/));+ expect(shellLine).toBeDefined();+ expect(+ within(shellLine!).getByRole("button", { name: "Review" }),+ ).toBeDefined();+ expect(+ within(shellLine!).queryByRole("button", { name: "Approve" }),+ ).toBeNull();+ expect(screen.getAllByRole("button", { name: "Approve" })).toHaveLength(3);+});++test("the approve menu is absent when the server offers no chat rule", async () => {+ serve([mail("m1", [])]);+ renderQueue();++ await queue();+ expect(screen.getByRole("button", { name: "Approve" })).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "More ways to approve" }),+ ).toBeNull();+});++test("the approve menu offers the rules the server allows", async () => {+ serve([mail("m1", ["allow"])]);+ renderQueue();++ 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(screen.queryByText(/Always allow/)).toBeNull();+});++test("a failed send says so on the card and lets you try again", async () => {+ serve([folder("a", "Q3 reports")], 500);+ renderQueue();++ await userEvent.click(await screen.findByRole("button", { name: "Approve" }));++ expect((await screen.findByRole("alert")).textContent).toContain(+ "Couldn't send your answer. Nothing ran. Try again.",+ );+ await waitFor(() =>+ expect(+ (screen.getByRole("button", { name: "Approve" }) as HTMLButtonElement)+ .disabled,+ ).toBe(false),+ );+});++test.each([+ ["supervisor", "Not sure this is safe: it uploads a file."],+ ["rule", "it uploads a file."],+])("a %s reason about this call shows on its card", async (kind, line) => {+ serve([+ heldReview({+ id: "r",+ tool: "bash_exec",+ args: { command: "ls" },+ reason: "it uploads a file.",+ reasonKind: kind,+ headline: { ask: "Run a command in the sandbox" },+ }),+ ]);+ renderQueue();++ expect(await screen.findByText(line)).toBeDefined();+});++test("a call told apart only by its id shows the id and is not approved as a set", async () => {+ serve([deleteFolder("a", "f-111"), deleteFolder("b", "f-222")]);+ renderQueue();++ expect(await screen.findByText("f-111")).toBeDefined();+ expect(screen.getByText("f-222")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Approve both" })).toBeNull();+});++test("a failed answer from a compact line opens its card with the error", async () => {+ serve(+ [+ folder("a", "One", 9),+ folder("b", "Two", 8),+ folder("c", "Three", 7),+ folder("d", "Four", 6),+ ],+ 500,+ );+ renderQueue();++ const [first] = await screen.findAllByRole("button", { name: "Approve" });+ await userEvent.click(first);++ expect((await screen.findByRole("alert")).textContent).toContain(+ "Couldn't send your answer",+ );+});++// As the server marks them (backend/copilot/gate/policy.py `is_irreversible`).+function destructive(id: string, tool: string, args: Record<string, unknown>) {+ return heldReview({+ id,+ tool,+ args,+ subject: {+ kind: "tool",+ key: tool,+ name: tool,+ effect: "platform",+ irreversible: true,+ },+ });+}++test.each([+ ["delete_workspace_file", (n: string) => ({ path: `${n}.md` })],+ ["delete_skill", (n: string) => ({ name: n })],+ ["delete_schedule", (n: string) => ({ schedule_id: n })],+ ["memory_forget_confirm", (n: string) => ({ uuids: [n], hard_delete: true })],+])(+ "%s is marked can't-be-undone and never approved as a set",+ async (tool, args) => {+ serve([+ destructive("a", tool, args("one")),+ destructive("b", tool, args("two")),+ ]);+ renderQueue();++ await queue();+ expect(screen.getAllByText("Can't be undone")).toHaveLength(2);+ expect(screen.queryByRole("button", { name: "Approve both" })).toBeNull();+ },+);++test("a folder delete, which moves its agents to the root, stays unmarked", async () => {+ serve([deleteFolder("a", "f-111")]);+ renderQueue();++ expect(await screen.findByText("f-111")).toBeDefined();+ expect(screen.queryByText("Can't be undone")).toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.tsnew file mode 100644index 0000000000..01fab57cb7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/fixtures.ts@@ -0,0 +1,137 @@+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";++export const CHAT_SESSION = "s1";++interface HeldArgs {+ id: string;+ tool: string;+ args?: Record<string, unknown>;+ fields?: { key: string; label: string }[];+ reason?: string;+ reasonKind?: string;+ mode?: string;+ subject?: Record<string, unknown>;+ chatRules?: string[];+ headline?: { ask: string; object?: string; object_key?: string };+ extra?: Record<string, unknown>;+ minutesAgo?: number;+}++// A gate review row as the server writes it (backend/copilot/gate/review.py).+export function heldReview({+ id,+ tool,+ args = {},+ fields,+ reason = "Ask First is on for this chat, so this action needs your approval.",+ reasonKind = "mode",+ mode = "ask_first",+ subject,+ chatRules = [],+ headline = { ask: tool },+ extra = {},+ minutesAgo = 5,+}: HeldArgs): PendingHumanReviewModel {+ const node = `copilot-node-gate-${tool}`;+ return {+ node_exec_id: `${node}:${id}`,+ node_id: node,+ user_id: "u-1",+ session_id: CHAT_SESSION,+ graph_exec_id: null,+ graph_id: null,+ graph_version: null,+ payload: {+ tool,+ arguments: args,+ clipped: [],+ fields:+ fields ??+ Object.keys(args).map((key) => ({+ key,+ label: key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " "),+ })),+ tool_call_id: `call-${id}`,+ turn: 1,+ mode,+ subject: subject ?? {+ kind: "tool",+ key: tool,+ name: tool,+ effect: "platform",+ irreversible: false,+ },+ reason,+ reason_kind: reasonKind,+ chat_rules_allowed: chatRules,+ headline,+ ...extra,+ },+ instructions: tool,+ editable: false,+ status: "WAITING",+ created_at: new Date(Date.now() - minutesAgo * 60_000),+ };+}++export function folder(id: string, name: string, minutesAgo = 5) {+ return heldReview({+ id,+ tool: "create_folder",+ args: { name },+ fields: [{ key: "name", label: "Name" }],+ headline: { ask: "Create folder", object: name, object_key: "name" },+ minutesAgo,+ });+}++export function mail(id = "mail", chatRules: string[] = ["allow", "judge"]) {+ return heldReview({+ id,+ tool: "run_capability",+ mode: "auto",+ reason: "Runs Gmail Send, which reaches outside the platform.",+ reasonKind: "subject",+ subject: {+ kind: "block",+ key: "gmail-send",+ name: "Gmail Send",+ effect: "external",+ irreversible: true,+ },+ chatRules,+ args: {+ to: ["[email protected]", "[email protected]"],+ subject: "Q3 invoices ready for review",+ body: "Hi Dana,\n\nThe Q3 invoice pack is in the shared “Invoices” folder. Three of them are still missing a PO number.\n\nCould you look before Friday?\n\nThanks,\nOtto",+ account: "[email protected]",+ api_key: "[redacted]",+ },+ });+}++export function shell(id = "shell") {+ return heldReview({+ id,+ tool: "bash_exec",+ mode: "auto",+ reason: "it uploads a file to a server outside the sandbox.",+ reasonKind: "supervisor",+ args: {+ command:+ "tar czf /tmp/q3.tgz ~/invoices && curl -F f=@/tmp/q3.tgz https://files.example.net/upload",+ },+ fields: [{ key: "command", label: "Command" }],+ headline: { ask: "Run a command in the sandbox" },+ });+}++export function deleteFolder(id: string, folderId: string) {+ return heldReview({+ id,+ tool: "delete_folder",+ args: { folder_id: folderId },+ fields: [{ key: "folder_id", label: "Folder" }],+ headline: { ask: "Delete a folder" },+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/goToApproval.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/goToApproval.test.tsxnew file mode 100644index 0000000000..a87c94a9b3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/goToApproval.test.tsx@@ -0,0 +1,58 @@+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { expect, test, vi } from "vitest";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import type { MessagePart } from "../../ChatMessagesContainer/helpers";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { CopilotPendingReviews } from "../../CopilotPendingReviews/CopilotPendingReviews";+import { ToolChain } from "../../ToolChain/ToolChain";+import { approvalCardId } from "../helpers";+import { folder, CHAT_SESSION } from "./fixtures";++// The chain row sits above the queue; its link must reach a card that is in+// the page however far the queue is scrolled, compact lines included.+test.each([1, 4])(+ "Go to the approval focuses the held call's card with %i waiting",+ async (count) => {+ const reviews = Array.from({ length: count }, (_, i) =>+ folder(`id${i}`, `Folder ${i}`, 10 - i),+ );+ server.use(+ http.get(`*/api/review/session/${CHAT_SESSION}`, () =>+ HttpResponse.json(reviews),+ ),+ );+ const held = {+ type: "tool-create_folder",+ state: "output-available",+ toolCallId: "call-id0",+ input: { name: "Folder 0" },+ output: {+ type: "approval_required",+ tool_name: "create_folder",+ review_id: reviews[0].node_exec_id,+ ask: "Create folder",+ object: "Folder 0",+ },+ } as MessagePart;++ render(+ <CopilotChatActionsProvider onSend={vi.fn()}>+ <ToolChain parts={[held]} isStreaming={false} />+ <CopilotPendingReviews chatSessionId={CHAT_SESSION} />+ </CopilotChatActionsProvider>,+ );++ await screen.findByRole("region", { name: "Waiting for you" });+ await userEvent.click(+ await screen.findByRole("button", { name: "Go to the approval" }),+ );++ await waitFor(() =>+ expect(document.activeElement?.id).toBe(+ approvalCardId(reviews[0].node_exec_id),+ ),+ );+ },+);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.tsxnew file mode 100644index 0000000000..0a1fe14c84--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx@@ -0,0 +1,95 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { ApprovalFields } from "@/components/organisms/ApprovalFields/ApprovalFields";+import {+ type ApprovalItem,+ type ChatRule,+ isBare,+ reasonLine,+} from "../../helpers";+import { ApprovalHeadline } from "../ApprovalHeadline";+import { ApproveSplitButton } from "./ApproveSplitButton";+import { useApprovalFields } from "./useApprovalFields";++export type CardStatus = "idle" | "approving" | "rejecting";++interface Props {+ item: ApprovalItem;+ status: CardStatus;+ failed: boolean;+ onApprove: (rule?: ChatRule) => void;+ onReject: () => void;+}++export function ApprovalCard({+ item,+ status,+ failed,+ onApprove,+ onReject,+}: Props) {+ const fields = useApprovalFields(item);+ const reason = reasonLine(item);+ const busy = status !== "idle";++ const actions = (+ <div className="grid grid-cols-2 gap-2 sm:flex sm:shrink-0 sm:flex-wrap">+ <ApproveSplitButton+ label="Approve"+ subjectName={item.subject.name}+ rules={item.chatRulesAllowed}+ loading={status === "approving"}+ disabled={busy}+ onApprove={onApprove}+ />+ <Button+ size="small"+ variant="secondary"+ className="min-w-0"+ loading={status === "rejecting"}+ disabled={busy}+ onClick={onReject}+ >+ {status === "rejecting" ? "Rejecting…" : "Reject"}+ </Button>+ </div>+ );++ // Nothing to read beyond the headline: the card is one row, as a list line is.+ if (isBare(item) && !failed) {+ return (+ <article+ aria-busy={busy}+ className="flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-center sm:gap-3"+ >+ <div className="min-w-0 flex-1">+ <ApprovalHeadline item={item} />+ </div>+ {actions}+ </article>+ );+ }++ return (+ <article aria-busy={busy} className="flex flex-col gap-2 px-4 py-3">+ <ApprovalHeadline item={item} />+ <div className="flex flex-col gap-3 sm:pl-[38px]">+ {failed && (+ <p role="alert" className="text-sm text-red-600">+ Couldn't send your answer. Nothing ran. Try again.+ </p>+ )}+ {reason && <p className="-mt-1 text-sm text-zinc-500">{reason}</p>}+ <ApprovalFields+ fields={fields.labels}+ values={fields.values}+ clipped={item.clipped}+ hiddenKeys={item.headlineKeys}+ idsWhenAlone={!item.headline.object}+ />+ {actions}+ </div>+ </article>+ );+}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.tsxnew file mode 100644index 0000000000..b47ce8858c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApproveSplitButton.tsx@@ -0,0 +1,93 @@+"use client";++import { ArrowDown01Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";+import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";+import type { ChatRule } from "../../helpers";++interface Props {+ label: string;+ subjectName: string;+ rules: ChatRule[];+ loading: boolean;+ disabled: boolean;+ onApprove: (rule?: ChatRule) => 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,+ rules,+ loading,+ disabled,+ onApprove,+}: Props) {+ const main = (+ <Button+ size="small"+ variant="primary"+ loading={loading}+ disabled={disabled}+ onClick={() => onApprove()}+ className={+ rules.length > 0 ? "min-w-0 flex-1 rounded-r-none pr-2.5" : "min-w-0"+ }+ >+ {loading ? "Approving…" : label}+ </Button>+ );+ if (rules.length === 0) return main;++ return (+ <div className="inline-flex">+ {main}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ size="small"+ variant="primary"+ disabled={disabled}+ aria-label="More ways to approve"+ withTooltip={false}+ className="min-w-0 rounded-l-none border-l-zinc-600 px-2"+ >+ <Icon icon={ArrowDown01Icon} size={14} aria-hidden />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-72">+ {rules.map((rule) => {+ const [title, detail] = RULE_COPY[rule](subjectName);+ return (+ <DropdownMenuItem+ key={rule}+ onSelect={() => onApprove(rule)}+ className="flex flex-col items-start gap-0.5 py-2"+ >+ <span className="text-sm text-zinc-900">{title}</span>+ <span className="text-xs text-zinc-500">{detail}</span>+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/useApprovalFields.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/useApprovalFields.tsnew file mode 100644index 0000000000..3a861fc5d6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/useApprovalFields.ts@@ -0,0 +1,25 @@+import { useReviewBlockSchema } from "@/components/organisms/PendingReviewCard/components/ReviewInputFields/useReviewBlockSchema";+import { asObject } from "../../../ToolChain/resultHelpers";+import type { ApprovalItem } from "../../helpers";++// A block's inputs are labelled by the block's own schema; a tool's by the server.+export function useApprovalFields(item: ApprovalItem) {+ const { schema } = useReviewBlockSchema(item.blockId);+ if (!item.blockId) return { labels: item.fields, values: item.args };+ const values = asObject(item.args.input_data) ?? {};+ const properties = asObject(schema?.properties) ?? {};+ const required = Array.isArray(schema?.required)+ ? (schema.required as string[])+ : [];+ const keys = [+ ...required.filter((key) => key in properties),+ ...Object.keys(properties).filter((key) => !required.includes(key)),+ ];+ return {+ labels: keys.map((key) => ({+ key,+ label: String(asObject(properties[key])?.title ?? key),+ })),+ values,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalHeadline.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalHeadline.tsxnew file mode 100644index 0000000000..448abddb95--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalHeadline.tsx@@ -0,0 +1,59 @@+import { Text } from "@/components/atoms/Text/Text";+import { cn } from "@/lib/utils";+import { COPILOT_TOOL_CATALOG } from "../../ToolChain/toolCatalog";+import { RowIcon } from "../../ToolChain/RowIcon";+import type { ApprovalItem } from "../helpers";++interface Props {+ item: ApprovalItem;+ // Inside a button a heading is not allowed, so the line renders a span.+ compact?: boolean;+}++export function ApprovalHeadline({ item, compact = false }: Props) {+ const category = COPILOT_TOOL_CATALOG[item.toolName]?.category ?? "other";+ return (+ <div className="flex min-w-0 items-start gap-2.5">+ <span+ aria-hidden="true"+ className="flex size-7 shrink-0 items-center justify-center rounded-lg border border-zinc-200 bg-white"+ >+ <RowIcon+ row={{ key: item.reviewId, category, text: "", state: "done" }}+ />+ </span>+ <Text+ variant="body"+ as={compact ? "span" : "h3"}+ className={cn(+ "min-w-0 flex-1 pt-[3px] text-zinc-900",+ compact ? "truncate" : "text-pretty",+ )}+ >+ <HeadlineText item={item} />+ </Text>+ {item.subject.irreversible && (+ <span className="mt-0.5 shrink-0 rounded-md bg-red-50 px-1.5 py-0.5 text-xs font-medium text-red-700">+ Can't be undone+ </span>+ )}+ </div>+ );+}++export function HeadlineText({ item }: Props) {+ const { ask, object } = item.headline;+ return (+ <>+ {ask}+ {object && (+ <>+ {" "}+ <b className="font-semibold" translate="no">+ {object}+ </b>+ </>+ )}+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/CompactApprovalLine.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/CompactApprovalLine.tsxnew file mode 100644index 0000000000..d59161a5d4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/CompactApprovalLine.tsx@@ -0,0 +1,69 @@+import { Button } from "@/components/atoms/Button/Button";+import type { ApprovalItem } from "../helpers";+import type { CardStatus } from "./ApprovalCard/ApprovalCard";+import { ApprovalHeadline } from "./ApprovalHeadline";++interface Props {+ item: ApprovalItem;+ // Nothing beyond the headline to show, so it can be answered in place.+ bare: boolean;+ status: CardStatus;+ onOpen: () => void;+ onApprove: () => void;+ onReject: () => void;+}++export function CompactApprovalLine({+ item,+ bare,+ status,+ onOpen,+ onApprove,+ onReject,+}: Props) {+ const busy = status !== "idle";+ return (+ <div className="flex items-center gap-3 px-4 py-2">+ <button+ type="button"+ onClick={onOpen}+ className="min-w-0 flex-1 rounded-md text-left hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-300"+ >+ <ApprovalHeadline item={item} compact />+ </button>+ {bare ? (+ <div className="flex shrink-0 gap-2">+ <Button+ size="xs"+ variant="primary"+ className="rounded-full"+ loading={status === "approving"}+ disabled={busy}+ onClick={onApprove}+ >+ Approve+ </Button>+ <Button+ size="xs"+ variant="secondary"+ className="rounded-full"+ loading={status === "rejecting"}+ disabled={busy}+ onClick={onReject}+ >+ Reject+ </Button>+ </div>+ ) : (+ <Button+ size="xs"+ variant="secondary"+ className="shrink-0 rounded-full"+ onClick={onOpen}+ >+ Review+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/QueueHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/QueueHeader.tsxnew file mode 100644index 0000000000..4378325ae3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/QueueHeader.tsx@@ -0,0 +1,35 @@+import { Button } from "@/components/atoms/Button/Button";+import { approveAllLabel, modeLabel } from "../helpers";++interface Props {+ count: number;+ mode: string | null;+ approveAll: { count: number; busy: boolean; onClick: () => void } | null;+}++export function QueueHeader({ count, mode, approveAll }: Props) {+ return (+ <div className="flex min-h-11 items-center justify-between gap-3 border-b border-zinc-100 bg-zinc-50/60 px-4 py-2">+ <span className="flex items-baseline gap-2 text-sm font-medium text-zinc-900">+ Waiting for you+ <span className="tabular-nums text-zinc-500">{count}</span>+ </span>+ <div className="flex items-center gap-3">+ {modeLabel(mode) && (+ <span className="text-xs text-zinc-500">{modeLabel(mode)}</span>+ )}+ {approveAll && (+ <Button+ size="small"+ variant="secondary"+ className="min-w-0"+ disabled={approveAll.busy}+ onClick={approveAll.onClick}+ >+ {approveAllLabel(approveAll.count)}+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ReceiptLine.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ReceiptLine.tsxnew file mode 100644index 0000000000..4a9a575600--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ReceiptLine.tsx@@ -0,0 +1,30 @@+import {+ Cancel01Icon,+ InformationCircleIcon,+ Tick02Icon,+} from "@hugeicons/core-free-icons";+import { Icon } from "@/components/atoms/Icon/Icon";+import type { Receipt } from "../useApprovalQueue";+import { HeadlineText } from "./ApprovalHeadline";++interface Props {+ receipt: Receipt;+}++export function ReceiptLine({ receipt }: Props) {+ const [icon, tone] =+ receipt.text === "Approved"+ ? [Tick02Icon, "text-green-600"]+ : receipt.text === "Rejected"+ ? [Cancel01Icon, "text-zinc-400"]+ : [InformationCircleIcon, "text-zinc-400"];+ return (+ <li className="flex items-center gap-2 px-4 py-2 text-sm text-zinc-600">+ <Icon icon={icon} size={14} className={tone} aria-hidden />+ <span className="min-w-0 truncate">+ <HeadlineText item={receipt.item} />+ </span>+ <span className="shrink-0 text-zinc-400">· {receipt.text}</span>+ </li>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/RejectAllFooter.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/RejectAllFooter.tsxnew file mode 100644index 0000000000..033571e13a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/RejectAllFooter.tsx@@ -0,0 +1,59 @@+import { Button } from "@/components/atoms/Button/Button";+import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";++interface Props {+ count: number;+ confirming: boolean;+ busy: boolean;+ onAsk: () => void;+ onCancel: () => void;+ onConfirm: () => void;+}++export function RejectAllFooter({+ count,+ confirming,+ busy,+ onAsk,+ onCancel,+ onConfirm,+}: Props) {+ return (+ <div className="flex flex-wrap items-center gap-2 border-t border-zinc-100 bg-zinc-50/60 px-4 py-2 text-sm">+ {confirming ? (+ <>+ <span role="alert" className="text-zinc-700">+ Reject all {count}? {AUTOPILOT_NAME} will be told none of them ran.+ </span>+ <Button+ size="xs"+ variant="primary"+ className="rounded-full"+ disabled={busy}+ onClick={onConfirm}+ >+ Reject all+ </Button>+ <Button+ size="xs"+ variant="ghost"+ className="rounded-full"+ onClick={onCancel}+ >+ Cancel+ </Button>+ </>+ ) : (+ <Button+ variant="link"+ size="small"+ className="h-auto min-w-0 px-0 py-0 text-sm"+ disabled={busy}+ onClick={onAsk}+ >+ Reject all {count}…+ </Button>+ )}+ </div>+ );+}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.tsnew file mode 100644index 0000000000..643ad09549--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts@@ -0,0 +1,166 @@+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { COPILOT_GATE_NODE_PREFIX } from "@/components/organisms/PendingReviewsList/PendingReviewsList";+import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";+import {+ isIdKey,+ visibleKeys,+} from "@/components/organisms/ApprovalFields/helpers";+import { beautifyString } from "@/lib/utils";+import { asObject, str } from "../ToolChain/resultHelpers";++export type ReasonKind = "mode" | "subject" | "supervisor" | "rule";++export type ChatRule = "allow" | "judge";++export interface ApprovalItem {+ reviewId: string;+ // Which list the answer refreshes: a chat's queue, or a run's.+ scope: Pick<PendingHumanReviewModel, "graph_exec_id" | "session_id">;+ toolName: string;+ toolCallId: string;+ args: Record<string, unknown>;+ fields: { key: string; label: string }[];+ clipped: string[];+ subject: { kind: string; key: string; name: string; irreversible: boolean };+ blockId: string | null;+ reason: string;+ reasonKind: ReasonKind;+ mode: string | null;+ chatRulesAllowed: ChatRule[];+ headline: { ask: string; object: string | null };+ // The argument the headline already names.+ headlineKeys: string[];+}++export function isGateReview(review: PendingHumanReviewModel) {+ return review.node_exec_id.startsWith(COPILOT_GATE_NODE_PREFIX);+}++export function toApprovalItem(review: PendingHumanReviewModel): ApprovalItem {+ const payload = asObject(review.payload) ?? {};+ const toolName =+ str(payload, "tool") ??+ (review.node_id ?? "").replace(COPILOT_GATE_NODE_PREFIX, "");+ const subject = asObject(payload.subject) ?? {};+ const headline = asObject(payload.headline) ?? {};+ const objectKey = str(headline, "object_key");+ return {+ reviewId: review.node_exec_id,+ scope: {+ graph_exec_id: review.graph_exec_id,+ session_id: review.session_id,+ },+ toolName,+ toolCallId: str(payload, "tool_call_id") ?? "",+ args: asObject(payload.arguments) ?? {},+ fields: asArray(payload.fields)+ .map((f) => asObject(f) ?? {})+ .filter((f) => str(f, "key"))+ .map((f) => ({+ key: String(f.key),+ label: str(f, "label") ?? String(f.key),+ })),+ clipped: asArray(payload.clipped).filter(+ (k): k is string => typeof k === "string",+ ),+ subject: {+ kind: str(subject, "kind") ?? "tool",+ key: str(subject, "key") ?? toolName,+ name: str(subject, "name") ?? toolName,+ irreversible: subject.irreversible === true,+ },+ blockId: str(subject, "block_id"),+ reason: str(payload, "reason") ?? "",+ reasonKind: (str(payload, "reason_kind") as ReasonKind | null) ?? "mode",+ mode: str(payload, "mode"),+ chatRulesAllowed: asArray(payload.chat_rules_allowed).filter(+ (r): r is ChatRule => r === "allow" || r === "judge",+ ),+ headline:+ subject.kind === "block"+ ? { ask: "Run", object: str(subject, "name") }+ : {+ ask: str(headline, "ask") ?? fallbackAsk(toolName),+ object: str(headline, "object"),+ },+ headlineKeys: objectKey ? [objectKey] : [],+ };+}++// A row the server wrote no headline for still names its tool.+export function fallbackAsk(toolName: string) {+ return `Run ${beautifyString(toolName.replace(/^run_/, "")).toLowerCase()}`;+}++export function approvalCardId(reviewId: string) {+ return `approval-${reviewId.replace(/[^a-zA-Z0-9_-]/g, "-")}`;+}++// Said once in the queue header; per card only a reason about this call.+export function reasonLine(item: ApprovalItem): string | null {+ if (!item.reason) return null;+ if (item.reasonKind === "supervisor")+ return `Not sure this is safe: ${item.reason}`;+ if (item.reasonKind === "subject" || item.reasonKind === "rule")+ return item.reason;+ return null;+}++export function modeLabel(mode: string | null) {+ if (mode === "ask_first") return "Ask First";+ if (mode === "unsupervised") return "Unsupervised";+ if (mode === "auto") return "Auto";+ return null;+}++export function modeLine(mode: string | null) {+ if (mode === "ask_first")+ return `Ask First is on, so ${AUTOPILOT_NAME} asks before he changes anything outside his workspace.`;+ return `${AUTOPILOT_NAME} asks before anything that reaches outside the platform.`;+}++export function shownFieldKeys(item: ApprovalItem) {+ return visibleKeys({+ keys: [...item.fields.map((f) => f.key), ...Object.keys(item.args)],+ values: item.args,+ hiddenKeys: item.headlineKeys,+ idsWhenAlone: !item.headline.object,+ });+}++// Nothing to read beyond the headline, so a compact line may answer it in place.+export function isBare(item: ApprovalItem) {+ return (+ shownFieldKeys(item).length === 0 &&+ !reasonLine(item) &&+ !item.subject.irreversible+ );+}++export const MAX_APPROVE_ALL = 5;++export function canApproveAll(items: ApprovalItem[], compact: boolean) {+ if (items.length < 2 || items.length > MAX_APPROVE_ALL) return false;+ const key = items[0].subject.key;+ return items.every(+ (item) =>+ item.subject.key === key &&+ !item.subject.irreversible &&+ !isIdOnly(item) &&+ (!compact || isBare(item)),+ );+}++export function approveAllLabel(count: number) {+ return count === 2 ? "Approve both" : `Approve all ${count}`;+}++// Told apart only by ids, so a set of them cannot be approved as one.+function isIdOnly(item: ApprovalItem) {+ const keys = shownFieldKeys(item);+ return !item.headline.object && keys.length > 0 && keys.every(isIdKey);+}++function asArray(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}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.tsnew file mode 100644index 0000000000..761d1e0a66--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/useApprovalQueue.ts@@ -0,0 +1,113 @@+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, ChatRule } from "./helpers";++export interface Receipt {+ item: ApprovalItem;+ text: string;+}++interface Args {+ items: ApprovalItem[];+ onAnswered: () => void;+}++export function useApprovalQueue({ items, onAnswered }: Args) {+ const outcomes = useContext(HeldOutcomesContext);+ const { processReviews } = useProcessReviews();+ const [statuses, setStatuses] = useState<Record<string, CardStatus>>({});+ const [failed, setFailed] = useState<string[]>([]);+ const [receipts, setReceipts] = useState<Receipt[]>([]);+ const [openId, setOpenId] = useState<string | null>(null);+ const [confirmRejectAll, setConfirmRejectAll] = useState(false);+ const seen = useRef(new Map<string, ApprovalItem>());+ const answeredHere = useRef(new Set<string>());++ // A card that leaves the poll without an answer from here was answered on Home or another tab.+ useEffect(() => {+ const current = new Set(items.map((item) => item.reviewId));+ const gone = [...seen.current.values()].filter(+ (item) =>+ !current.has(item.reviewId) && !answeredHere.current.has(item.reviewId),+ );+ if (gone.length > 0) {+ setReceipts((prev) => [+ ...prev,+ ...gone.map((item) => ({ item, text: "Answered elsewhere" })),+ ]);+ }+ seen.current = new Map(items.map((item) => [item.reviewId, item]));+ }, [items]);++ async function answer(+ batch: ApprovalItem[],+ approved: boolean,+ rule?: ChatRule,+ ) {+ const ids = batch.map((item) => item.reviewId);+ setFailed((prev) => prev.filter((id) => !ids.includes(id)));+ setStatuses((prev) => ({+ ...prev,+ ...Object.fromEntries(+ ids.map((id) => [id, approved ? "approving" : "rejecting"]),+ ),+ }));+ ids.forEach((id) => answeredHere.current.add(id));+ let ok = false;+ try {+ const res = await processReviews(+ batch.map((item) => ({+ node_exec_id: item.reviewId,+ approved,+ // The chat-scoped rule rides the approval; the gate reads it once it records rules.+ auto_approve_future: approved && !!rule,+ message: rule,+ })),+ batch.map((item) => item.scope),+ );+ ok = res.status === 200 && res.data.failed_count === 0;+ } catch {+ ok = false;+ }+ if (ok) {+ setReceipts((prev) => [+ ...prev,+ ...batch.map((item) => ({+ item,+ text: approved ? "Approved" : "Rejected",+ })),+ ]);+ setConfirmRejectAll(false);+ onAnswered();+ } else {+ ids.forEach((id) => answeredHere.current.delete(id));+ setFailed((prev) => [...prev, ...ids]);+ }+ setStatuses((prev) => {+ const next = { ...prev };+ ids.forEach((id) => delete next[id]);+ return next;+ });+ }++ const receiptIds = new Set(receipts.map((r) => r.item.reviewId));+ const currentIds = new Set(items.map((item) => item.reviewId));+ return {+ pending: items.filter((item) => !receiptIds.has(item.reviewId)),+ // A receipt stays until the chain row shows the answer.+ receipts: receipts.filter((r) =>+ r.item.toolCallId+ ? !outcomes.has(r.item.toolCallId)+ : currentIds.has(r.item.reviewId),+ ),+ statusOf: (id: string) => statuses[id] ?? "idle",+ hasFailed: (id: string) => failed.includes(id),+ openId,+ setOpenId,+ confirmRejectAll,+ setConfirmRejectAll,+ answer,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PendingAnswerContexts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PendingAnswerContexts.tsxindex f686e8e316..342146d98a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PendingAnswerContexts.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/PendingAnswerContexts.tsx@@ -1,6 +1,8 @@"use client";import type { UIDataTypes, UIMessage, UITools } from "ai";+import { getHeldOutcomes } from "../../ChatMessagesContainer/heldCallRows";+import { HeldOutcomesContext } from "../../ChatMessagesContainer/HeldOutcomesContext";import { getPendingOnboardingCallId } from "../../ExpertOnboardingCard/helpers";import { PendingOnboardingContext } from "../../ExpertOnboardingCard/PendingOnboardingContext";import { getPendingQuestions } from "../../QuestionDock/helpers";@@ -12,16 +14,18 @@ interface Props {}/** What the session is still waiting on the user for: the clarifying-question- * dock and the hire's onboarding card each decide from here whether their- * form is live or already history, rather than from local state a reload- * would lose. */+ * dock, the hire's onboarding card and a held call's row each decide from+ * here whether they are live or already history, rather than from local+ * state a reload would lose. */export function PendingAnswerContexts({ messages, children }: Props) {return (<PendingQuestionsContext.Provider value={getPendingQuestions(messages)}><PendingOnboardingContext.Providervalue={getPendingOnboardingCallId(messages)}>- {children}+ <HeldOutcomesContext.Provider value={getHeldOutcomes(messages)}>+ {children}+ </HeldOutcomesContext.Provider></PendingOnboardingContext.Provider></PendingQuestionsContext.Provider>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/HeldOutcomesContext.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/HeldOutcomesContext.tsnew file mode 100644index 0000000000..63311ca14c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/HeldOutcomesContext.ts@@ -0,0 +1,10 @@+"use client";++import { createContext } from "react";+import type { HeldOutcome } from "./heldCallRows";++/** Answered held calls by their original tool call id, so the chain row and+ * the approval queue read the answer from the persisted late result. */+export const HeldOutcomesContext = createContext<+ ReadonlyMap<string, HeldOutcome>+>(new Map());diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/heldOutcomes.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/heldOutcomes.test.tsnew file mode 100644index 0000000000..9de65d5fd5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/heldOutcomes.test.ts@@ -0,0 +1,70 @@+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { expect, test } from "vitest";+import { getHeldOutcomes } from "../heldCallRows";++function lateResult(+ metadata: Record<string, unknown>,+ body: string,+): UIMessage<unknown, UIDataTypes, UITools> {+ return {+ id: "m1",+ role: "user",+ metadata,+ parts: [+ {+ type: "text",+ text: `<held_call_result tool="create_folder" tool_call_id="call-7" review_id="r">\n${body}\n</held_call_result>`,+ },+ ],+ };+}++test("a late result is keyed by the original call and carries its outcome and output", () => {+ const outcomes = getHeldOutcomes([+ lateResult(+ { held_call: { tool_call_id: "call-7", outcome: "approved" } },+ '{"type":"folder_created","name":"Q3"}',+ ),+ ]);+ expect(outcomes.get("call-7")).toEqual({+ outcome: "approved",+ output: { type: "folder_created", name: "Q3" },+ });+});++test("a row from before outcomes were recorded is read from its text", () => {+ const refused = getHeldOutcomes([+ lateResult(+ { held_call: { tool_call_id: "call-7" } },+ "Nothing ran: declined",+ ),+ ]);+ expect(refused.get("call-7")?.outcome).toBe("closed");+});++test("an unknown outcome reads as approved, and plain text stays text", () => {+ const outcomes = getHeldOutcomes([+ lateResult({ held_call: { tool_call_id: "call-7" } }, "posted"),+ ]);+ expect(outcomes.get("call-7")).toEqual({+ outcome: "approved",+ output: "posted",+ });+});++test("rows that are not late results are ignored", () => {+ expect(+ getHeldOutcomes([lateResult({ held_calls_answered: true }, "x")]).size,+ ).toBe(0);+});++test("an output that contains the closing tag is kept whole", () => {+ const body = 'wrote "</held_call_result>" into notes.md';+ const outcomes = getHeldOutcomes([+ lateResult(+ { held_call: { tool_call_id: "call-7", outcome: "approved" } },+ body,+ ),+ ]);+ expect(outcomes.get("call-7")?.output).toBe(body);+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.tsindex 57807e3efb..0ab76a597f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts@@ -46,3 +46,72 @@ function isHeldOutput(output: unknown): boolean {typeof (value as { review_id?: unknown }).review_id === "string");}++export type HeldOutcomeKind =+ | "approved"+ | "rejected"+ | "expired"+ | "closed"+ | "unknown";++export interface HeldOutcome {+ outcome: HeldOutcomeKind;+ // The run's own output, as the tool would have returned it directly.+ output: unknown;+}++const OUTCOMES = new Set<string>([+ "approved",+ "rejected",+ "expired",+ "closed",+ "unknown",+]);+// Anchored at the end: the output itself may contain the closing tag.+const RESULT_RE =+ /<held_call_result[^>]*>\n?([\s\S]*?)\n?<\/held_call_result>\s*$/;++export function getHeldOutcomes(+ messages: UIMessage<unknown, UIDataTypes, UITools>[],+): Map<string, HeldOutcome> {+ const outcomes = new Map<string, HeldOutcome>();+ for (const message of messages) {+ const held = heldCallMetadata(message.metadata);+ if (!held) continue;+ const text = message.parts+ .map((part) => (part.type === "text" ? part.text : ""))+ .join("");+ const body = RESULT_RE.exec(text)?.[1] ?? "";+ outcomes.set(held.toolCallId, {+ // Rows persisted before the outcome was recorded say "Nothing ran" when refused.+ outcome:+ held.outcome ??+ (body.startsWith("Nothing ran") ? "closed" : "approved"),+ output: parseOutput(body),+ });+ }+ return outcomes;+}++function heldCallMetadata(metadata: unknown) {+ if (!metadata || typeof metadata !== "object") return null;+ const held = (metadata as { held_call?: unknown }).held_call;+ if (!held || typeof held !== "object") return null;+ const { tool_call_id, outcome } = held as Record<string, unknown>;+ if (typeof tool_call_id !== "string" || !tool_call_id) return null;+ return {+ toolCallId: tool_call_id,+ outcome:+ typeof outcome === "string" && OUTCOMES.has(outcome)+ ? (outcome as HeldOutcomeKind)+ : null,+ };+}++function parseOutput(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+}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 59985b60ff..24f1260628 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@@ -7,6 +7,8 @@ import {} from "@/components/organisms/PendingReviewsList/PendingReviewsList";import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";import { okData } from "@/app/api/helpers";+import { ApprovalQueue } from "../ApprovalQueue/ApprovalQueue";+import { isGateReview, toApprovalItem } from "../ApprovalQueue/helpers";import { useCopilotPendingReviews } from "./useCopilotPendingReviews";type Props =@@ -15,18 +17,18 @@ type Props =/*** Renders the chat's pending reviews, or those of an agent run it started:- * each held AutoPilot call as its own card, oldest first, and every block,- * MCP or run review in one consolidated list.+ * held AutoPilot calls in one "Waiting for you" queue, oldest first, and+ * every block, MCP or run review in one consolidated list.*/export function CopilotPendingReviews(props: Props) {const { onSend, onBackendTurn } = useCopilotChatActions();const graphExecId = "graphExecId" in props ? props.graphExecId : "";const { pendingReviews, refetch } = useCopilotPendingReviews(props);- // A held call's own card runs it: one Approve per call, never one for all.- const heldCalls = pendingReviews.filter((r) =>- r.node_exec_id.startsWith(COPILOT_GATE_NODE_PREFIX),- );+ const heldCalls = pendingReviews+ .filter(isGateReview)+ .sort((a, b) => +new Date(a.created_at) - +new Date(b.created_at))+ .map(toApprovalItem);const otherReviews = pendingReviews.filter((r) => !r.node_exec_id.startsWith(COPILOT_GATE_NODE_PREFIX),);@@ -62,17 +64,9 @@ export function CopilotPendingReviews(props: Props) {}}, [refetch, onSend, graphExecId]);- if (pendingReviews.length === 0) return null;-return (- <div className="flex flex-col gap-2 py-2">- {heldCalls.map((review) => (- <PendingReviewsList- key={review.node_exec_id}- reviews={[review]}- onReviewComplete={handleHeldCallAnswered}- />- ))}+ <div className="flex flex-col gap-2 py-2 empty:hidden">+ <ApprovalQueue items={heldCalls} onAnswered={handleHeldCallAnswered} />{otherReviews.length > 0 && (<PendingReviewsListreviews={otherReviews}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsxindex 0e730fafe3..2570e51faa 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx@@ -10,6 +10,7 @@ import type { ChainRow } from "./helpers";import { ProviderIcon, RowIcon } from "./RowIcon";import { useSubSessionEffectiveStatus } from "./SubSessionLive";import { SwapText } from "./SwapText";+import { HeldTag } from "./HeldCallRowParts";import { getCatalogLabel } from "./toolCatalog";import { ToolResult } from "./ToolResult";import { ToolStatusBadge } from "./ToolStatusBadge";@@ -135,10 +136,17 @@ export function ChainRowView({ row, isLast, readOnly = false }: Props) {shimmer={row.state === "running" || stillWorking}className={cn("max-w-full text-sm transition-colors duration-300",- row.state === "error" ? "text-red-500" : "text-zinc-600",+ row.state === "error"+ ? "text-red-500"+ : row.held &&+ row.held.state !== "approved" &&+ row.held.state !== "waiting"+ ? "text-zinc-400"+ : "text-zinc-600",)}/>);+ const heldTag = row.held ? <HeldTag state={row.held.state} /> : null;return (<div className="flex items-stretch gap-2.5">@@ -167,9 +175,10 @@ export function ChainRowView({ row, isLast, readOnly = false }: Props) {type="button"onClick={() => setOpen(!open)}aria-expanded={showContent}- className="group/row flex h-7 items-center gap-1.5"+ className="group/row flex h-7 min-w-0 items-center gap-1.5">{rowText}+ {heldTag}{!liveReasoning && (<Iconicon={ArrowDown01Icon}@@ -182,7 +191,10 @@ export function ChainRowView({ row, isLast, readOnly = false }: Props) {)}</button>) : (- <div className="flex h-7 items-center gap-1.5">{rowText}</div>+ <div className="flex h-7 items-center gap-1.5">+ {rowText}+ {heldTag}+ </div>)}{row.detail && (<p className="animate-fade-in truncate text-xs text-red-400 motion-reduce:animate-none">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/HeldCallRowParts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/HeldCallRowParts.tsxnew file mode 100644index 0000000000..43883a8f57--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/HeldCallRowParts.tsx@@ -0,0 +1,67 @@+import { Tick02Icon } from "@hugeicons/core-free-icons";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";+import { cn } from "@/lib/utils";+import { approvalCardId } from "../ApprovalQueue/helpers";+import type { HeldRowInfo, HeldState } from "./heldRow";++const TAGS: Record<HeldState, { text: string; className: string }> = {+ waiting: { text: "Waiting for you", className: "bg-amber-50 text-amber-700" },+ approved: { text: "Approved", className: "bg-zinc-100 text-zinc-500" },+ rejected: { text: "Rejected", className: "bg-zinc-100 text-zinc-500" },+ expired: { text: "Expired", className: "bg-zinc-100 text-zinc-500" },+ closed: { text: "Not run", className: "bg-zinc-100 text-zinc-500" },+ unknown: { text: "Unclear", className: "bg-amber-50 text-amber-700" },+ "not-run": { text: "Not run", className: "bg-red-50 text-red-700" },+};++export function HeldTag({ state }: { state: HeldState }) {+ const tag = TAGS[state];+ return (+ <span+ className={cn(+ "inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-px text-xs font-medium",+ tag.className,+ )}+ >+ {state === "approved" && <Icon icon={Tick02Icon} size={11} aria-hidden />}+ {tag.text}+ </span>+ );+}++const DETAIL: Record<Exclude<HeldState, "approved">, string> = {+ waiting: `Nothing has run yet. ${AUTOPILOT_NAME} carried on without it.`,+ rejected: `You rejected this, so it didn't run. ${AUTOPILOT_NAME} was told.`,+ expired: `Approved, but it didn't run within an hour, so the approval lapsed. Ask ${AUTOPILOT_NAME} to try again.`,+ unknown: `It may have run, but its result was lost. Check before relying on it.`,+ closed: `It couldn't be carried out, so nothing ran. Ask ${AUTOPILOT_NAME} to try again if it's still needed.`,+ "not-run": `${AUTOPILOT_NAME} couldn't open an approval for this, so nothing ran.`,+};++export function HeldCallDetail({ held }: { held: HeldRowInfo }) {+ if (held.state === "approved") return null;+ const reviewId = held.reviewId;+ function goToApproval() {+ if (!reviewId) return;+ const el = document.getElementById(approvalCardId(reviewId));+ el?.scrollIntoView?.({ block: "center", behavior: "smooth" });+ el?.focus({ preventScroll: true });+ }+ return (+ <div className="flex flex-col items-start gap-1 rounded-lg border border-zinc-200 px-3 py-2 text-sm text-zinc-600">+ <p>{DETAIL[held.state]}</p>+ {held.state === "waiting" && reviewId && (+ <Button+ variant="link"+ size="small"+ className="h-auto min-w-0 px-0 py-0 text-sm"+ onClick={goToApproval}+ >+ Go to the approval+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsxindex b7d65d4c6c..bc04b35e1b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -36,7 +36,9 @@ import {type ChainActionEntry,} from "./chainActions";import { useCredentialFailureCounters } from "./useCredentialFailureCounters";+import { HeldOutcomesContext } from "../ChatMessagesContainer/HeldOutcomesContext";import { ChainRowView } from "./ChainRowView";+import { applyHeldOutcome } from "./heldRow";import {type ChainRow,getChainHeading,@@ -65,6 +67,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {const reducedMotion = useReducedMotion();const pendingQuestions = useContext(PendingQuestionsContext);+ const heldOutcomes = useContext(HeldOutcomesContext);const { onSend } = useCopilotChatActions();// The ref latches against a double effect run; the state re-renders Proceed.const autoSentRef = useRef(false);@@ -167,6 +170,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {parts.map((part, i) => toChainRow(part, i)).filter((row): row is ChainRow => row !== null)+ .map((row) => applyHeldOutcome(row, heldOutcomes))// Unanswered clarifying questions and setup cards render their work// in the card below the chain — their rows are lifted out of view..map((row) =>@@ -177,7 +181,7 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {: row,),),- [parts, pendingQuestions],+ [parts, pendingQuestions, heldOutcomes],);if (rows.length === 0) return null;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsxindex 627a62b06a..9291531229 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx@@ -1,6 +1,7 @@"use client";import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";+import { HeldCallDetail } from "./HeldCallRowParts";import { useContext } from "react";import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContext";import { QuestionsForm } from "../QuestionDock/QuestionDock";@@ -502,6 +503,10 @@ export function ToolResult({ row, readOnly = false }: Props) {);}+ if (row.held && row.held.state !== "approved") {+ return <HeldCallDetail held={row.held} />;+ }+const target = capabilityTargetRow(row);const card =toolCard(target, output, readOnly) ??diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldRow.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldRow.test.tsxnew file mode 100644index 0000000000..18ca7c14ba--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldRow.test.tsx@@ -0,0 +1,99 @@+import { expect, test, vi } from "vitest";+import { render, screen } from "@/tests/integrations/test-utils";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import type { MessagePart } from "../../ChatMessagesContainer/helpers";+import type { HeldOutcome } from "../../ChatMessagesContainer/heldCallRows";+import { HeldOutcomesContext } from "../../ChatMessagesContainer/HeldOutcomesContext";+import { ToolChain } from "../ToolChain";++const HELD: MessagePart = {+ type: "tool-create_folder",+ state: "output-available",+ toolCallId: "call-7",+ input: { name: "Q3 reports" },+ output: {+ type: "approval_required",+ tool_name: "create_folder",+ reason: "Ask First is on.",+ review_id: "copilot-node-gate-create_folder:abc",+ ask: "Create folder",+ object: "Q3 reports",+ },+} as MessagePart;++function chain(outcomes: Map<string, HeldOutcome>) {+ return (+ <CopilotChatActionsProvider onSend={vi.fn()}>+ <HeldOutcomesContext.Provider value={outcomes}>+ <ToolChain parts={[HELD]} isStreaming={false} />+ </HeldOutcomesContext.Provider>+ </CopilotChatActionsProvider>+ );+}++test("a held call's row flips from waiting to approved when its late result lands", async () => {+ const { rerender } = render(chain(new Map()));++ expect(await screen.findByText("Waiting for you")).toBeDefined();+ expect(+ screen.getAllByText('Create folder "Q3 reports"').length,+ ).toBeGreaterThan(0);++ rerender(+ chain(+ new Map([+ ["call-7", { outcome: "approved", output: { message: "Created" } }],+ ]),+ ),+ );++ expect(await screen.findByText("Approved")).toBeDefined();+ expect(+ screen.getAllByText('Created folder "Q3 reports"').length,+ ).toBeGreaterThan(0);+ expect(screen.queryByText("Waiting for you")).toBeNull();+});++test("a late result for another call leaves the row waiting", async () => {+ render(chain(new Map([["call-8", { outcome: "approved", output: "done" }]])));+ expect(await screen.findByText("Waiting for you")).toBeDefined();+});++test.each([+ ["rejected", "Rejected", "Didn't create folder"],+ ["expired", "Expired", "Didn't create folder"],+] as const)("a %s call says so on its row", async (outcome, tag, label) => {+ render(chain(new Map([["call-7", { outcome, output: "" }]])));+ expect(await screen.findByText(tag)).toBeDefined();+ expect(screen.getAllByText(new RegExp(label)).length).toBeGreaterThan(0);+});++test("an approved call that failed when it ran shows its error, still marked approved", async () => {+ render(+ chain(+ new Map([+ [+ "call-7",+ {+ outcome: "approved",+ output: { type: "error", message: "Folder exists" },+ },+ ],+ ]),+ ),+ );+ expect(await screen.findByText("Approved")).toBeDefined();+ // The error line under the row, as an unheld call's failure shows it.+ const errorLine = screen+ .getAllByText("Folder exists")+ .find((el) => el.className.includes("text-red"));+ expect(errorLine).toBeDefined();+});++test("a call that may have run claims neither approval nor refusal", async () => {+ render(chain(new Map([["call-7", { outcome: "unknown", output: "" }]])));+ expect(await screen.findByText("Unclear")).toBeDefined();+ expect(screen.queryByText("Approved")).toBeNull();+ expect(screen.queryByText(/Created folder/)).toBeNull();+ expect(screen.queryByText(/Didn't create folder/)).toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.tsindex bd7b368a8d..3d81ed4d88 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts@@ -269,13 +269,18 @@ describe("toChainRow", () => {toolPart("bash_exec",{ command: "ls" },- { type: "approval_required", tool_name: "bash_exec", reason: "why" },+ {+ type: "approval_required",+ tool_name: "bash_exec",+ reason: "why",+ ask: "Run a command in the sandbox",+ },),0,);expect(row?.requiresAction).toBe(true);- expect(row?.text).toBe("Approve Bash Exec");+ expect(row?.text).toBe("Run a command in the sandbox");});it.each([@@ -286,10 +291,10 @@ describe("toChainRow", () => {[{ type: "review_required" }, "Review this action"],[{ type: "approval_required", tool_name: "post_to_chat_platform" },- "Approve Post To Chat Platform",+ "Run post to chat platform",],- [{ type: "approval_required" }, "Approve this action"],- [{ type: "approval_required", tool_name: " " }, "Approve this action"],+ [{ type: "approval_required" }, "Run block"],+ [{ type: "approval_required", tool_name: " " }, "Run block"],[{ type: "suggested_goal" }, "Review the suggested goal"],[{ type: "need_login", message: "Log in first" }, "Log in first"],[{ type: "need_login" }, "Action required"],diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/heldRow.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/heldRow.tsnew file mode 100644index 0000000000..97a6658023--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/heldRow.ts@@ -0,0 +1,96 @@+import type { HeldOutcome } from "../ChatMessagesContainer/heldCallRows";+import { fallbackAsk } from "../ApprovalQueue/helpers";+import type { ChainRow } from "./helpers";+import { asObject, str } from "./resultHelpers";+import { getCatalogLabel } from "./toolCatalog";++export type HeldState =+ | "waiting"+ | "approved"+ | "rejected"+ | "expired"+ | "closed"+ | "unknown"+ | "not-run";++export interface HeldRowInfo {+ state: HeldState;+ reviewId: string | null;+}++// A held call's row names the action while it waits, then what became of it.+export function applyHeldOutcome(+ row: ChainRow,+ outcomes: ReadonlyMap<string, HeldOutcome>,+): ChainRow {+ const data = asObject(row.output);+ if (!row.tool || data?.type !== "approval_required") return row;+ const reviewId = str(data, "review_id");+ const tool = heldToolName(data, row.tool);+ const ask = heldAskText(data, tool);+ const didnt = `Didn't ${lowerFirst(ask)}`;+ if (!reviewId) {+ return settle(+ row,+ `Couldn't ask about ${lowerFirst(ask)}`,+ "not-run",+ reviewId,+ );+ }+ const outcome = outcomes.get(row.key);+ if (!outcome) {+ return {+ ...row,+ text: ask,+ requiresAction: true,+ held: { state: "waiting", reviewId },+ };+ }+ // It may have run; claim neither success nor a refusal.+ if (outcome.outcome === "unknown") {+ return settle(row, ask, "unknown", reviewId);+ }+ if (outcome.outcome !== "approved") {+ return settle(row, didnt, outcome.outcome, reviewId);+ }+ const result = asObject(outcome.output);+ const done = getCatalogLabel(tool, row.input, "done")?.text ?? ask;+ // It ran and failed: the normal error row, still marked as approved.+ if (result?.type === "error") {+ return {+ ...settle(row, done, "approved", reviewId),+ state: "error",+ detail: str(result, "message", "error") ?? undefined,+ output: outcome.output,+ };+ }+ return { ...settle(row, done, "approved", reviewId), output: outcome.output };+}++// The held call's own tool, which a capability row names only in its output.+export function heldToolName(+ output: Record<string, unknown>,+ fallback: string,+) {+ return str(output, "tool_name")?.trim() ?? fallback;+}++// The server's words for the call, quoted as every other chain row quotes.+export function heldAskText(output: Record<string, unknown>, toolName: string) {+ const ask = str(output, "ask") ?? fallbackAsk(toolName);+ const object = str(output, "object");+ return object ? `${ask} "${object}"` : ask;+}++function settle(+ row: ChainRow,+ text: string,+ state: HeldState,+ reviewId: string | null,+): ChainRow {+ return { ...row, text, requiresAction: false, held: { state, reviewId } };+}++function lowerFirst(text: string) {+ return text.charAt(0).toLowerCase() + text.slice(1);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.tsindex f50c017255..1d7cf2ebf7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts@@ -1,5 +1,4 @@import type { ToolUIPart } from "ai";-import { beautifyString } from "@/lib/utils";import { getBlockDisplayName } from "../../helpers/toolDisplay";import type { MessagePart } from "../ChatMessagesContainer/helpers";import { EXPERT_ONBOARDING_PART_TYPE } from "../ExpertOnboardingCard/helpers";@@ -10,6 +9,8 @@ import {} from "../../tools/GenericTool/helpers";import { capabilityTargetRow, capabilityTargetToolName } from "./capabilityRow";import { type ChainCategory, getCatalogLabel } from "./toolCatalog";+import type { HeldRowInfo } from "./heldRow";+import { heldAskText, heldToolName } from "./heldRow";import { asObject, integrationIconSrc } from "./resultHelpers";export type ChainRowState = "running" | "done" | "error";@@ -34,6 +35,8 @@ export interface ChainRow {* row line but renders no card, so one delegation never stacks* duplicate cards down the chain. */supersededSubSession?: boolean;+ /** A call the action gate held: whether it waits, ran or was turned down. */+ held?: HeldRowInfo;}const SUB_SESSION_CARD_TOOLS = new Set([@@ -127,12 +130,8 @@ function actionLabel(toolName: string, tool: ToolUIPart): string | null {? `Review ${name.trim()}`: "Review this action";}- if (data.type === "approval_required") {- const name = data.tool_name;- return typeof name === "string" && name.trim()- ? `Approve ${beautifyString(name.trim())}`- : "Approve this action";- }+ if (data.type === "approval_required")+ return heldAskText(data, heldToolName(data, toolName));if (data.type === "suggested_goal") return "Review the suggested goal";return typeof data.message === "string" && data.message.trim()? data.message.trim()diff --git a/autogpt_platform/frontend/src/app/(platform)/home/__tests__/needs-you.test.tsx b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/needs-you.test.tsxindex 34cd7a8c33..4df603f644 100644--- a/autogpt_platform/frontend/src/app/(platform)/home/__tests__/needs-you.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/needs-you.test.tsx@@ -238,3 +238,23 @@ test("offers no approve or decline on a question", async () => {screen.queryByRole("button", { name: /Decline: Maria has a question/ }),).toBeNull();});++test("a held call's row sets its object in semibold, as its card does", async () => {+ mockDashboard([+ {+ ...makeApproval(9),+ title: "Create folder “Q3 reports”",+ headline: { ask: "Create folder", object: "Q3 reports" },+ },+ makeApproval(10),+ ]);++ render(<HomePage />);++ const object = await screen.findByText("Q3 reports");+ expect(object.tagName).toBe("B");+ expect(object.parentElement?.textContent).toBe("Create folder Q3 reports");+ expect(screen.queryByText("Create folder “Q3 reports”")).toBeNull();+ // A row without a headline keeps its plain title.+ expect(screen.getByText("Approve item 10")).toBeDefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/components/AttentionRow.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/components/AttentionRow.tsxindex b1581902a1..3122e84e09 100644--- a/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/components/AttentionRow.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/components/AttentionRow.tsx@@ -56,7 +56,7 @@ export function AttentionRow({ item, isProcessing, onDecision }: Props) {<div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-2"><Text variant="body-medium" tone="primary" className="text-pretty">- {item.title}+ <AttentionTitle item={item} /></Text>{item.priority === "high" ? (<Text@@ -94,3 +94,17 @@ export function AttentionRow({ item, isProcessing, onDecision }: Props) {</article>);}++// A held call's object is set in semibold, as on its card in the chat.+function AttentionTitle({ item }: { item: HomeAttentionItem }) {+ const headline = item.headline;+ if (!headline?.object) return <>{item.title}</>;+ return (+ <>+ {headline.ask}{" "}+ <b className="font-semibold" translate="no">+ {headline.object}+ </b>+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 1668d1f3f3..37c368ea98 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -23758,6 +23758,12 @@"title": "Priority"},"title": { "type": "string", "title": "Title" },+ "headline": {+ "anyOf": [+ { "$ref": "#/components/schemas/HomeHeadline" },+ { "type": "null" }+ ]+ },"description": { "type": "string", "title": "Description" },"why_it_matters": { "type": "string", "title": "Why It Matters" },"expert": {@@ -23983,6 +23989,18 @@"required": ["id", "name", "role", "avatar_url"],"title": "HomeExpert"},+ "HomeHeadline": {+ "properties": {+ "ask": { "type": "string", "title": "Ask" },+ "object": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Object"+ }+ },+ "type": "object",+ "required": ["ask"],+ "title": "HomeHeadline"+ },"HomeRecentWork": {"properties": {"window_started_at": {diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsxnew file mode 100644index 0000000000..b49f63cba1--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsx@@ -0,0 +1,67 @@+"use client";++import { useState } from "react";+import { Button } from "@/components/atoms/Button/Button";+import { FieldValue } from "./components/FieldValue";+import { type FieldSpec, humanize, MAX_FIELDS, visibleKeys } from "./helpers";++interface Props {+ // Labels and order from the tool's or block's input schema.+ fields: FieldSpec[];+ values: Record<string, unknown>;+ // Keys the server shortened; the approval still binds the whole value.+ clipped?: string[];+ // Keys the card's headline already names.+ hiddenKeys?: string[];+ idsWhenAlone?: boolean;+}++export function ApprovalFields({+ fields,+ values,+ clipped = [],+ hiddenKeys = [],+ idsWhenAlone = false,+}: Props) {+ const [showAll, setShowAll] = useState(false);+ const labels = new Map(fields.map((f) => [f.key, f.label]));+ const ordered = visibleKeys({+ keys: [...fields.map((f) => f.key), ...Object.keys(values)],+ values,+ hiddenKeys,+ idsWhenAlone,+ }).map((key) => ({ key, label: labels.get(key) ?? humanize(key) }));++ if (ordered.length === 0) return null;+ const shown = showAll ? ordered : ordered.slice(0, MAX_FIELDS);+ const more = ordered.length - shown.length;++ return (+ <div className="flex flex-col gap-2">+ <dl className="grid grid-cols-1 gap-x-4 gap-y-1.5 text-sm sm:grid-cols-[minmax(5rem,9rem)_minmax(0,1fr)] sm:gap-y-2">+ {shown.map((field) => (+ <div key={field.key} className="contents">+ <dt className="text-zinc-500 sm:pt-px">{field.label}</dt>+ <dd className="mb-1.5 min-w-0 text-zinc-900 [overflow-wrap:anywhere] sm:mb-0">+ <FieldValue+ name={field.key}+ value={values[field.key]}+ clipped={clipped.includes(field.key)}+ />+ </dd>+ </div>+ ))}+ </dl>+ {more > 0 && (+ <Button+ variant="link"+ size="small"+ className="h-auto min-w-0 self-start px-0 py-0 text-sm"+ onClick={() => setShowAll(true)}+ >+ Show {more} more+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/FieldValue.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/FieldValue.tsxnew file mode 100644index 0000000000..56be0dea94--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/FieldValue.tsx@@ -0,0 +1,121 @@+"use client";++import { useState } from "react";+import { Button } from "@/components/atoms/Button/Button";+import { cn } from "@/lib/utils";+import {+ CLAMP_LINES,+ CODE_MAX_LINES,+ fieldKind,+ humanize,+ lineCount,+ listText,+ scalarText,+} from "../helpers";++interface Props {+ name: string;+ value: unknown;+ clipped: boolean;+}++export function FieldValue({ name, value, clipped }: Props) {+ const kind = fieldKind(name, value);+ const shortened = clipped ? (+ <span className="ml-1 text-zinc-400">(shortened)</span>+ ) : null;++ switch (kind) {+ case "secret":+ return (+ <span className="text-zinc-500">+ <span aria-hidden="true">•••••••• </span>hidden+ </span>+ );+ case "code":+ return (+ <pre+ translate="no"+ className="overflow-auto whitespace-pre-wrap rounded-lg bg-zinc-900 px-3 py-2 font-mono text-[0.8125rem] leading-5 text-zinc-100"+ style={{ maxHeight: `${CODE_MAX_LINES * 1.25 + 1}rem` }}+ >+ {String(value)}+ {shortened}+ </pre>+ );+ case "long":+ return <LongText text={String(value)} shortened={shortened} />;+ case "list":+ return (+ <span translate="no">+ {listText(value as unknown[])}+ {shortened}+ </span>+ );+ case "object":+ return (+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 border-l border-zinc-200 pl-3">+ {Object.entries(value as Record<string, unknown>).map(([k, v]) => (+ <div key={k} className="contents">+ <dt className="text-zinc-500">{humanize(k)}</dt>+ <dd className="min-w-0">+ {Array.isArray(v) ? listText(v) : scalarText(v)}+ </dd>+ </div>+ ))}+ </dl>+ );+ case "json":+ return (+ <details className="group">+ <summary className="cursor-pointer text-zinc-600 underline decoration-zinc-300 underline-offset-2 hover:text-zinc-900">+ View as JSON+ </summary>+ <pre className="mt-1.5 max-h-64 overflow-auto rounded-lg bg-zinc-50 px-3 py-2 font-mono text-xs text-zinc-800">+ {JSON.stringify(value, null, 2)}+ </pre>+ </details>+ );+ default:+ return (+ <span>+ {scalarText(value)}+ {shortened}+ </span>+ );+ }+}++interface LongTextProps {+ text: string;+ shortened: React.ReactNode;+}++function LongText({ text, shortened }: LongTextProps) {+ const [open, setOpen] = useState(false);+ return (+ <div className="flex flex-col items-start gap-1">+ <div className="w-full rounded-lg bg-zinc-50 px-3 py-2">+ <p+ className={cn("whitespace-pre-wrap", !open && "line-clamp-3")}+ style={{ WebkitLineClamp: open ? undefined : CLAMP_LINES }}+ >+ {text}+ {shortened}+ </p>+ </div>+ {!open && (+ <Button+ variant="link"+ size="small"+ className="h-auto min-w-0 px-0 py-0 text-sm"+ onClick={() => setOpen(true)}+ >+ {lineCount(text) > CLAMP_LINES+ ? `Show all ${lineCount(text)} lines`+ : "Show all"}+ </Button>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.ts b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.tsnew file mode 100644index 0000000000..7e4b1ac5d5--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.ts@@ -0,0 +1,100 @@+export const REDACTED = "[redacted]";+export const MAX_FIELDS = 6;+export const CLAMP_LINES = 3;+export const CLAMP_CHARS = 280;+export const CODE_MAX_LINES = 12;+export const ARRAY_SHOWN = 3;+export const ARRAY_MAX = 5;++// Arguments whose value is the content, shown as code rather than prose.+const CODE_KEYS = new Set(["command", "code", "script", "source", "sql"]);++export type FieldKind =+ | "secret"+ | "code"+ | "long"+ | "short"+ | "list"+ | "object"+ | "json";++export interface FieldSpec {+ key: string;+ label: string;+}++export function fieldKind(key: string, value: unknown): FieldKind {+ if (value === REDACTED) return "secret";+ if (Array.isArray(value)) {+ return value.every(isScalar) ? "list" : "json";+ }+ if (value && typeof value === "object") {+ return Object.values(value).every(+ (v) => isScalar(v) || (Array.isArray(v) && v.every(isScalar)),+ )+ ? "object"+ : "json";+ }+ const text = String(value);+ if (CODE_KEYS.has(key)) return "code";+ if (text.length > CLAMP_CHARS || lineCount(text) > CLAMP_LINES) return "long";+ return "short";+}++interface VisibleKeysArgs {+ keys: string[];+ values: Record<string, unknown>;+ hiddenKeys: string[];+ // Show ids when nothing else would tell this call from another.+ idsWhenAlone: boolean;+}++export function visibleKeys({+ keys,+ values,+ hiddenKeys,+ idsWhenAlone,+}: VisibleKeysArgs) {+ const present = [...new Set(keys)].filter(+ (key) => !hiddenKeys.includes(key) && hasValue(values[key]),+ );+ const named = present.filter((key) => !isIdKey(key));+ return named.length > 0 || !idsWhenAlone ? named : present;+}++export function isIdKey(key: string) {+ return /(^|_)ids?$/.test(key);+}++function hasValue(value: unknown) {+ if (value === null || value === undefined || value === "") return false;+ if (value === false) return false;+ if (Array.isArray(value)) return value.length > 0;+ if (typeof value === "object") return Object.keys(value).length > 0;+ return true;+}++export function listText(values: unknown[]) {+ if (values.length <= ARRAY_MAX) return values.map(String).join(", ");+ return `${values.slice(0, ARRAY_SHOWN).map(String).join(", ")} +${values.length - ARRAY_SHOWN} more`;+}++export function scalarText(value: unknown) {+ if (typeof value === "boolean") return value ? "Yes" : "No";+ return String(value);+}++export function lineCount(text: string) {+ return text.split("\n").length;+}++export function humanize(key: string) {+ const words = key.replace(/_/g, " ").trim();+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function isScalar(value: unknown) {+ return (+ value === null || ["string", "number", "boolean"].includes(typeof value)+ );+}