AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform/copilot): a held call names the things its IDs point at, with links (#14891)
Reinier van der Leera493930004aa
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex fe759c4560..a41a2824eb 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -59,6 +59,7 @@ from backend.api.features.experts.models import (ExpertSoulFieldsPatch,ExpertSoulUpdate,ExpertTemplate,+ ExpertWorkflowLabel,ExpertWorkflowRef,HireResult,RaiseAttachment,@@ -2155,6 +2156,32 @@ async def remove_workflow(user_id: str, expert_id: str, workflow_id: str) -> lisreturn stopped+async def get_workflow_label(+ user_id: str, workflow_id: str+) -> ExpertWorkflowLabel | None:+ """An installed workflow's name and expert, if *user_id* owns the expert."""+ row = await prisma.models.ExpertWorkflow.prisma().find_first(+ where={+ "id": workflow_id,+ "Expert": {"is": {"ownerUserId": user_id, "isTemplate": False}},+ },+ include={+ "LibraryAgent": {"include": {"AgentGraph": True}},+ "StoreListingVersion": True,+ },+ )+ if row is None:+ return None+ # Named as the roster names it: the listing's title first.+ if row.StoreListingVersion is not None:+ name = row.StoreListingVersion.name+ elif row.LibraryAgent is not None:+ name = _library_agent_labels(row.LibraryAgent)[0]+ else:+ name = None+ return ExpertWorkflowLabel(expert_id=row.expertId, name=name)++async def resolve_expert_for_graph(user_id: str, graph_id: str) -> str | None:"""Expert attribution for a manually scheduled graph.diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.pyindex dc8d7dcb0c..1021edb1b8 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -2843,6 +2843,26 @@ async def test_remove_workflow_detaches_it_from_the_expert(assert library_agent is not None and not library_agent.isDeleted[email protected](loop_scope="session")+async def test_a_workflow_label_is_its_agents_name_for_the_owner_only(+ server: SpinTestServer, test_user+):+ library_agent_id, _ = await _seed_own_library_agent(server, test_user.id)+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(test_user.id, template.id, None)+ installed = await experts_db.install_workflow(+ test_user.id, hired.expert.id, library_agent_id=library_agent_id+ )++ label = await experts_db.get_workflow_label(test_user.id, installed.id)++ assert label is not None+ assert (label.expert_id, label.name) == (hired.expert.id, installed.name)+ assert label.name+ stranger = await _create_seed_user()+ assert await experts_db.get_workflow_label(stranger.id, installed.id) is None++@pytest.mark.asyncio(loop_scope="session")async def test_remove_workflow_unknown_id_raises(server: SpinTestServer, test_user):template = await _seed_template(name="Maria", preload_listings=[])diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pyindex 296f73cc17..e17269b9f0 100644--- a/autogpt_platform/backend/backend/api/features/experts/models.py+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -124,6 +124,13 @@ class ExpertWorkflowRef(BaseModel):integration_providers: list[str] = Field(default_factory=list)+class ExpertWorkflowLabel(BaseModel):+ """What names an installed workflow on an approval card."""++ expert_id: str+ name: str | None++class ExpertIdentity(BaseModel):id: strname: strdiff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.pyindex dfc37c7021..8dcce803d0 100644--- a/autogpt_platform/backend/backend/api/features/home/attention.py+++ b/autogpt_platform/backend/backend/api/features/home/attention.py@@ -96,7 +96,7 @@ def _gate_attention(created_at=created_at,preview=_clip(" · ".join(- f"{field.label}: {_preview_value(gate.arguments[field.key])}"+ f"{field.label}: {_named_value(gate, field.key) or _preview_value(gate.arguments[field.key])}"for field in gate.fieldsif field.key != gate.headline.object_keyand gate.arguments.get(field.key) not in (None, "", [], {})@@ -126,6 +126,16 @@ def _gate_reason(gate: GateReviewPayload) -> str:return f"{AUTOPILOT_NAME} is waiting for your approval."+def _named_value(gate: GateReviewPayload, key: str) -> str | None:+ """An id argument as the names it resolved to, as the card shows it."""+ refs = [ref for ref in gate.references if ref.key == key]+ if not any(ref.name for ref in refs):+ return None+ more = gate.reference_totals.get(key, len(refs)) - len(refs)+ text = ", ".join(ref.name or ref.id for ref in refs)+ return f"{text} +{more} more" if more > 0 else text++def _preview_value(value: object) -> str:"""As the card shows it: a list of names joined, never a Python repr."""if isinstance(value, str):diff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.pyindex 3dab33cd2b..8bd0981fcb 100644--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py@@ -6,6 +6,7 @@ from prisma.enums import ReviewStatusfrom backend.api.features.experts.models import Expert, ExpertWorkflowReffrom backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.constants import AUTOPILOT_NAME+from backend.copilot.gate.references import Referencefrom backend.copilot.gate.review import node_id_for, review_payloadfrom backend.copilot.model import ChatSessionInfo, ChatSessionMetadata, PendingQuestionfrom backend.executor.scheduler import GraphExecutionJobInfo@@ -476,7 +477,7 @@ def _gate_review(**payload_overrides) -> PendingHumanReviewModel:"graph_exec_id": "copilot-session-s1","session_id": "s1","payload": payload,- "instructions": "Create folder “Q3 reports”",+ "instructions": "Create library folder “Q3 reports”",})@@ -491,9 +492,12 @@ def _one(review: PendingHumanReviewModel):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.title == "Create library folder “Q3 reports”"assert item.headline is not None- assert (item.headline.ask, item.headline.object) == ("Create folder", "Q3 reports")+ assert (item.headline.ask, item.headline.object) == (+ "Create library 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.@@ -530,7 +534,7 @@ def test_a_gate_row_from_before_the_headline_falls_back() -> None:update={"payload": {"tool": "create_folder", "arguments": {}}})item = _one(review)- assert item.title == "Create folder “Q3 reports”"+ assert item.title == "Create library folder “Q3 reports”"assert item.headline is Noneassert item.primary_action is not Noneassert item.primary_action.label == "Review"@@ -545,3 +549,46 @@ def test_home_previews_lists_and_flags_as_the_card_does() -> None:],)assert _one(review).preview == "To: [email protected], [email protected] · Notify: Yes"+++def test_home_names_a_held_calls_ids_as_the_card_does() -> None:+ folder = Reference(+ key="folder_id", entity="library_folder", id="f-9", name="Archive"+ )+ agents = [+ Reference(key="agent_ids", entity="library_agent", id=f"a{i}", name=name)+ for i, name in enumerate(["Digest", None, "Triage", "Notes", "Inbox"])+ ]+ payload = review_payload(+ "move_agents_to_folder",+ # A blank is not an id, so it counts neither as shown nor as "more".+ {"agent_ids": ["a0", "", *(f"a{i}" for i in range(1, 7))], "folder_id": "f-9"},+ references=[folder, *agents],+ )+ review = _gate_review().model_copy(update={"payload": payload})++ item = _one(review)++ assert item.title == "Move agents into library folder “Archive”"+ assert item.preview == "Agents: Digest, a1, Triage, Notes, Inbox +2 more"+++def test_a_clipped_id_list_still_counts_every_id() -> None:+ """A long enough list outgrows the per-argument clip, which stores it as a+ string; the total is kept from the raw call."""+ ids = [f"{i:03d}" + "0" * 33 for i in range(120)]+ refs = [+ Reference(key="agent_ids", entity="library_agent", id=id, name=f"Agent {i}")+ for i, id in enumerate(ids[:5])+ ]+ payload = review_payload(+ "move_agents_to_folder",+ {"agent_ids": ids, "folder_id": "f-9"},+ references=refs,+ )+ assert payload["clipped"] == ["agent_ids"]+ review = _gate_review().model_copy(update={"payload": payload})++ assert _one(review).preview == (+ "Agents: Agent 0, Agent 1, Agent 2, Agent 3, Agent 4 +115 more · Folder: f-9"+ )diff --git a/autogpt_platform/backend/backend/copilot/gate/__init__.py b/autogpt_platform/backend/backend/copilot/gate/__init__.pyindex a9c477f7f0..aa4a8c8d8c 100644--- a/autogpt_platform/backend/backend/copilot/gate/__init__.py+++ b/autogpt_platform/backend/backend/copilot/gate/__init__.py@@ -25,6 +25,7 @@ from backend.util.feature_flag import Flag, is_feature_enabledfrom . import chat_rules, heldfrom . import review as review_storefrom .classifier import classify+from .headline import Headlinefrom .policy import (DEFAULT_MODE,AutopilotMode,@@ -71,10 +72,10 @@ class Decision(BaseModel):allowed: boolreason: str = ""review_id: str | None = None+ # The held card's headline, ids resolved, for the chat's own row.+ headline: Headline | None = None# The user approved this exact call on a card, so nothing downstream asks again.approved: bool = False- # The block or workflow the card names, so the chain row names it too.- subject_name: str | None = NoneALLOW = Decision(allowed=True)@@ -191,7 +192,7 @@ async def _park("""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(+ headline = await review_store.open_review(call.review_id,user_id,session,@@ -201,14 +202,12 @@ async def _park(subject,reason_kind=reason_kind,tool_call_id=call.tool_call_id,- ):+ )+ if headline is None:await held.forget(session.session_id, call.review_id)return Decision(allowed=False, reason=_UNRECORDABLE)return Decision(- allowed=False,- reason=reason,- review_id=call.review_id,- subject_name=subject.name if subject is not None else None,+ allowed=False, reason=reason, review_id=call.review_id, headline=headline)diff --git a/autogpt_platform/backend/backend/copilot/gate/gate_test.py b/autogpt_platform/backend/backend/copilot/gate/gate_test.pyindex fff2bd5270..40c5c3c399 100644--- a/autogpt_platform/backend/backend/copilot/gate/gate_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/gate_test.py@@ -13,6 +13,7 @@ import pytestfrom prisma.enums import ReviewStatusfrom backend.copilot.gate import active_mode, chat_rules, check_action, gate_active+from backend.copilot.gate.headline import Headlinefrom backend.copilot.model import (AutopilotMode,ChatMessage,@@ -59,7 +60,10 @@ def clean_session_state():patch(f"{_GATE}.review_store.find_review", AsyncMock(return_value=None)),patch(f"{_GATE}.held.remember", AsyncMock(return_value=True)),patch(f"{_GATE}.held._held", AsyncMock(return_value={})),- patch(f"{_GATE}.review_store.open_review", AsyncMock(return_value=True)),+ patch(+ f"{_GATE}.review_store.open_review",+ AsyncMock(return_value=Headline(ask="Run it")),+ ),patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value=None)),patch(f"{_GATE}.chat_rules.set_ask", AsyncMock()),):@@ -249,7 +253,7 @@ async def test_calls_that_always_run_never_query_the_review_store(async def test_a_call_that_cannot_be_kept_is_not_parked(gate_on, clean_session_state):"""A card whose call is lost could be approved and then run nothing."""- open_review = AsyncMock(return_value=True)+ open_review = AsyncMock(return_value=Headline(ask="Run it"))with (patch(f"{_GATE}.held.remember", AsyncMock(return_value=False)),patch(f"{_GATE}.review_store.open_review", open_review),@@ -265,7 +269,7 @@ async def test_a_call_that_cannot_be_kept_is_not_parked(gate_on, clean_session_sasync def test_an_unrecordable_approval_refuses_rather_than_runs(gate_on, clean_session_state):- with patch(f"{_GATE}.review_store.open_review", AsyncMock(return_value=False)):+ with patch(f"{_GATE}.review_store.open_review", AsyncMock(return_value=None)):decision = await check_action("post_to_chat_platform", {"text": "hi"}, "u", _session())diff --git a/autogpt_platform/backend/backend/copilot/gate/headline.py b/autogpt_platform/backend/backend/copilot/gate/headline.pyindex e8ce08f7c2..d629b388f9 100644--- a/autogpt_platform/backend/backend/copilot/gate/headline.py+++ b/autogpt_platform/backend/backend/copilot/gate/headline.py@@ -5,6 +5,8 @@ from typing import Anyfrom pydantic import BaseModel+from .references import Reference+# 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, ...]]] = {@@ -17,11 +19,11 @@ _ASK: dict[str, tuple[str, tuple[str, ...]]] = {"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", ()),+ "create_folder": ("Create library folder", ("name",)),+ "update_folder": ("Update library folder", ("name",)),+ "move_folder": ("Move library folder", ()),+ "delete_folder": ("Delete library folder", ()),+ "move_agents_to_folder": ("Move agents into library folder", ()),"update_preset": ("Update preset", ("name",)),"delete_preset": ("Delete a preset", ()),"schedule_followup": ("Schedule a follow-up", ("name",)),@@ -46,12 +48,37 @@ _ASK: dict[str, tuple[str, tuple[str, ...]]] = {"message_session": ("Message another chat", ()),"run_sub_session": ("Start a subtask", ()),"delete_skill": ("Delete skill", ("name",)),- "delete_workspace_file": ("Delete file", ("path",)),+ "delete_workspace_file": ("Delete workspace file", ("path",)),"memory_forget_confirm": ("Forget memories", ()),# The card names the block or workflow from the call's subject instead."run_capability": ("Run a block", ()),"run_agent": ("Run a workflow", ()),}+# Tool -> the id whose resolved name is the object when no argument names one.+_OBJECT_ID: dict[str, str] = {+ "edit_agent": "agent_id",+ "update_folder": "folder_id",+ "move_folder": "folder_id",+ "delete_folder": "folder_id",+ "move_agents_to_folder": "folder_id",+ "update_preset": "preset_id",+ "delete_preset": "preset_id",+ "schedule_routine": "routine_id",+ "pause_schedule": "schedule_id",+ "resume_schedule": "schedule_id",+ "delete_schedule": "schedule_id",+ "update_expert": "expert_id",+ "confirm_expert_change": "confirmation_id",+ "confirm_expert_soul_update": "confirmation_id",+ "install_expert_workflow": "library_agent_id",+ "remove_expert_workflow": "workflow_id",+ "grant_expert_credential": "credential_id",+ "revoke_expert_credential": "credential_id",+ "delegate_to_expert": "expert_id",+ "handoff_to_expert": "expert_id",+ "message_session": "session_id",+ "run_sub_session": "sub_autopilot_session_id",+}_MAX_OBJECT_CHARS = 60@@ -66,9 +93,20 @@ class Headline(BaseModel):return f"{self.ask} “{self.object}”" if self.object else self.ask-def headline_for(tool_name: str, args: dict[str, Any]) -> Headline:+def headline_for(+ tool_name: str,+ args: dict[str, Any],+ references: list[Reference] | None = None,+) -> Headline:ask, keys = _ASK.get(tool_name, (f"Run {tool_name.replace('_', ' ')}", ()))- return named(ask, keys, args)+ headline = named(ask, keys, args)+ if headline.object:+ return headline+ id_key = _OBJECT_ID.get(tool_name)+ for ref in references or []:+ if ref.key == id_key and ref.name:+ return _named(ask, ref.key, ref.name)+ return headlinedef named(ask: str, keys: tuple[str, ...], args: dict[str, Any]) -> Headline:@@ -76,16 +114,17 @@ def named(ask: str, keys: tuple[str, ...], args: dict[str, Any]) -> Headline: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 _named(ask, key, value)return Headline(ask=ask)def gated_tools() -> frozenset[str]:return frozenset(_ASK)+++def _named(ask: str, key: str, value: str) -> Headline:+ 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.+ return Headline(ask=ask, object=name, object_key=key if name == value else None)diff --git a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py b/autogpt_platform/backend/backend/copilot/gate/held_db_test.pyindex d4a0b7b506..775f5962fa 100644--- a/autogpt_platform/backend/backend/copilot/gate/held_db_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/held_db_test.py@@ -191,7 +191,7 @@ async def test_a_call_whose_card_could_not_open_leaves_nothing_held():session = await _new_session(test_user_id)- with patch.object(review_store, "open_review", AsyncMock(return_value=False)):+ with patch.object(review_store, "open_review", AsyncMock(return_value=None)):decision = await check_action(_TOOL, {"text": "no card"}, test_user_id, session, tool_call_id="c1")diff --git a/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py b/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.pynew file mode 100644index 0000000000..111853fc50--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py@@ -0,0 +1,339 @@+"""The id-carrying approval cards the frontend's stories and tests render are+built here, by the real resolvers and payload builder over stubbed reads, so+their references cannot drift from what the server stores.++Regenerate with ``UPDATE_CARD_FIXTURE=1``.+"""++import json+import os+from datetime import UTC, datetime+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++from pydantic import SecretStr++from backend.api.features.experts.models import ExpertRoutine, ExpertWorkflowLabel+from backend.api.features.library.model import LibraryFolder+from backend.copilot.gate import references+from backend.copilot.gate.review import review_id_for, review_payload+from backend.copilot.model import ChatSession, ChatSessionInfo+from backend.copilot.tools.expert_proposal import ExpertChangeProposal+from backend.copilot.tools.models import ExpertChangePreview+from backend.data.model import APIKeyCredentials+from backend.data.workspace import WorkspaceFile+from backend.executor.scheduler import GraphExecutionJobInfo+from backend.util.exceptions import NotFoundError++FIXTURE = (+ Path(__file__).parents[4]+ / "frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__"+ / "referenceCards.json"+)+_USER = "user-1"+_FOLDERS = {"f-q3": "Q3 reports", "f-archive": "Archive", "f-finance": "Finance"}+_PARENTS = {"f-q3": "f-finance"}+_AGENTS = {+ "lib-digest": ("Morning digest", "Summarises overnight email and news at 7am."),+ "lib-triage": ("Inbox triage", "Labels and routes new support email."),+ "lib-notes": ("Meeting notes", "Turns call recordings into action items."),+ "lib-invoices": ("Invoice chaser", "Nudges clients about overdue invoices."),+ "lib-leads": ("Lead scorer", "Scores inbound leads against the ICP."),+ "lib-social": ("Social scheduler", "Queues the week's posts."),+}+_WHEN = datetime(2026, 9, 24, 14, 5, tzinfo=UTC)+_SESSION = "session-1"+# The call, as the model sends it, per story.+_CALLS: list[tuple[str, str, dict[str, Any]]] = [+ ("Delete folder", "delete_folder", {"folder_id": "f-q3"}),+ (+ "Move agents",+ "move_agents_to_folder",+ {+ "agent_ids": [+ "lib-digest",+ "lib-gone",+ "lib-triage",+ "lib-notes",+ "lib-invoices",+ "lib-leads",+ "lib-social",+ ],+ "folder_id": "f-archive",+ },+ ),+ ("Pause schedule", "pause_schedule", {"schedule_id": "sch-digest"}),+ ("Hire expert", "hire_expert", {"template_id": "tpl-ada", "name": "Ada"}),+ ("Message chat", "message_session", {"session_id": "s-q3", "message": "Done?"}),+ (+ "Grant credential",+ "grant_expert_credential",+ {"expert_id": "exp-ada", "credential_id": "cred-gh"},+ ),+ ("Edit agent", "edit_agent", {"agent_id": "g-digest"}),+ ("Update template", "update_preset", {"preset_id": "pre-weekly"}),+ ("Delete trigger", "delete_preset", {"preset_id": "pre-inbox"}),+ ("Schedule routine", "schedule_routine", {"routine_id": "rt-close"}),+ (+ "Install workflow",+ "install_expert_workflow",+ {"expert_id": "exp-ada", "store_listing_version_id": "slv-receipts"},+ ),+ ("Remove workflow", "remove_expert_workflow", {"workflow_id": "wf-receipts"}),+ ("Confirm team change", "confirm_expert_change", {"confirmation_id": "cf-1"}),+ (+ "Delete file",+ "delete_workspace_file",+ {"file_id": "file-q3", "path": "/reports/q3-report.pdf"},+ ),+ ("Unresolved id", "delete_preset", {"preset_id": "3f0c9a2e-preset-gone"}),+]+++async def build_cards() -> list[dict[str, Any]]:+ with (+ patch.object(references, "library_db", return_value=_library()),+ patch.object(references, "experts_db", return_value=_experts()),+ patch.object(references, "get_scheduler_client", return_value=_scheduler()),+ patch.object(references, "get_chat_session_metadata", _chat),+ patch.object(references, "IntegrationCredentialsManager", _credentials),+ patch.object(references, "get_workspace_manager", _workspace),+ patch.object(references, "store_db", return_value=_store()),+ patch.object(references, "get_redis_async", _redis),+ ):+ cards = [await _card(*call) for call in _CALLS]+ return json.loads(json.dumps(cards, default=str))+++async def test_the_frontend_reference_fixture_is_what_the_builder_makes():+ cards = await build_cards()+ if os.environ.get("UPDATE_CARD_FIXTURE"):+ FIXTURE.write_text(json.dumps(cards, indent=2, ensure_ascii=False) + "\n")+ assert (+ json.loads(FIXTURE.read_text()) == cards+ ), "the reference-card fixture is stale; rerun with UPDATE_CARD_FIXTURE=1"+++async def _card(story: str, tool: str, args: dict[str, Any]) -> dict[str, Any]:+ session = ChatSession.new(user_id=_USER, dry_run=False).model_copy(+ update={"session_id": _SESSION, "expert_id": "exp-ada"}+ )+ refs = await references.resolve_references(tool, args, _USER, session)+ review_id = review_id_for("session-1", _USER, tool, args)+ return {+ "story": story,+ "review": {+ "node_exec_id": review_id,+ "node_id": review_id.split(":")[0],+ "user_id": _USER,+ "session_id": "s1",+ "graph_exec_id": None,+ "graph_id": None,+ "graph_version": None,+ "payload": review_payload(+ tool,+ args,+ reason="Ask First is on for this chat, so this action needs your approval.",+ mode="ask_first",+ tool_call_id=f"call-{tool}",+ turn=1,+ references=refs,+ ),+ "instructions": tool,+ "editable": False,+ "status": "WAITING",+ },+ }+++def _library() -> MagicMock:+ async def get_folder(folder_id: str, user_id: str) -> LibraryFolder:+ if folder_id not in _FOLDERS:+ raise NotFoundError(f"Folder #{folder_id} not found")+ now = datetime(2026, 9, 24, tzinfo=UTC)+ return LibraryFolder(+ id=folder_id,+ user_id=user_id,+ name=_FOLDERS[folder_id],+ parent_id=_PARENTS.get(folder_id),+ agent_count=4,+ subfolder_count=1,+ created_at=now,+ updated_at=now,+ )++ async def get_library_agent(agent_id: str, user_id: str) -> MagicMock:+ if agent_id not in _AGENTS:+ raise NotFoundError(f"Library agent #{agent_id} not found")+ return _agent(agent_id)++ async def by_graph(user_id: str, graph_id: str) -> MagicMock | None:+ return _agent("lib-digest") if graph_id == "g-digest" else None++ async def get_preset(user_id: str, preset_id: str) -> MagicMock | None:+ return _presets().get(preset_id)++ lib = MagicMock()+ lib.get_folder = AsyncMock(side_effect=get_folder)+ lib.get_library_agent = AsyncMock(side_effect=get_library_agent)+ lib.get_library_agent_by_graph_id = AsyncMock(side_effect=by_graph)+ lib.get_preset = AsyncMock(side_effect=get_preset)+ return lib+++def _agent(agent_id: str) -> MagicMock:+ agent = _named(agent_id, *_AGENTS[agent_id])+ agent.graph_version, agent.folder_name = 3, "Mornings"+ agent.last_run_at = _WHEN if agent_id == "lib-digest" else None+ return agent+++def _preset(id: str, name: str, description: str, webhook_id: str | None) -> MagicMock:+ preset = _named(id, name, description)+ preset.graph_id, preset.webhook_id, preset.is_active = "g-digest", webhook_id, True+ return preset+++def _experts() -> MagicMock:+ experts = MagicMock()+ ada = _template("tpl-ada", "Ada", "Keeps the books balanced.", None, "Finance")+ grace = _template(+ "tpl-grace", "Grace", "Ships on Thursdays.", "Release manager", "Engineering"+ )+ experts.list_templates = AsyncMock(return_value=[ada, grace])+ experts.with_bundled_skills = AsyncMock(+ side_effect=lambda templates, user_id: templates+ )+ hired = _named("exp-ada", "Ada")+ hired.tagline, hired.job_title, hired.role = None, "Bookkeeper", "Finance"+ experts.get_expert = AsyncMock(return_value=hired)+ hired.bio, hired.is_archived = None, False+ hired.avatar_url, hired.color = None, "#0ea5e9"+ routine = ExpertRoutine(+ id="rt-close",+ expert_id="exp-ada",+ title="Month-end close",+ prompt="Reconcile every account against the bank feed, flag anything "+ "over $500 that has no receipt, and draft the close summary for review.",+ crons=["0 9 1 * *"],+ enabled=True,+ )+ experts.list_routines = AsyncMock(return_value=[routine])+ experts.get_workflow_label = AsyncMock(+ return_value=ExpertWorkflowLabel(expert_id="exp-ada", name="Receipt matcher")+ )+ return experts+++def _template(+ id: str, name: str, tagline: str, job_title: str | None, role: str+) -> MagicMock:+ template = _named(id, name)+ template.tagline, template.job_title, template.role = tagline, job_title, role+ template.bio, template.categories = None, [role]+ template.avatar_url, template.color = None, "#7c3aed"+ template.bundled_skills = [MagicMock(title=title) for title in _SKILLS.get(id, [])]+ return template+++_SKILLS = {+ "tpl-ada": ["Month-end close", "Receipt matching", "Cash forecast", "Payroll"],+ "tpl-grace": ["Release notes", "Changelog"],+}+++def _store() -> MagicMock:+ listing = MagicMock(+ agent_name="Receipt matcher",+ creator="ledgerly",+ slug="receipt-matcher",+ sub_heading="Matches card spend to emailed receipts.",+ description="",+ runs=1_204,+ rating=4.6,+ )+ return MagicMock(get_store_agent_by_version_id=AsyncMock(return_value=listing))+++async def _redis() -> MagicMock:+ proposal = ExpertChangeProposal(+ user_id=_USER,+ session_id=_SESSION,+ preview=ExpertChangePreview(+ kind="hire",+ name="Grace",+ role="Engineering",+ job_title="Release manager",+ tagline="Ships on Thursdays.",+ template_id="tpl-grace",+ color="#7c3aed",+ ),+ user_turn_watermark=1,+ )+ return MagicMock(get=AsyncMock(return_value=proposal.model_dump_json()))+++def _scheduler() -> MagicMock:+ job = GraphExecutionJobInfo(+ id="sch-digest",+ name="Daily digest",+ next_run_time="2026-09-25T07:00:00+00:00",+ user_id=_USER,+ graph_id="g-digest",+ graph_version=1,+ cron="0 7 * * *",+ input_data={},+ )+ return MagicMock(get_execution_schedules=AsyncMock(return_value=[job]))+++async def _chat(session_id: str, user_id: str) -> ChatSessionInfo:+ return ChatSessionInfo(+ session_id=session_id,+ user_id=user_id,+ title="Q3 planning",+ usage=[],+ started_at=_WHEN,+ updated_at=_WHEN,+ )+++def _credentials() -> MagicMock:+ creds = APIKeyCredentials(+ id="cred-gh", provider="github", title="GitHub (work)", api_key=SecretStr("x")+ )+ return MagicMock(store=MagicMock(get_creds_by_id=AsyncMock(return_value=creds)))+++async def _workspace(user_id: str, session_id: str) -> MagicMock:+ file = WorkspaceFile(+ id="file-q3",+ workspace_id="ws-1",+ created_at=_WHEN,+ updated_at=_WHEN,+ name="q3-report.pdf",+ path="/reports/q3-report.pdf",+ storage_path="ws-1/file-q3",+ mime_type="application/pdf",+ size_bytes=248_000,+ folder_id="wf-reports",+ )+ return MagicMock(get_file_info=AsyncMock(return_value=file))+++def _named(id: str, name: str, description: str = "") -> MagicMock:+ thing = MagicMock(id=id, description=description)+ thing.name = name+ return thing+++def _presets() -> dict[str, MagicMock]:+ return {+ "pre-weekly": _preset(+ "pre-weekly", "Weekly digest", "The digest, but Mondays only.", None+ ),+ "pre-inbox": _preset(+ "pre-inbox", "New invoice email", "Runs when an invoice lands.", "wh-1"+ ),+ }diff --git a/autogpt_platform/backend/backend/copilot/gate/references.py b/autogpt_platform/backend/backend/copilot/gate/references.pynew file mode 100644index 0000000000..0a58d19fa3--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/gate/references.py@@ -0,0 +1,613 @@+"""What a held call's ids point at: ``folder_id="f-111"`` becomes “Q3 reports”,+linked to its page, resolved once when the call is held and frozen into the card."""++import asyncio+import logging+from datetime import datetime+from typing import Any, Awaitable, Callable, Literal+from urllib.parse import quote, urlencode++from pydantic import BaseModel, field_serializer++from backend.api.features.experts.models import Expert, ExpertTemplate+from backend.api.features.library.model import LibraryAgent, LibraryFolder+from backend.copilot.context import get_workspace_manager+from backend.copilot.model import ChatSession, get_chat_session_metadata+from backend.data.db_accessors import experts_db, library_db, store_db+from backend.data.redis_client import get_redis_async+from backend.executor.scheduler import GraphExecutionJobInfo+from backend.integrations.creds_manager import IntegrationCredentialsManager+from backend.util.clients import get_scheduler_client++logger = logging.getLogger(__name__)++Entity = Literal[+ "library_folder",+ "library_agent",+ "graph",+ "agent_or_graph",+ "preset",+ "schedule",+ "chat_session",+ "expert",+ "expert_or_name",+ "expert_template",+ "expert_workflow",+ "credential",+ "routine",+ "store_listing",+ "workspace_file",+ "team_change",+ "soul_change",+]++# (tool, argument) -> what its id names. None is a decision: not a platform id.+REFERENCES: dict[tuple[str, str], Entity | None] = {+ ("create_agent", "folder_id"): "library_folder",+ ("create_agent", "library_agent_ids"): "library_agent",+ ("customize_agent", "folder_id"): "library_folder",+ ("customize_agent", "library_agent_ids"): "library_agent",+ ("edit_agent", "agent_id"): "agent_or_graph",+ ("edit_agent", "library_agent_ids"): "library_agent",+ ("create_folder", "parent_id"): "library_folder",+ ("create_folder", "icon"): None,+ ("update_folder", "folder_id"): "library_folder",+ ("update_folder", "icon"): None,+ ("move_folder", "folder_id"): "library_folder",+ ("move_folder", "target_parent_id"): "library_folder",+ ("delete_folder", "folder_id"): "library_folder",+ ("move_agents_to_folder", "folder_id"): "library_folder",+ ("move_agents_to_folder", "agent_ids"): "library_agent",+ ("update_preset", "preset_id"): "preset",+ ("delete_preset", "preset_id"): "preset",+ ("pause_schedule", "schedule_id"): "schedule",+ ("resume_schedule", "schedule_id"): "schedule",+ ("delete_schedule", "schedule_id"): "schedule",+ ("schedule_followup", "session_id"): "chat_session",+ ("schedule_routine", "routine_id"): "routine",+ ("schedule_routine", "session_id"): "chat_session",+ ("schedule_routine", "expert_id"): "expert",+ ("setup_agent_webhook_trigger", "library_agent_id"): "library_agent",+ ("setup_agent_webhook_trigger", "graph_id"): "graph",+ ("hire_expert", "template_id"): "expert_template",+ ("update_expert", "expert_id"): "expert",+ ("confirm_expert_change", "confirmation_id"): "team_change",+ ("confirm_expert_soul_update", "confirmation_id"): "soul_change",+ ("install_expert_workflow", "library_agent_id"): "library_agent",+ ("install_expert_workflow", "store_listing_version_id"): "store_listing",+ ("install_expert_workflow", "expert_id"): "expert",+ ("remove_expert_workflow", "workflow_id"): "expert_workflow",+ ("remove_expert_workflow", "library_agent_id"): "library_agent",+ ("remove_expert_workflow", "expert_id"): "expert",+ ("grant_expert_credential", "credential_id"): "credential",+ ("grant_expert_credential", "expert_id"): "expert",+ ("revoke_expert_credential", "credential_id"): "credential",+ ("revoke_expert_credential", "expert_id"): "expert",+ ("delegate_to_expert", "expert_id"): "expert_or_name",+ ("delegate_to_expert", "delegated_session_id"): "chat_session",+ ("handoff_to_expert", "expert_id"): "expert",+ ("message_session", "session_id"): "chat_session",+ ("run_sub_session", "sub_autopilot_session_id"): "chat_session",+ ("delete_skill", "expert_id"): "expert",+ ("delete_workspace_file", "file_id"): "workspace_file",+ ("run_agent", "library_agent_id"): "agent_or_graph",+ ("run_agent", "preset_id"): "preset",+ # Another system's ids, or not ids at all though described as one.+ ("create_feature_request", "existing_issue_id"): None,+ ("edit_chat_platform_message", "channel_id"): None,+ ("edit_chat_platform_message", "ref_id"): None,+ ("memory_forget_confirm", "uuids"): None,+ ("browser_act", "target"): None,+ ("post_to_chat_platform", "channel"): None,+ # A block or MCP server; the card's subject already names it.+ ("run_capability", "id"): None,+}++LOOKUP_SECONDS = 1.0+CARD_SECONDS = 2.0+# Ids of a list resolved for the card; the rest read "+N more".+MAX_LISTED = 5+_MAX_SUMMARY_CHARS = 140+_MAX_DESCRIPTION_CHARS = 240+++class Fact(BaseModel):+ """One short fact; with ``cron`` or ``at`` the card words it for the viewer."""++ text: str+ cron: str | None = None+ # Shown as the label and the time relative to now, e.g. "Last active 5 minutes ago".+ label: str | None = None+ at: datetime | None = None++ # Stored in a JSON payload, so the card always parses one ISO form.+ @field_serializer("at")+ def _iso(self, at: datetime | None) -> str | None:+ return at.isoformat() if at else None+++class Reference(BaseModel):+ key: str+ entity: Entity+ id: str+ # None: unresolved, and the card shows the raw id. href is None then too.+ name: str | None = None+ href: str | None = None+ # The hover card: what family the thing is, its own prose, short facts.+ kind: str | None = None+ description: str | None = None+ meta: list[Fact] = []+ avatar_url: str | None = None+ avatar_color: str | None = None+ skills: list[str] = []+ # The card's facts as one line, for surfaces with room for no more.+ summary: str | None = None+++async def resolve_references(+ tool_name: str, args: dict[str, Any], user_id: str, session: ChatSession+) -> list[Reference]:+ """Every id the call carries, named where its owner can see it; never raises."""+ wanted = wanted_references(tool_name, args)+ if not wanted:+ return []+ call = _Call(user_id=user_id, session=session, args=args)+ try:+ return list(+ await asyncio.wait_for(+ asyncio.gather(*(_resolve(ref, call) for ref in wanted)),+ CARD_SECONDS,+ )+ )+ except asyncio.TimeoutError:+ logger.warning(f"Gate card references for {tool_name} timed out")+ return wanted+++def wanted_references(tool_name: str, args: dict[str, Any]) -> list[Reference]:+ refs: list[Reference] = []+ for (tool, key), entity in REFERENCES.items():+ if tool != tool_name or entity is None:+ continue+ value = args.get(key)+ refs.extend(+ Reference(key=key, entity=entity, id=id)+ for id in listed_ids(value)[:MAX_LISTED]+ )+ return refs+++def listed_ids(value: Any) -> list[str]:+ """The ids an argument holds, blanks and non-strings dropped."""+ values = value if isinstance(value, list) else [value]+ return [v.strip() for v in values if isinstance(v, str) and v.strip()]+++class _Call(BaseModel):+ user_id: str+ session: ChatSession+ args: dict[str, Any]+++class _Found(BaseModel):+ kind: str+ name: str+ href: str | None = None+ description: str | None = None+ meta: list[str | Fact | None] = []+ avatar_url: str | None = None+ avatar_color: str | None = None+ skills: list[str] = []+++async def _resolve(ref: Reference, call: _Call) -> Reference:+ try:+ found = await asyncio.wait_for(+ _RESOLVERS[ref.entity](ref.id, call), LOOKUP_SECONDS+ )+ except asyncio.TimeoutError:+ logger.warning(f"Gate reference {ref.entity} lookup timed out")+ return ref+ except Exception as e:+ # Not found or not owned raise here as often as a real failure does.+ logger.debug("Gate reference %s unresolved: %s", ref.entity, e)+ return ref+ if found is None or not found.name.strip():+ return ref+ facts = [fact for m in found.meta if (fact := _fact(m))]+ # A role and an area can be the same word; say it once.+ meta = [f for i, f in enumerate(facts) if f.text not in {g.text for g in facts[:i]}]+ description = _clip(found.description, _MAX_DESCRIPTION_CHARS)+ return ref.model_copy(+ update={+ "name": " ".join(found.name.split()),+ "href": found.href,+ "kind": found.kind,+ "description": description,+ "meta": meta,+ "avatar_url": found.avatar_url,+ "avatar_color": found.avatar_color or None,+ "skills": found.skills,+ "summary": _one_line(" · ".join(fact.text for fact in meta))+ or _one_line(description),+ }+ )+++async def _library_folder(folder_id: str, call: _Call) -> _Found | None:+ folder = await library_db().get_folder(folder_id, call.user_id)+ parent = await _parent_folder(folder.parent_id, call) if folder.parent_id else None+ return _Found(+ kind="Library folder",+ name=folder.name,+ href=f"/library?{urlencode({'folder': folder.id})}",+ meta=[+ _count(folder.agent_count, "agent"),+ _count(folder.subfolder_count, "subfolder"),+ f"In {parent.name}" if parent else None,+ ],+ )+++async def _library_agent(agent_id: str, call: _Call) -> _Found | None:+ agent = await library_db().get_library_agent(agent_id, call.user_id)+ return _agent(agent)+++async def _graph(graph_id: str, call: _Call) -> _Found | None:+ agent = await library_db().get_library_agent_by_graph_id(call.user_id, graph_id)+ return _agent(agent) if agent else None+++async def _agent_or_graph(agent_id: str, call: _Call) -> _Found | None:+ return await _graph(agent_id, call) or await _library_agent(agent_id, call)+++async def _preset(preset_id: str, call: _Call) -> _Found | None:+ preset = await library_db().get_preset(call.user_id, preset_id)+ if preset is None:+ return None+ agent = await library_db().get_library_agent_by_graph_id(+ call.user_id, preset.graph_id+ )+ # A preset with a webhook lists under Triggers, the rest under Templates.+ kind, tab, item = (+ ("Trigger", "triggers", f"preset:{preset_id}")+ if preset.webhook_id+ else ("Template", "templates", preset_id)+ )+ return _Found(+ kind=kind,+ name=preset.name,+ href=_agent_href(agent.id, activeTab=tab, activeItem=item) if agent else None,+ description=preset.description,+ meta=[+ f"Agent: {agent.name}" if agent else None,+ None if preset.is_active else "Inactive",+ ],+ )+++async def _schedule(schedule_id: str, call: _Call) -> _Found | None:+ # No by-id read exists; include_paused, as the tools list them.+ jobs = await get_scheduler_client().get_execution_schedules(+ user_id=call.user_id, include_paused=True+ )+ job = next((j for j in jobs if j.id == schedule_id), None)+ if job is None:+ return None+ # include_paused lists schedules with no next run.+ when = datetime.fromisoformat(job.next_run_time) if job.next_run_time else None+ href, agent = "/library/followups", None+ if isinstance(job, GraphExecutionJobInfo):+ agent = await library_db().get_library_agent_by_graph_id(+ call.user_id, job.graph_id+ )+ if agent is not None:+ href = _agent_href(agent.id, activeTab="scheduled", activeItem=schedule_id)+ return _Found(+ kind="Schedule",+ name=job.name,+ href=href,+ meta=[+ _cron(job.cron) if job.cron else "Runs once",+ _when("Next run", when) if when else "Paused",+ f"Agent: {agent.name}" if agent else None,+ ],+ )+++async def _chat_session(session_id: str, call: _Call) -> _Found | None:+ meta = await get_chat_session_metadata(session_id, call.user_id)+ if meta is None:+ return None+ return _Found(+ kind="Chat",+ name=meta.title or "Untitled chat",+ href=f"/copilot?{urlencode({'sessionId': session_id})}",+ meta=[+ _when("Started", meta.started_at),+ _when("Last active", meta.updated_at),+ ],+ )+++async def _expert(expert_id: str, call: _Call) -> _Found | None:+ expert = await experts_db().get_expert(+ call.user_id, expert_id, include_workflows=False+ )+ return _teammate(expert) if expert else None+++async def _expert_or_name(reference: str, call: _Call) -> _Found | None:+ # Lazy: the tools package imports the gate.+ from backend.copilot.tools.expert_delegation import resolve_target_expert++ expert = await resolve_target_expert(call.user_id, reference)+ return _teammate(expert) if expert else None+++async def _expert_template(template_id: str, call: _Call) -> _Found | None:+ template = await _template(template_id, call.user_id)+ if template is None:+ return None+ return _Found(+ kind="Expert template",+ name=template.name,+ href=f"/marketplace/experts/{quote(template.id, safe='')}",+ description=template.tagline or template.bio,+ meta=[template.job_title or template.role, _area(template)],+ avatar_url=template.avatar_url,+ avatar_color=template.color,+ skills=[skill.title for skill in template.bundled_skills],+ )+++async def _expert_workflow(workflow_id: str, call: _Call) -> _Found | None:+ label = await experts_db().get_workflow_label(call.user_id, workflow_id)+ if label is None or label.name is None:+ return None+ return _Found(+ kind="Expert workflow", name=label.name, href=_team_href(label.expert_id)+ )+++async def _credential(credential_id: str, call: _Call) -> _Found | None:+ creds = await IntegrationCredentialsManager().store.get_creds_by_id(+ call.user_id, credential_id+ )+ if creds is None:+ return None+ return _Found(+ kind="Credential",+ name=creds.title or str(creds.provider),+ href="/settings/integrations",+ meta=[str(creds.provider), creds.type.replace("_", " ")],+ )+++async def _routine(routine_id: str, call: _Call) -> _Found | None:+ # get_routine is unscoped, so the owner's own listing is the lookup.+ expert_id = call.args.get("expert_id") or call.session.expert_id+ routines = await experts_db().list_routines(call.user_id, expert_id)+ routine = next((r for r in routines if r.id == routine_id), None)+ if routine is None:+ return None+ return _Found(+ kind="Routine",+ name=routine.title,+ href=_team_href(routine.expert_id) if routine.expert_id else None,+ description=routine.prompt,+ meta=[+ *(_cron(cron) for cron in routine.crons),+ _when("Runs", routine.run_at) if routine.run_at else None,+ None if routine.enabled else "Paused",+ ],+ )+++async def _store_listing(version_id: str, call: _Call) -> _Found | None:+ agent = await store_db().get_store_agent_by_version_id(version_id)+ return _Found(+ kind="Marketplace agent",+ name=agent.agent_name,+ href=f"/marketplace/agent/{quote(agent.creator, safe='')}/"+ f"{quote(agent.slug, safe='')}",+ description=agent.sub_heading or agent.description,+ meta=[+ f"By {agent.creator}",+ _count(agent.runs, "run"),+ f"{agent.rating:.1f} ★" if agent.rating else None,+ ],+ )+++async def _workspace_file(file_id: str, call: _Call) -> _Found | None:+ manager = await get_workspace_manager(call.user_id, call.session.session_id)+ file = await manager.get_file_info(file_id)+ if file is None:+ return None+ query = f"?{urlencode({'folder': file.folder_id})}" if file.folder_id else ""+ folder = file.path.rsplit("/", 1)[0].lstrip("/")+ return _Found(+ kind="Workspace file",+ name=file.name,+ href=f"/artifacts{query}",+ meta=[+ file.mime_type,+ _size(file.size_bytes),+ _when("Modified", file.updated_at),+ f"In {folder}" if folder else None,+ ],+ )+++async def _team_change(confirmation_id: str, call: _Call) -> _Found | None:+ # Read without load_bound_proposal, which deletes a proposal it rejects.+ from backend.copilot.tools.expert_proposal import ExpertChangeProposal, proposal_key++ raw = await (await get_redis_async()).get(proposal_key(confirmation_id))+ if raw is None:+ return None+ proposal = ExpertChangeProposal.model_validate_json(raw)+ if not _bound(proposal.user_id, proposal.session_id, call):+ return None+ preview = proposal.preview+ # A hire's skills and area live on its template, as the marketplace card shows them.+ template = (+ await _template(preview.template_id, call.user_id)+ if preview.template_id+ else None+ )+ return _Found(+ kind=_TEAM_CHANGE_KINDS[preview.kind],+ name=preview.name,+ href=_team_href(proposal.expert_id) if proposal.expert_id else None,+ description=preview.tagline or preview.about,+ meta=[preview.job_title or preview.role, _area(template) if template else None],+ avatar_url=preview.avatar_url,+ avatar_color=preview.color,+ skills=[skill.title for skill in template.bundled_skills] if template else [],+ )+++async def _soul_change(confirmation_id: str, call: _Call) -> _Found | None:+ from backend.copilot.tools.soul_proposal import SoulEditProposal, proposal_key++ raw = await (await get_redis_async()).get(proposal_key(confirmation_id))+ if raw is None:+ return None+ proposal = SoulEditProposal.model_validate_json(raw)+ if not _bound(proposal.user_id, proposal.session_id, call):+ return None+ found = await _expert(proposal.expert_id, call)+ return found.model_copy(update={"kind": "Expert update"}) if found else None+++_TEAM_CHANGE_KINDS = {+ "hire": "New hire",+ "raise": "New expert",+ "update": "Expert update",+}++_RESOLVERS: dict[Entity, Callable[[str, _Call], Awaitable[_Found | None]]] = {+ "library_folder": _library_folder,+ "library_agent": _library_agent,+ "graph": _graph,+ "agent_or_graph": _agent_or_graph,+ "preset": _preset,+ "schedule": _schedule,+ "chat_session": _chat_session,+ "expert": _expert,+ "expert_or_name": _expert_or_name,+ "expert_template": _expert_template,+ "expert_workflow": _expert_workflow,+ "credential": _credential,+ "routine": _routine,+ "store_listing": _store_listing,+ "workspace_file": _workspace_file,+ "team_change": _team_change,+ "soul_change": _soul_change,+}+++def _bound(user_id: str, session_id: str, call: _Call) -> bool:+ return user_id == call.user_id and session_id == call.session.session_id+++def _agent_href(library_agent_id: str, **params: str) -> str:+ href = f"/library/agents/{quote(library_agent_id, safe='')}"+ return f"{href}?{urlencode(params)}" if params else href+++def _team_href(expert_id: str) -> str:+ return f"/team/{quote(expert_id, safe='')}"+++async def _parent_folder(parent_id: str, call: _Call) -> LibraryFolder | None:+ try:+ return await library_db().get_folder(parent_id, call.user_id)+ except Exception:+ # The folder itself resolved; a missing parent only drops the line.+ return None+++def _agent(agent: LibraryAgent) -> _Found:+ return _Found(+ kind="Agent",+ name=agent.name,+ href=_agent_href(agent.id),+ description=agent.description,+ meta=[+ f"Version {agent.graph_version}",+ f"In {agent.folder_name}" if agent.folder_name else None,+ _when("Last run", agent.last_run_at) if agent.last_run_at else "Never run",+ ],+ )+++def _teammate(expert: Expert) -> _Found:+ return _Found(+ kind="Expert",+ name=expert.name,+ href=_team_href(expert.id),+ description=expert.tagline or expert.bio,+ meta=[+ expert.job_title or expert.role,+ "Archived" if expert.is_archived else None,+ ],+ avatar_url=expert.avatar_url,+ avatar_color=expert.color,+ )+++async def _template(template_id: str, user_id: str) -> ExpertTemplate | None:+ templates = await experts_db().list_templates()+ template = next((t for t in templates if t.id == template_id), None)+ if template is None:+ return None+ [card] = await experts_db().with_bundled_skills([template], user_id)+ return card+++def _area(template: ExpertTemplate) -> str | None:+ return template.categories[0] if template.categories else None+++def _fact(item: str | Fact | None) -> Fact | None:+ if isinstance(item, Fact):+ return item+ line = _one_line(item)+ return Fact(text=line) if line else None+++def _cron(cron: str) -> Fact:+ return Fact(text=f"Runs {cron}", cron=cron)+++def _when(label: str, at: datetime) -> Fact:+ return Fact(text=f"{label} {at:%Y-%m-%d}", label=label, at=at)+++def _one_line(text: str | None) -> str | None:+ return _clip(text, _MAX_SUMMARY_CHARS)+++def _clip(text: str | None, limit: int) -> str | None:+ line = " ".join((text or "").split())+ if len(line) > limit:+ return line[: limit - 1] + "…"+ return line or None+++def _count(n: int, noun: str) -> str:+ return f"{n:,} {noun}{'' if n == 1 else 's'}"+++def _size(size_bytes: int) -> str:+ size = float(size_bytes)+ for unit in ("B", "KB", "MB"):+ if size < 1024:+ return f"{size:.0f} {unit}"+ size /= 1024+ return f"{size:.1f} GB"diff --git a/autogpt_platform/backend/backend/copilot/gate/references_db_test.py b/autogpt_platform/backend/backend/copilot/gate/references_db_test.pynew file mode 100644index 0000000000..274e73a925--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/gate/references_db_test.py@@ -0,0 +1,61 @@+"""A held call names what its ids point at, read from Postgres as its owner."""++import uuid++import pytest+from prisma.models import PendingHumanReview++from backend.api.features.library.db import create_folder+from backend.copilot.gate import review as review_store+from backend.copilot.gate.references import Fact, Reference, resolve_references+from backend.copilot.model import ChatSession, upsert_chat_session++[email protected](loop_scope="session")+async def test_a_held_delete_names_the_folder_in_the_stored_card(+ setup_test_user, test_user_id+):+ name = f"Q3 reports {uuid.uuid4().hex[:6]}"+ folder = await create_folder(test_user_id, name)+ session = await upsert_chat_session(+ ChatSession.new(user_id=test_user_id, dry_run=False)+ )+ args = {"folder_id": folder.id}+ review_id = review_store.review_id_for(+ session.session_id, test_user_id, "delete_folder", args+ )++ headline = await review_store.open_review(+ review_id, test_user_id, session, "delete_folder", args, "needs you"+ )++ assert headline is not None and headline.text == f"Delete library folder “{name}”"+ row = await PendingHumanReview.prisma().find_unique(where={"nodeExecId": review_id})+ assert row is not None+ stored = review_store.GateReviewPayload.model_validate(row.payload)+ assert stored.references == [+ Reference(+ key="folder_id",+ entity="library_folder",+ id=folder.id,+ name=name,+ href=f"/library?folder={folder.id}",+ kind="Library folder",+ meta=[Fact(text="0 agents"), Fact(text="0 subfolders")],+ summary="0 agents · 0 subfolders",+ )+ ]++[email protected](loop_scope="session")+async def test_another_users_folder_is_never_named(+ setup_test_user, test_user_id, setup_admin_user, admin_user_id+):+ theirs = await create_folder(admin_user_id, f"Private {uuid.uuid4().hex[:6]}")+ session = ChatSession.new(user_id=test_user_id, dry_run=False)++ [ref] = await resolve_references(+ "delete_folder", {"folder_id": theirs.id}, test_user_id, session+ )++ assert (ref.id, ref.name, ref.href) == (theirs.id, None, None)diff --git a/autogpt_platform/backend/backend/copilot/gate/references_test.py b/autogpt_platform/backend/backend/copilot/gate/references_test.pynew file mode 100644index 0000000000..62aafadb18--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/gate/references_test.py@@ -0,0 +1,386 @@+"""A held call's ids named for the card: the table's coverage, each shape of+lookup, and the budget that keeps a slow one from holding the card."""++import asyncio+import re+import time+from datetime import UTC, datetime+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.api.features.library.model import LibraryFolder+from backend.copilot.gate import references+from backend.copilot.gate.headline import _OBJECT_ID, gated_tools, headline_for+from backend.copilot.gate.references import (+ REFERENCES,+ Fact,+ Reference,+ resolve_references,+ wanted_references,+)+from backend.copilot.gate.review import open_review, review_payload+from backend.copilot.model import ChatSession+from backend.executor.scheduler import GraphExecutionJobInfo+from backend.util.exceptions import NotFoundError++# The survey's definition of an id-shaped input: its name, or its description.+_ID_NAME = re.compile(r"(^|_)(ids?|uuids?)$|Ids?$")+_ID_WORD = re.compile(r"\b(id|ID|ids|IDs|uuid|UUID|identifier)\b")+++def test_every_id_shaped_input_of_a_gated_tool_has_a_decided_row():+ """A new tool's id must not fall back to a raw uuid unnoticed."""+ from backend.copilot.tools import get_tool++ missing = []+ for tool_name in sorted(gated_tools()):+ tool = get_tool(tool_name)+ assert tool is not None, tool_name+ for key, spec in (tool.parameters.get("properties") or {}).items():+ shaped = _ID_NAME.search(key) or _ID_WORD.search(+ spec.get("description") or ""+ )+ if shaped and (tool_name, key) not in REFERENCES:+ missing.append(f"{tool_name}.{key}")+ assert missing == [], "add a row (or a None row) to gate/references.py"+++def test_every_row_names_a_gated_tool_and_every_entity_a_resolver():+ assert {tool for tool, _ in REFERENCES} <= gated_tools()+ entities = {entity for entity in REFERENCES.values() if entity}+ assert entities == set(references._RESOLVERS)+++def test_every_headline_id_is_one_the_table_resolves():+ for tool, key in _OBJECT_ID.items():+ assert REFERENCES.get((tool, key)), f"{tool}.{key}"+++async def test_a_single_id_resolves_to_its_name_and_page():+ lib = _library(folders={"f-111": "Q3 reports"})+ with patch.object(references, "library_db", return_value=lib):+ [ref] = await resolve_references(+ "delete_folder", {"folder_id": "f-111"}, "user-1", _session()+ )++ assert ref == Reference(+ key="folder_id",+ entity="library_folder",+ id="f-111",+ name="Q3 reports",+ href="/library?folder=f-111",+ kind="Library folder",+ meta=[Fact(text="0 agents"), Fact(text="0 subfolders")],+ summary="0 agents · 0 subfolders",+ )+ lib.get_folder.assert_awaited_once_with("f-111", "user-1")+++async def test_an_id_that_does_not_resolve_keeps_the_raw_id_and_no_link():+ """Not found and not owned look the same: the id, never a broken link."""+ lib = _library(folders={})+ with patch.object(references, "library_db", return_value=lib):+ [ref] = await resolve_references(+ "delete_folder", {"folder_id": "f-gone"}, "user-1", _session()+ )++ assert (ref.id, ref.name, ref.href) == ("f-gone", None, None)+++async def test_a_list_resolves_each_element_up_to_the_cap():+ lib = _library(agents={f"a{i}": f"Agent {i}" for i in range(7) if i != 1})+ args = {"agent_ids": ["a0", "", *(f"a{i}" for i in range(1, 7))], "folder_id": None}+ with patch.object(references, "library_db", return_value=lib):+ refs = await resolve_references(+ "move_agents_to_folder", args, "user-1", _session()+ )++ assert [(r.id, r.name) for r in refs] == [+ ("a0", "Agent 0"),+ ("a1", None),+ ("a2", "Agent 2"),+ ("a3", "Agent 3"),+ ("a4", "Agent 4"),+ ]+ assert refs[0].href == "/library/agents/a0"+ assert lib.get_library_agent.await_count == references.MAX_LISTED+++async def test_one_slow_lookup_is_cut_at_its_own_budget_and_the_rest_still_resolve():+ """A hung query must neither hold the card nor cost the other names."""+ lib = _library(folders={"f-dest": "Archive"})+ lib.get_folder = AsyncMock(side_effect=_folder_or_hang({"f-dest": "Archive"}))+ args = {"folder_id": "f-slow", "target_parent_id": "f-dest"}+ with (+ patch.object(references, "library_db", return_value=lib),+ patch.object(references, "LOOKUP_SECONDS", 0.05),+ patch.object(references, "CARD_SECONDS", 1.0),+ ):+ refs = await resolve_references("move_folder", args, "user-1", _session())++ assert [(r.key, r.name) for r in refs] == [+ ("folder_id", None),+ ("target_parent_id", "Archive"),+ ]+++async def test_the_card_as_a_whole_is_cut_at_its_budget():+ lib = _library(folders={})+ lib.get_folder = AsyncMock(side_effect=_folder_or_hang({}))+ with (+ patch.object(references, "library_db", return_value=lib),+ patch.object(references, "LOOKUP_SECONDS", 30.0),+ patch.object(references, "CARD_SECONDS", 0.05),+ ):+ started = time.monotonic()+ [ref] = await resolve_references(+ "delete_folder", {"folder_id": "f-slow"}, "user-1", _session()+ )++ assert time.monotonic() - started < 5+ assert (ref.id, ref.name) == ("f-slow", None)+++def test_an_external_id_is_never_looked_up():+ assert (+ wanted_references("create_feature_request", {"existing_issue_id": "L-1"}) == []+ )+ assert wanted_references("memory_forget_confirm", {"uuids": ["u1", "u2"]}) == []+++def test_the_headline_takes_the_resolved_name_as_its_object():+ folder = Reference(+ key="folder_id", entity="library_folder", id="f-1", name="Q3 reports"+ )+ headline = headline_for("delete_folder", {"folder_id": "f-1"}, [folder])++ assert headline.text == "Delete library folder “Q3 reports”"+ # The card does not list the folder a second time.+ assert headline.object_key == "folder_id"+ unresolved = folder.model_copy(update={"name": None})+ assert (+ headline_for("delete_folder", {}, [unresolved]).text == "Delete library folder"+ )+++def test_a_name_the_call_carries_wins_over_the_resolved_one():+ """``update_folder.name`` is the NEW name, which is what the user approves."""+ old = Reference(key="folder_id", entity="library_folder", id="f-1", name="Old")+ headline = headline_for("update_folder", {"folder_id": "f-1", "name": "New"}, [old])+ assert headline.text == "Update library folder “New”"+++def test_the_payload_freezes_the_references_and_the_named_headline():+ ref = Reference(+ key="schedule_id",+ entity="schedule",+ id="sch-1",+ name="Daily digest",+ href="/library/followups",+ )+ payload = review_payload(+ "pause_schedule", {"schedule_id": "sch-1"}, references=[ref]+ )++ assert payload["references"] == [ref.model_dump()]+ assert payload["headline"] == {+ "ask": "Pause a schedule",+ "object": "Daily digest",+ "object_key": "schedule_id",+ }+++async def test_holding_a_call_resolves_its_ids_into_the_stored_card():+ lib = _library(folders={"f-111": "Q3 reports"})+ reviews = MagicMock(get_or_create_human_review=AsyncMock())+ session = ChatSession.new(user_id="user-1", dry_run=False)+ with (+ patch.object(references, "library_db", return_value=lib),+ patch("backend.copilot.gate.review.review_db", return_value=reviews),+ ):+ headline = await open_review(+ "rid", "user-1", session, "delete_folder", {"folder_id": "f-111"}, ""+ )++ assert (+ headline is not None and headline.text == "Delete library folder “Q3 reports”"+ )+ stored = reviews.get_or_create_human_review.await_args.kwargs+ assert stored["message"] == "Delete library folder “Q3 reports”"+ assert stored["input_data"]["references"][0]["name"] == "Q3 reports"+++ "owner, session_id, expected",+ [+ ("user-1", "s-mine", "Ada"),+ ("user-2", "s-mine", None),+ ("user-1", "s-other", None),+ ],+)+async def test_a_pending_team_change_is_named_only_in_its_own_chat(+ owner, session_id, expected+):+ from backend.copilot.tools.expert_proposal import ExpertChangeProposal+ from backend.copilot.tools.models import ExpertChangePreview++ proposal = ExpertChangeProposal(+ user_id=owner,+ session_id=session_id,+ preview=ExpertChangePreview(kind="hire", name="Ada"),+ )+ redis = MagicMock(get=AsyncMock(return_value=proposal.model_dump_json()))+ session = ChatSession.new(user_id="user-1", dry_run=False)+ session.session_id = "s-mine"+ with patch.object(references, "get_redis_async", AsyncMock(return_value=redis)):+ [ref] = await resolve_references(+ "confirm_expert_change", {"confirmation_id": "c-1"}, "user-1", session+ )++ assert ref.name == expected+ # Read only: a proposal it will not name is left for the tool to refuse.+ redis.delete.assert_not_called()+++def _session() -> ChatSession:+ return ChatSession.new(user_id="user-1", dry_run=False)+++def _library(+ folders: dict[str, str] | None = None, agents: dict[str, str] | None = None+):+ folders, agents = folders or {}, agents or {}++ async def get_folder(folder_id: str, user_id: str):+ if folder_id not in folders:+ raise NotFoundError(f"Folder #{folder_id} not found")+ return _folder(folder_id, user_id, folders[folder_id])++ async def get_library_agent(agent_id: str, user_id: str):+ if agent_id not in agents:+ raise NotFoundError(f"Library agent #{agent_id} not found")+ agent = MagicMock(id=agent_id)+ agent.name = agents[agent_id]+ agent.description = ""+ agent.graph_version, agent.folder_name, agent.last_run_at = 1, None, None+ return agent++ lib = MagicMock()+ lib.get_folder = AsyncMock(side_effect=get_folder)+ lib.get_library_agent = AsyncMock(side_effect=get_library_agent)+ return lib+++def _folder_or_hang(folders: dict[str, str]):+ async def get_folder(folder_id: str, user_id: str):+ if folder_id not in folders:+ await asyncio.Event().wait()+ return _folder(folder_id, user_id, folders[folder_id])++ return get_folder+++def _folder(folder_id: str, user_id: str, name: str) -> LibraryFolder:+ now = datetime.now(UTC)+ return LibraryFolder(+ id=folder_id, user_id=user_id, name=name, created_at=now, updated_at=now+ )+++ "text, expected",+ [+ (" Sends the\n morning digest ", "Sends the morning digest"),+ ("x" * 200, "x" * 139 + "…"),+ (" ", None),+ (None, None),+ ],+)+def test_a_summary_is_one_short_line_or_none(text, expected):+ assert references._one_line(text) == expected+++async def test_a_resolved_agent_carries_its_card_for_the_hover():+ ref = await _resolved_agent(description="Sends the morning digest")++ assert (ref.kind, ref.name, ref.description) == (+ "Agent",+ "Digest",+ "Sends the morning digest",+ )+ assert [fact.text for fact in ref.meta] == ["Version 1", "Never run"]+ assert ref.summary == "Version 1 · Never run"+++async def test_a_long_description_is_capped_for_the_card():+ ref = await _resolved_agent(description="word " * 100)++ assert ref.description is not None+ assert len(ref.description) == 240 and ref.description.endswith("…")+++async def test_without_facts_the_summary_is_the_description():+ lib = MagicMock()+ lib.get_preset = AsyncMock(+ return_value=MagicMock(+ description="Posts at noon", webhook_id=None, is_active=True, graph_id="g"+ )+ )+ lib.get_preset.return_value.name = "Noon post"+ lib.get_library_agent_by_graph_id = AsyncMock(return_value=None)+ with patch.object(references, "library_db", return_value=lib):+ [ref] = await resolve_references(+ "delete_preset", {"preset_id": "p-1"}, "user-1", _session()+ )++ assert (ref.kind, ref.meta, ref.summary) == ("Template", [], "Posts at noon")+++async def _resolved_agent(description: str) -> Reference:+ lib = _library(agents={"a0": "Digest"})+ agent = await lib.get_library_agent("a0", "user-1")+ agent.description = description+ lib.get_library_agent = AsyncMock(return_value=agent)+ with patch.object(references, "library_db", return_value=lib):+ [ref] = await resolve_references(+ "move_agents_to_folder", {"agent_ids": ["a0"]}, "user-1", _session()+ )+ return ref+++ "next_run, expected",+ [+ ("2026-09-25T07:00:00+00:00", "Runs 0 7 * * * · Next run 2026-09-25"),+ ("", "Runs 0 7 * * * · Paused"),+ ],+)+async def test_a_schedule_summary_says_when_it_runs_next_or_that_it_is_paused(+ next_run, expected+):+ job = GraphExecutionJobInfo(+ id="sch-1",+ name="Daily digest",+ next_run_time=next_run,+ user_id="user-1",+ graph_id="g-1",+ graph_version=1,+ cron="0 7 * * *",+ input_data={},+ )+ scheduler = MagicMock(get_execution_schedules=AsyncMock(return_value=[job]))+ lib = MagicMock(get_library_agent_by_graph_id=AsyncMock(return_value=None))+ with (+ patch.object(references, "get_scheduler_client", return_value=scheduler),+ patch.object(references, "library_db", return_value=lib),+ ):+ [ref] = await resolve_references(+ "pause_schedule", {"schedule_id": "sch-1"}, "user-1", _session()+ )++ assert (ref.name, ref.summary) == ("Daily digest", expected)+ # The card words the cadence and the next run itself, from the raw values.+ assert ref.meta[0].cron == "0 7 * * *"+ if next_run:+ assert ref.meta[1].at == datetime.fromisoformat(next_run)diff --git a/autogpt_platform/backend/backend/copilot/gate/review.py b/autogpt_platform/backend/backend/copilot/gate/review.pyindex 9e7f8e44d7..52060898d3 100644--- a/autogpt_platform/backend/backend/copilot/gate/review.py+++ b/autogpt_platform/backend/backend/copilot/gate/review.py@@ -30,6 +30,7 @@ from backend.data.db_accessors import review_dbfrom .headline import Headline, headline_forfrom .policy import DEFAULT_MODE, effect_for, is_irreversible+from .references import Reference, listed_ids, resolve_referencesif TYPE_CHECKING:from .subject import Subject as GateSubject@@ -67,6 +68,10 @@ class GateReviewPayload(BaseModel):arguments: dict[str, Any]clipped: list[str] = []fields: list[FieldLabel] = []+ # What the call's ids name, as they were when it was held.+ references: list[Reference] = []+ # Ids per argument before clipping, so a long list still says "+N more".+ reference_totals: dict[str, int] = {}tool_call_id: str = ""turn: int = 0mode: str | None = None@@ -115,6 +120,7 @@ def review_payload(mode: str | None = None,tool_call_id: str = "",turn: int = 0,+ references: list[Reference] | None = None,) -> dict[str, Any]:"""The subject is kept as decided when the card opened: what the user saw,not a recomputation over a tree that may have moved since."""@@ -132,6 +138,11 @@ def review_payload(arguments=shown,clipped=[key for key in shown if shown[key] is not redacted[key]],fields=_field_labels(tool_name, shown),+ references=references or [],+ reference_totals={+ key: len(listed_ids(args.get(key)))+ for key in {ref.key for ref in references or []}+ },tool_call_id=tool_call_id,turn=turn,mode=mode,@@ -142,7 +153,7 @@ def review_payload(headline=(Headline(ask="Run", object=subject.name)if subject is not None- else headline_for(tool_name, args)+ else headline_for(tool_name, args, references)),).model_dump()@@ -209,21 +220,33 @@ async def open_review(subject: "GateSubject | None" = None,reason_kind: ReasonKind = "mode",tool_call_id: str = "",-) -> bool:- """Park the call for approval. False means nothing was recorded."""- payload = review_payload(- tool_name,- args,- subject,- reason=reason,- reason_kind=reason_kind,- mode=session.metadata.autopilot_mode or DEFAULT_MODE,- tool_call_id=tool_call_id,- turn=turn_of(session),- )- return await open_review_row(- review_id, user_id, session, payload, payload_headline(payload)- )+) -> Headline | None:+ """Park the call for approval; the card's headline, or None if nothing was+ recorded."""+ try:+ references = await resolve_references(tool_name, args, user_id, session)+ payload = review_payload(+ tool_name,+ args,+ subject,+ reason=reason,+ reason_kind=reason_kind,+ mode=session.metadata.autopilot_mode or DEFAULT_MODE,+ tool_call_id=tool_call_id,+ turn=turn_of(session),+ references=references,+ )+ except Exception:+ logger.warning(+ f"Gate could not build a review for {tool_name} in session "+ f"{session.session_id}",+ exc_info=True,+ )+ return None+ headline = Headline.model_validate(payload["headline"])+ if not await open_review_row(review_id, user_id, session, payload, headline.text):+ return None+ return headlineasync def open_review_row(@@ -307,7 +330,10 @@ def _field_labels(tool_name: str, shown: dict[str, Any]) -> list[FieldLabel]:def _humanize(key: str) -> str:- words = key.removesuffix("_id").replace("_", " ").strip()+ # agent_ids -> "Agents": the card shows names there, not ids.+ plural = key.endswith("_ids")+ words = key.removesuffix("_ids").removesuffix("_id").replace("_", " ").strip()+ words += "s" if plural else ""return words[:1].upper() + words[1:]diff --git a/autogpt_platform/backend/backend/copilot/gate/review_test.py b/autogpt_platform/backend/backend/copilot/gate/review_test.pyindex dab669f40a..3e6f45dad4 100644--- a/autogpt_platform/backend/backend/copilot/gate/review_test.py+++ b/autogpt_platform/backend/backend/copilot/gate/review_test.py@@ -98,7 +98,7 @@ def test_the_headline_names_the_action_and_its_object():"create_folder", {"name": "Q3 reports"}, reason="Ignore me")["headline"]assert headline == {- "ask": "Create folder",+ "ask": "Create library folder","object": "Q3 reports","object_key": "name",}@@ -106,7 +106,7 @@ def test_the_headline_names_the_action_and_its_object():"Create teammate “Ada”")assert headline_for("delete_folder", {"folder_id": "f1"}).text == (- "Delete a folder"+ "Delete library folder")assert headline_for("create_folder", {"name": "x" * 100}).text.endswith("…”")diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.pyindex 55f62f03db..8aa32ed7f1 100644--- a/autogpt_platform/backend/backend/copilot/tools/base.py+++ b/autogpt_platform/backend/backend/copilot/tools/base.py@@ -24,6 +24,7 @@ from .models import ()if TYPE_CHECKING:+ from backend.copilot.gate.headline import Headlinefrom backend.copilot.gate.subject import Subjectlogger = logging.getLogger(__name__)@@ -568,7 +569,7 @@ class BaseTool:decision.reason,review_id=decision.review_id,args=kwargs,- subject_name=decision.subject_name,+ headline=decision.headline,),False,)@@ -645,16 +646,12 @@ class BaseTool:reason: str,review_id: str | None = None,args: dict[str, Any] | None = None,- subject_name: str | None = None,+ headline: "Headline | None" = None,) -> StreamToolOutputAvailable:from backend.copilot.gate import refusal_message- from backend.copilot.gate.headline import Headline, headline_for+ from backend.copilot.gate.headline import headline_for- headline = (- Headline(ask="Run", object=subject_name)- if subject_name- else headline_for(self.name, args or {})- )+ headline = headline or headline_for(self.name, args or {})return StreamToolOutputAvailable(toolCallId=tool_call_id,toolName=self.name,diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.pyindex 66746b38ee..9c545d1c55 100644--- a/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/gate_mcp_test.py@@ -14,6 +14,7 @@ import pytestfrom prisma.enums import ReviewStatusfrom backend.copilot.gate import chat_rules+from backend.copilot.gate.headline import Headlinefrom backend.copilot.gate.review import payload_headline, review_payloadfrom backend.copilot.model import AutopilotMode, ChatSession, ChatSessionMetadatafrom backend.copilot.tools.models import MCPToolOutputResponse@@ -55,7 +56,7 @@ def gate():"""The gate on, no approval on record, chat rules on a fresh store."""store = SimpleNamespace(find_review=AsyncMock(return_value=None),- open_review=AsyncMock(return_value=True),+ open_review=AsyncMock(side_effect=_opened),consume=AsyncMock(return_value=True),own_review=AsyncMock(return_value="copilot-mcp-x:1"),classify=AsyncMock(return_value=(True, "")),@@ -262,3 +263,10 @@ async def test_flag_off_the_verb_heuristic_decides_as_before(ran, server, tool,await _call(_session(), server, tool)assert own_review.await_count == int(pauses)assert ran.await_count == int(not pauses)+++async def _opened(+ review_id, user_id, session, tool_name, args, reason, subject=None, **_+) -> Headline:+ # The headline the real card stores, so the chat row names what it names.+ return Headline.model_validate(review_payload(tool_name, args, subject)["headline"])diff --git a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.pyindex a1d11f4246..243b1f0f37 100644--- a/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/gate_subject_test.py@@ -28,7 +28,9 @@ from backend.blocks.io import AgentInputBlock, AgentOutputBlockfrom backend.blocks.search import GetWikipediaSummaryBlockfrom backend.blocks.sql_query_block import SQLQueryBlockfrom backend.copilot.gate.effects import block_effect, graph_effect+from backend.copilot.gate.headline import Headlinefrom backend.copilot.gate.policy import Effect+from backend.copilot.gate.review import review_payloadfrom backend.copilot.gate.subject import workflow_subjectfrom backend.copilot.model import AutopilotMode, ChatSession, ChatSessionMetadatafrom backend.copilot.tools.models import BlockOutputResponse, ErrorResponse@@ -58,7 +60,7 @@ def gate():"""The gate on, no approval on record, nothing rejected in this chat."""store = SimpleNamespace(find_review=AsyncMock(return_value=None),- open_review=AsyncMock(return_value=True),+ open_review=AsyncMock(side_effect=_opened),consume=AsyncMock(return_value=True),)with (@@ -677,3 +679,10 @@ async def test_a_workflow_called_without_its_inputs_asks_nothing(gate):)gate.open_review.assert_not_awaited()run.assert_awaited_once()+++async def _opened(+ review_id, user_id, session, tool_name, args, reason, subject=None, **_+) -> Headline:+ # The headline the real card stores, so the chat row names what it names.+ return Headline.model_validate(review_payload(tool_name, args, subject)["headline"])diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex eb81ed34bd..2b44c91777 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -15,6 +15,7 @@ from backend.api.features.library.db import (create_library_agent,create_preset,delete_folder,+ get_folder,get_folder_agents_map,get_folder_tree,get_library_agent,@@ -46,6 +47,7 @@ from backend.api.features.search.hybrid_search import unified_hybrid_searchfrom backend.api.features.store.db import (get_agent,get_available_graph,+ get_store_agent_by_version_id,get_store_agent_details,get_store_agents,)@@ -399,6 +401,7 @@ class DatabaseManager(AppService):create_folder = _(create_folder)list_folders = _(list_folders)+ get_folder = _(get_folder)get_folder_tree = _(get_folder_tree)update_folder = _(update_folder)move_folder = _(move_folder)@@ -416,6 +419,7 @@ class DatabaseManager(AppService):# ============ Store ============ #get_store_agents = _(get_store_agents)get_store_agent_details = _(get_store_agent_details)+ get_store_agent_by_version_id = _(get_store_agent_by_version_id)get_agent = _(get_agent)get_available_graph = _(get_available_graph)@@ -566,12 +570,14 @@ class DatabaseManager(AppService):remove_expert_skill_name = _(experts_db.remove_expert_skill_name)install_workflow = _(experts_db.install_workflow)remove_workflow = _(experts_db.remove_workflow)+ get_workflow_label = _(experts_db.get_workflow_label)grant_expert_credentials = _(expert_credentials.grant_expert_credentials)revoke_expert_credential = _(expert_credentials.revoke_expert_credential)list_expert_credentials = _(expert_credentials.list_expert_credentials)# Hire / raise from the copilot chat tools, plus the counts their# preview step uses to refuse a change that could never land.list_templates = _(experts_db.list_templates)+ with_bundled_skills = _(experts_db.with_bundled_skills)hire_expert = _(experts_db.hire_expert)expert_setup_status = _(experts_db.expert_setup_status)create_raised_expert = _(experts_db.create_raised_expert)@@ -845,6 +851,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ Library Folders ============ #create_folder = d.create_folderlist_folders = d.list_folders+ get_folder = d.get_folderget_folder_tree = d.get_folder_treeupdate_folder = d.update_foldermove_folder = d.move_folder@@ -862,6 +869,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ Store ============ #get_store_agents = d.get_store_agentsget_store_agent_details = d.get_store_agent_details+ get_store_agent_by_version_id = d.get_store_agent_by_version_idget_agent = d.get_agentget_available_graph = d.get_available_graph@@ -977,10 +985,12 @@ class DatabaseManagerAsyncClient(AppServiceClient):remove_expert_skill_name = d.remove_expert_skill_nameinstall_workflow = d.install_workflowremove_workflow = d.remove_workflow+ get_workflow_label = d.get_workflow_labelgrant_expert_credentials = d.grant_expert_credentialsrevoke_expert_credential = d.revoke_expert_credentiallist_expert_credentials = d.list_expert_credentialslist_templates = d.list_templates+ with_bundled_skills = d.with_bundled_skillshire_expert = d.hire_expertexpert_setup_status = d.expert_setup_statuscreate_raised_expert = d.create_raised_expertdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsxindex 42c212f12d..20ede2cc98 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx@@ -16,6 +16,7 @@ import {heldRead,heldReview,mail,+ referenceCard,mcpTool,realCardSchemaHandler,realCards,@@ -124,6 +125,67 @@ export const IdentifiedOnlyById: Story = {args: queueOf([deleteFolder("f1", "f-111"), deleteFolder("f2", "f-222")]),};+// Ids the server resolved to names and pages when the call was held.+export const NamedFolder: Story = {+ args: queueOf([referenceCard("Delete folder")]),+};++export const NamedAgentList: Story = {+ args: queueOf([referenceCard("Move agents")]),+};++export const NamedSchedule: Story = {+ args: queueOf([referenceCard("Pause schedule")]),+};++export const NamedTemplate: Story = {+ args: queueOf([referenceCard("Hire expert")]),+};++export const NamedChat: Story = {+ args: queueOf([referenceCard("Message chat")]),+};++export const NamedCredential: Story = {+ args: queueOf([referenceCard("Grant credential")]),+};++export const NamedAgent: Story = {+ args: queueOf([referenceCard("Edit agent")]),+};++export const NamedTemplatePreset: Story = {+ args: queueOf([referenceCard("Update template")]),+};++export const NamedTrigger: Story = {+ args: queueOf([referenceCard("Delete trigger")]),+};++export const NamedRoutine: Story = {+ args: queueOf([referenceCard("Schedule routine")]),+};++export const NamedMarketplaceAgent: Story = {+ args: queueOf([referenceCard("Install workflow")]),+};++export const NamedWorkflow: Story = {+ args: queueOf([referenceCard("Remove workflow")]),+};++export const NamedTeamChange: Story = {+ args: queueOf([referenceCard("Confirm team change")]),+};++export const NamedFile: Story = {+ args: queueOf([referenceCard("Delete file")]),+};++export const UnresolvedId: Story = {+ args: queueOf([referenceCard("Unresolved id")]),+};+export const FiveWaiting: Story = {args: queueOf([heldReview({@@ -168,7 +230,7 @@ const HELD_PART = (id: string, name: string): MessagePart =>type: "approval_required",tool_name: "create_folder",review_id: `copilot-node-gate-create_folder:${id}`,- ask: "Create folder",+ ask: "Create library folder",object: name,},}) as MessagePart;@@ -192,7 +254,7 @@ export const ChainRows: StoryObj = {type: "approval_required",tool_name: "create_folder",review_id: null,- ask: "Create folder",+ ask: "Create library folder",},} as MessagePart,];@@ -319,7 +381,7 @@ function homeRow(export const HomeRowBefore: StoryObj = {render: () =>homeRow(- "Create folder — Ask First is on for this chat, so this action needs your approval.",+ "Create library folder — Ask First is on for this chat, so this action needs your approval.","Otto is waiting for your approval.","Review",),@@ -328,10 +390,10 @@ export const HomeRowBefore: StoryObj = {export const HomeRowAfter: StoryObj = {render: () =>homeRow(- "Create folder “Q3 reports”",+ "Create library folder “Q3 reports”","Otto is waiting for your approval.","Open chat",- { ask: "Create folder", object: "Q3 reports" },+ { ask: "Create library folder", object: "Q3 reports" },),};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsxindex b9c9a6da61..c74b074296 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/ApprovalQueue.test.tsx@@ -61,7 +61,7 @@ test("the headline names the action and its argument is not repeated below", asy{ key: "color", label: "Color" },],headline: {- ask: "Create folder",+ ask: "Create library folder",object: "Q3 reports",object_key: "name",},@@ -70,7 +70,7 @@ test("the headline names the action and its argument is not repeated below", asyrenderQueue();const heading = await screen.findByRole("heading", {- name: "Create folder Q3 reports",+ name: "Create library folder Q3 reports",});expect(heading).toBeDefined();expect(screen.getByText("Color")).toBeDefined();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.tsindex 16ca453965..7b6651b833 100644--- 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.ts@@ -1,5 +1,6 @@import { http, HttpResponse } from "msw";import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import referenceCardsJson from "./referenceCards.json";import realCardsJson from "./realCards.json";export const CHAT_SESSION = "s1";@@ -82,7 +83,11 @@ export function folder(id: string, name: string, minutesAgo = 5) {tool: "create_folder",args: { name },fields: [{ key: "name", label: "Name" }],- headline: { ask: "Create folder", object: name, object_key: "name" },+ headline: {+ ask: "Create library folder",+ object: name,+ object_key: "name",+ },minutesAgo,});}@@ -135,10 +140,35 @@ export function deleteFolder(id: string, folderId: string) {tool: "delete_folder",args: { folder_id: folderId },fields: [{ key: "folder_id", label: "Folder" }],- headline: { ask: "Delete a folder" },+ headline: { ask: "Delete library folder" },});}+export interface ReferenceCard {+ story: string;+ review: PendingHumanReviewModel;+}++// Built by the server's resolvers and payload builder (reference_cards_test.py).+export function referenceCards(): ReferenceCard[] {+ return (+ referenceCardsJson as unknown as { story: string; review: object }[]+ ).map((card) => ({+ story: card.story,+ review: {+ ...(card.review as PendingHumanReviewModel),+ created_at: new Date(Date.now() - 5 * 60_000),+ },+ }));+}++export function referenceCard(story: string) {+ const card = referenceCards().find((c) => c.story === story);+ if (!card) throw new Error(`No reference card "${story}"`);+ // A copy: tests edit the payload, and the JSON module is shared.+ return structuredClone(card.review);+}+// A workflow run whose step reaches outside the platform.export function workflow(id = "wf") {return heldReview({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.tsxindex a87c94a9b3..2f6da1fc8e 100644--- 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.tsx@@ -32,7 +32,7 @@ test.each([1, 4])(type: "approval_required",tool_name: "create_folder",review_id: reviews[0].node_exec_id,- ask: "Create folder",+ ask: "Create library folder",object: "Folder 0",},} as MessagePart;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.jsonindex 87e3f151f2..5fb318a397 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/realCards.json@@ -36,6 +36,8 @@"label": "Body"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_capability","turn": 1,"mode": "auto",@@ -218,6 +220,8 @@"label": "Values"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_capability","turn": 1,"mode": "auto",@@ -434,6 +438,8 @@"label": "Step code"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_capability","turn": 1,"mode": "auto",@@ -579,6 +585,8 @@"label": "Body"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_capability","turn": 1,"mode": "auto",@@ -718,6 +726,8 @@"label": "Shorten links"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_capability","turn": 1,"mode": "auto",@@ -1057,6 +1067,8 @@"label": "Inputs"}],+ "references": [],+ "reference_totals": {},"tool_call_id": "call-run_agent","turn": 1,"mode": "auto",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.jsonnew file mode 100644index 0000000000..bb4e347358--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json@@ -0,0 +1,1407 @@+[+ {+ "story": "Delete folder",+ "review": {+ "node_exec_id": "copilot-node-gate-delete_folder:e3f421dfb462abc8",+ "node_id": "copilot-node-gate-delete_folder",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "delete_folder",+ "arguments": {+ "folder_id": "f-q3"+ },+ "clipped": [],+ "fields": [+ {+ "key": "folder_id",+ "label": "Folder"+ }+ ],+ "references": [+ {+ "key": "folder_id",+ "entity": "library_folder",+ "id": "f-q3",+ "name": "Q3 reports",+ "href": "/library?folder=f-q3",+ "kind": "Library folder",+ "description": null,+ "meta": [+ {+ "text": "4 agents",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "1 subfolder",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Finance",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "4 agents · 1 subfolder · In Finance"+ }+ ],+ "reference_totals": {+ "folder_id": 1+ },+ "tool_call_id": "call-delete_folder",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "delete_folder",+ "name": "Delete folder",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Delete library folder",+ "object": "Q3 reports",+ "object_key": "folder_id"+ }+ },+ "instructions": "delete_folder",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Move agents",+ "review": {+ "node_exec_id": "copilot-node-gate-move_agents_to_folder:438bc4a7e55797ed",+ "node_id": "copilot-node-gate-move_agents_to_folder",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "move_agents_to_folder",+ "arguments": {+ "agent_ids": [+ "lib-digest",+ "lib-gone",+ "lib-triage",+ "lib-notes",+ "lib-invoices",+ "lib-leads",+ "lib-social"+ ],+ "folder_id": "f-archive"+ },+ "clipped": [],+ "fields": [+ {+ "key": "agent_ids",+ "label": "Agents"+ },+ {+ "key": "folder_id",+ "label": "Folder"+ }+ ],+ "references": [+ {+ "key": "folder_id",+ "entity": "library_folder",+ "id": "f-archive",+ "name": "Archive",+ "href": "/library?folder=f-archive",+ "kind": "Library folder",+ "description": null,+ "meta": [+ {+ "text": "4 agents",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "1 subfolder",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "4 agents · 1 subfolder"+ },+ {+ "key": "agent_ids",+ "entity": "library_agent",+ "id": "lib-digest",+ "name": "Morning digest",+ "href": "/library/agents/lib-digest",+ "kind": "Agent",+ "description": "Summarises overnight email and news at 7am.",+ "meta": [+ {+ "text": "Version 3",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Mornings",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Last run 2026-09-24",+ "cron": null,+ "label": "Last run",+ "at": "2026-09-24T14:05:00+00:00"+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Version 3 · In Mornings · Last run 2026-09-24"+ },+ {+ "key": "agent_ids",+ "entity": "library_agent",+ "id": "lib-gone",+ "name": null,+ "href": null,+ "kind": null,+ "description": null,+ "meta": [],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": null+ },+ {+ "key": "agent_ids",+ "entity": "library_agent",+ "id": "lib-triage",+ "name": "Inbox triage",+ "href": "/library/agents/lib-triage",+ "kind": "Agent",+ "description": "Labels and routes new support email.",+ "meta": [+ {+ "text": "Version 3",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Mornings",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Never run",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Version 3 · In Mornings · Never run"+ },+ {+ "key": "agent_ids",+ "entity": "library_agent",+ "id": "lib-notes",+ "name": "Meeting notes",+ "href": "/library/agents/lib-notes",+ "kind": "Agent",+ "description": "Turns call recordings into action items.",+ "meta": [+ {+ "text": "Version 3",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Mornings",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Never run",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Version 3 · In Mornings · Never run"+ },+ {+ "key": "agent_ids",+ "entity": "library_agent",+ "id": "lib-invoices",+ "name": "Invoice chaser",+ "href": "/library/agents/lib-invoices",+ "kind": "Agent",+ "description": "Nudges clients about overdue invoices.",+ "meta": [+ {+ "text": "Version 3",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Mornings",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Never run",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Version 3 · In Mornings · Never run"+ }+ ],+ "reference_totals": {+ "folder_id": 1,+ "agent_ids": 7+ },+ "tool_call_id": "call-move_agents_to_folder",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "move_agents_to_folder",+ "name": "Move agents to folder",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Move agents into library folder",+ "object": "Archive",+ "object_key": "folder_id"+ }+ },+ "instructions": "move_agents_to_folder",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Pause schedule",+ "review": {+ "node_exec_id": "copilot-node-gate-pause_schedule:ecd458da7a506241",+ "node_id": "copilot-node-gate-pause_schedule",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "pause_schedule",+ "arguments": {+ "schedule_id": "sch-digest"+ },+ "clipped": [],+ "fields": [+ {+ "key": "schedule_id",+ "label": "Schedule"+ }+ ],+ "references": [+ {+ "key": "schedule_id",+ "entity": "schedule",+ "id": "sch-digest",+ "name": "Daily digest",+ "href": "/library/agents/lib-digest?activeTab=scheduled&activeItem=sch-digest",+ "kind": "Schedule",+ "description": null,+ "meta": [+ {+ "text": "Runs 0 7 * * *",+ "cron": "0 7 * * *",+ "label": null,+ "at": null+ },+ {+ "text": "Next run 2026-09-25",+ "cron": null,+ "label": "Next run",+ "at": "2026-09-25T07:00:00+00:00"+ },+ {+ "text": "Agent: Morning digest",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Runs 0 7 * * * · Next run 2026-09-25 · Agent: Morning digest"+ }+ ],+ "reference_totals": {+ "schedule_id": 1+ },+ "tool_call_id": "call-pause_schedule",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "pause_schedule",+ "name": "Pause schedule",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Pause a schedule",+ "object": "Daily digest",+ "object_key": "schedule_id"+ }+ },+ "instructions": "pause_schedule",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Hire expert",+ "review": {+ "node_exec_id": "copilot-node-gate-hire_expert:3ffe656fbe28a59c",+ "node_id": "copilot-node-gate-hire_expert",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "hire_expert",+ "arguments": {+ "template_id": "tpl-ada",+ "name": "Ada"+ },+ "clipped": [],+ "fields": [+ {+ "key": "template_id",+ "label": "Template"+ },+ {+ "key": "name",+ "label": "Name"+ }+ ],+ "references": [+ {+ "key": "template_id",+ "entity": "expert_template",+ "id": "tpl-ada",+ "name": "Ada",+ "href": "/marketplace/experts/tpl-ada",+ "kind": "Expert template",+ "description": "Keeps the books balanced.",+ "meta": [+ {+ "text": "Finance",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": "#7c3aed",+ "skills": [+ "Month-end close",+ "Receipt matching",+ "Cash forecast",+ "Payroll"+ ],+ "summary": "Finance"+ }+ ],+ "reference_totals": {+ "template_id": 1+ },+ "tool_call_id": "call-hire_expert",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "hire_expert",+ "name": "Hire expert",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Hire",+ "object": "Ada",+ "object_key": "name"+ }+ },+ "instructions": "hire_expert",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Message chat",+ "review": {+ "node_exec_id": "copilot-node-gate-message_session:2c8054b35c3384ca",+ "node_id": "copilot-node-gate-message_session",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "message_session",+ "arguments": {+ "session_id": "s-q3",+ "message": "Done?"+ },+ "clipped": [],+ "fields": [+ {+ "key": "session_id",+ "label": "Session"+ },+ {+ "key": "message",+ "label": "Message"+ }+ ],+ "references": [+ {+ "key": "session_id",+ "entity": "chat_session",+ "id": "s-q3",+ "name": "Q3 planning",+ "href": "/copilot?sessionId=s-q3",+ "kind": "Chat",+ "description": null,+ "meta": [+ {+ "text": "Started 2026-09-24",+ "cron": null,+ "label": "Started",+ "at": "2026-09-24T14:05:00+00:00"+ },+ {+ "text": "Last active 2026-09-24",+ "cron": null,+ "label": "Last active",+ "at": "2026-09-24T14:05:00+00:00"+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Started 2026-09-24 · Last active 2026-09-24"+ }+ ],+ "reference_totals": {+ "session_id": 1+ },+ "tool_call_id": "call-message_session",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "message_session",+ "name": "Message session",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Message another chat",+ "object": "Q3 planning",+ "object_key": "session_id"+ }+ },+ "instructions": "message_session",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Grant credential",+ "review": {+ "node_exec_id": "copilot-node-gate-grant_expert_credential:b489e74557cde77d",+ "node_id": "copilot-node-gate-grant_expert_credential",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "grant_expert_credential",+ "arguments": {+ "expert_id": "exp-ada",+ "credential_id": "[redacted]"+ },+ "clipped": [],+ "fields": [+ {+ "key": "expert_id",+ "label": "Expert"+ },+ {+ "key": "credential_id",+ "label": "Credential"+ }+ ],+ "references": [+ {+ "key": "credential_id",+ "entity": "credential",+ "id": "cred-gh",+ "name": "GitHub (work)",+ "href": "/settings/integrations",+ "kind": "Credential",+ "description": null,+ "meta": [+ {+ "text": "github",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "api key",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "github · api key"+ },+ {+ "key": "expert_id",+ "entity": "expert",+ "id": "exp-ada",+ "name": "Ada",+ "href": "/team/exp-ada",+ "kind": "Expert",+ "description": null,+ "meta": [+ {+ "text": "Bookkeeper",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": "#0ea5e9",+ "skills": [],+ "summary": "Bookkeeper"+ }+ ],+ "reference_totals": {+ "expert_id": 1,+ "credential_id": 1+ },+ "tool_call_id": "call-grant_expert_credential",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "grant_expert_credential",+ "name": "Grant expert credential",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Give a teammate an account",+ "object": "GitHub (work)",+ "object_key": "credential_id"+ }+ },+ "instructions": "grant_expert_credential",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Edit agent",+ "review": {+ "node_exec_id": "copilot-node-gate-edit_agent:4f2d4af36c72c9de",+ "node_id": "copilot-node-gate-edit_agent",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "edit_agent",+ "arguments": {+ "agent_id": "g-digest"+ },+ "clipped": [],+ "fields": [+ {+ "key": "agent_id",+ "label": "Agent"+ }+ ],+ "references": [+ {+ "key": "agent_id",+ "entity": "agent_or_graph",+ "id": "g-digest",+ "name": "Morning digest",+ "href": "/library/agents/lib-digest",+ "kind": "Agent",+ "description": "Summarises overnight email and news at 7am.",+ "meta": [+ {+ "text": "Version 3",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "In Mornings",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Last run 2026-09-24",+ "cron": null,+ "label": "Last run",+ "at": "2026-09-24T14:05:00+00:00"+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Version 3 · In Mornings · Last run 2026-09-24"+ }+ ],+ "reference_totals": {+ "agent_id": 1+ },+ "tool_call_id": "call-edit_agent",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "edit_agent",+ "name": "Edit agent",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Edit an agent",+ "object": "Morning digest",+ "object_key": "agent_id"+ }+ },+ "instructions": "edit_agent",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Update template",+ "review": {+ "node_exec_id": "copilot-node-gate-update_preset:678cab8eb4cadd6b",+ "node_id": "copilot-node-gate-update_preset",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "update_preset",+ "arguments": {+ "preset_id": "pre-weekly"+ },+ "clipped": [],+ "fields": [+ {+ "key": "preset_id",+ "label": "Preset"+ }+ ],+ "references": [+ {+ "key": "preset_id",+ "entity": "preset",+ "id": "pre-weekly",+ "name": "Weekly digest",+ "href": "/library/agents/lib-digest?activeTab=templates&activeItem=pre-weekly",+ "kind": "Template",+ "description": "The digest, but Mondays only.",+ "meta": [+ {+ "text": "Agent: Morning digest",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Agent: Morning digest"+ }+ ],+ "reference_totals": {+ "preset_id": 1+ },+ "tool_call_id": "call-update_preset",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "update_preset",+ "name": "Update preset",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Update preset",+ "object": "Weekly digest",+ "object_key": "preset_id"+ }+ },+ "instructions": "update_preset",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Delete trigger",+ "review": {+ "node_exec_id": "copilot-node-gate-delete_preset:9a95d1034809569c",+ "node_id": "copilot-node-gate-delete_preset",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "delete_preset",+ "arguments": {+ "preset_id": "pre-inbox"+ },+ "clipped": [],+ "fields": [+ {+ "key": "preset_id",+ "label": "Preset"+ }+ ],+ "references": [+ {+ "key": "preset_id",+ "entity": "preset",+ "id": "pre-inbox",+ "name": "New invoice email",+ "href": "/library/agents/lib-digest?activeTab=triggers&activeItem=preset%3Apre-inbox",+ "kind": "Trigger",+ "description": "Runs when an invoice lands.",+ "meta": [+ {+ "text": "Agent: Morning digest",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Agent: Morning digest"+ }+ ],+ "reference_totals": {+ "preset_id": 1+ },+ "tool_call_id": "call-delete_preset",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "delete_preset",+ "name": "Delete preset",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Delete a preset",+ "object": "New invoice email",+ "object_key": "preset_id"+ }+ },+ "instructions": "delete_preset",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Schedule routine",+ "review": {+ "node_exec_id": "copilot-node-gate-schedule_routine:e90d2f84ec894011",+ "node_id": "copilot-node-gate-schedule_routine",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "schedule_routine",+ "arguments": {+ "routine_id": "rt-close"+ },+ "clipped": [],+ "fields": [+ {+ "key": "routine_id",+ "label": "Routine"+ }+ ],+ "references": [+ {+ "key": "routine_id",+ "entity": "routine",+ "id": "rt-close",+ "name": "Month-end close",+ "href": "/team/exp-ada",+ "kind": "Routine",+ "description": "Reconcile every account against the bank feed, flag anything over $500 that has no receipt, and draft the close summary for review.",+ "meta": [+ {+ "text": "Runs 0 9 1 * *",+ "cron": "0 9 1 * *",+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "Runs 0 9 1 * *"+ }+ ],+ "reference_totals": {+ "routine_id": 1+ },+ "tool_call_id": "call-schedule_routine",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "schedule_routine",+ "name": "Schedule routine",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Schedule a routine",+ "object": "Month-end close",+ "object_key": "routine_id"+ }+ },+ "instructions": "schedule_routine",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Install workflow",+ "review": {+ "node_exec_id": "copilot-node-gate-install_expert_workflow:56e5c481a85b33f0",+ "node_id": "copilot-node-gate-install_expert_workflow",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "install_expert_workflow",+ "arguments": {+ "expert_id": "exp-ada",+ "store_listing_version_id": "slv-receipts"+ },+ "clipped": [],+ "fields": [+ {+ "key": "store_listing_version_id",+ "label": "Store listing version"+ },+ {+ "key": "expert_id",+ "label": "Expert"+ }+ ],+ "references": [+ {+ "key": "store_listing_version_id",+ "entity": "store_listing",+ "id": "slv-receipts",+ "name": "Receipt matcher",+ "href": "/marketplace/agent/ledgerly/receipt-matcher",+ "kind": "Marketplace agent",+ "description": "Matches card spend to emailed receipts.",+ "meta": [+ {+ "text": "By ledgerly",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "1,204 runs",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "4.6 ★",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "By ledgerly · 1,204 runs · 4.6 ★"+ },+ {+ "key": "expert_id",+ "entity": "expert",+ "id": "exp-ada",+ "name": "Ada",+ "href": "/team/exp-ada",+ "kind": "Expert",+ "description": null,+ "meta": [+ {+ "text": "Bookkeeper",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": "#0ea5e9",+ "skills": [],+ "summary": "Bookkeeper"+ }+ ],+ "reference_totals": {+ "expert_id": 1,+ "store_listing_version_id": 1+ },+ "tool_call_id": "call-install_expert_workflow",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "install_expert_workflow",+ "name": "Install expert workflow",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Give a teammate a workflow",+ "object": null,+ "object_key": null+ }+ },+ "instructions": "install_expert_workflow",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Remove workflow",+ "review": {+ "node_exec_id": "copilot-node-gate-remove_expert_workflow:413dbad9f561e35a",+ "node_id": "copilot-node-gate-remove_expert_workflow",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "remove_expert_workflow",+ "arguments": {+ "workflow_id": "wf-receipts"+ },+ "clipped": [],+ "fields": [+ {+ "key": "workflow_id",+ "label": "Workflow"+ }+ ],+ "references": [+ {+ "key": "workflow_id",+ "entity": "expert_workflow",+ "id": "wf-receipts",+ "name": "Receipt matcher",+ "href": "/team/exp-ada",+ "kind": "Expert workflow",+ "description": null,+ "meta": [],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": null+ }+ ],+ "reference_totals": {+ "workflow_id": 1+ },+ "tool_call_id": "call-remove_expert_workflow",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "remove_expert_workflow",+ "name": "Remove expert workflow",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Take a workflow from a teammate",+ "object": "Receipt matcher",+ "object_key": "workflow_id"+ }+ },+ "instructions": "remove_expert_workflow",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Confirm team change",+ "review": {+ "node_exec_id": "copilot-node-gate-confirm_expert_change:acae127705401f90",+ "node_id": "copilot-node-gate-confirm_expert_change",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "confirm_expert_change",+ "arguments": {+ "confirmation_id": "cf-1"+ },+ "clipped": [],+ "fields": [+ {+ "key": "confirmation_id",+ "label": "Confirmation"+ }+ ],+ "references": [+ {+ "key": "confirmation_id",+ "entity": "team_change",+ "id": "cf-1",+ "name": "Grace",+ "href": null,+ "kind": "New hire",+ "description": "Ships on Thursdays.",+ "meta": [+ {+ "text": "Release manager",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Engineering",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": "#7c3aed",+ "skills": ["Release notes", "Changelog"],+ "summary": "Release manager · Engineering"+ }+ ],+ "reference_totals": {+ "confirmation_id": 1+ },+ "tool_call_id": "call-confirm_expert_change",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "confirm_expert_change",+ "name": "Confirm expert change",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Confirm the team change",+ "object": "Grace",+ "object_key": "confirmation_id"+ }+ },+ "instructions": "confirm_expert_change",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Delete file",+ "review": {+ "node_exec_id": "copilot-node-gate-delete_workspace_file:728b5af581bf1036",+ "node_id": "copilot-node-gate-delete_workspace_file",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "delete_workspace_file",+ "arguments": {+ "file_id": "file-q3",+ "path": "/reports/q3-report.pdf"+ },+ "clipped": [],+ "fields": [+ {+ "key": "file_id",+ "label": "File"+ },+ {+ "key": "path",+ "label": "Path"+ }+ ],+ "references": [+ {+ "key": "file_id",+ "entity": "workspace_file",+ "id": "file-q3",+ "name": "q3-report.pdf",+ "href": "/artifacts?folder=wf-reports",+ "kind": "Workspace file",+ "description": null,+ "meta": [+ {+ "text": "application/pdf",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "242 KB",+ "cron": null,+ "label": null,+ "at": null+ },+ {+ "text": "Modified 2026-09-24",+ "cron": null,+ "label": "Modified",+ "at": "2026-09-24T14:05:00+00:00"+ },+ {+ "text": "In reports",+ "cron": null,+ "label": null,+ "at": null+ }+ ],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": "application/pdf · 242 KB · Modified 2026-09-24 · In reports"+ }+ ],+ "reference_totals": {+ "file_id": 1+ },+ "tool_call_id": "call-delete_workspace_file",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "delete_workspace_file",+ "name": "Delete workspace file",+ "effect": "platform",+ "irreversible": true,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Delete workspace file",+ "object": "/reports/q3-report.pdf",+ "object_key": "path"+ }+ },+ "instructions": "delete_workspace_file",+ "editable": false,+ "status": "WAITING"+ }+ },+ {+ "story": "Unresolved id",+ "review": {+ "node_exec_id": "copilot-node-gate-delete_preset:67a218ba0946e3d5",+ "node_id": "copilot-node-gate-delete_preset",+ "user_id": "user-1",+ "session_id": "s1",+ "graph_exec_id": null,+ "graph_id": null,+ "graph_version": null,+ "payload": {+ "tool": "delete_preset",+ "arguments": {+ "preset_id": "3f0c9a2e-preset-gone"+ },+ "clipped": [],+ "fields": [+ {+ "key": "preset_id",+ "label": "Preset"+ }+ ],+ "references": [+ {+ "key": "preset_id",+ "entity": "preset",+ "id": "3f0c9a2e-preset-gone",+ "name": null,+ "href": null,+ "kind": null,+ "description": null,+ "meta": [],+ "avatar_url": null,+ "avatar_color": null,+ "skills": [],+ "summary": null+ }+ ],+ "reference_totals": {+ "preset_id": 1+ },+ "tool_call_id": "call-delete_preset",+ "turn": 1,+ "mode": "ask_first",+ "subject": {+ "kind": "tool",+ "key": "delete_preset",+ "name": "Delete preset",+ "effect": "platform",+ "irreversible": false,+ "block_id": null+ },+ "reason": "Ask First is on for this chat, so this action needs your approval.",+ "reason_kind": "mode",+ "chat_rules_allowed": [],+ "headline": {+ "ask": "Delete a preset",+ "object": null,+ "object_key": null+ }+ },+ "instructions": "delete_preset",+ "editable": false,+ "status": "WAITING"+ }+ }+]diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsxnew file mode 100644index 0000000000..86df5a796e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx@@ -0,0 +1,234 @@+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { expect, test, vi } from "vitest";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { server } from "@/mocks/mock-server";+import { act, render, screen, within } from "@/tests/integrations/test-utils";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import { CopilotPendingReviews } from "../../CopilotPendingReviews/CopilotPendingReviews";+import { CHAT_SESSION, referenceCard } from "./fixtures";++function renderCard(review: PendingHumanReviewModel) {+ server.use(+ http.get(`*/api/review/session/${CHAT_SESSION}`, () =>+ HttpResponse.json([review]),+ ),+ );+ render(+ <CopilotChatActionsProvider onSend={vi.fn()} onBackendTurn={vi.fn()}>+ <CopilotPendingReviews chatSessionId={CHAT_SESSION} />+ </CopilotChatActionsProvider>,+ );+}++async function card() {+ return within(await screen.findByRole("article"));+}++test("a held delete names its folder in the headline, not as a raw id", async () => {+ renderCard(referenceCard("Delete folder"));++ const view = await card();+ expect(+ view.getByRole("heading", { name: /Delete library folder Q3 reports/ }),+ ).toBeDefined();+ expect(view.queryByText("f-q3")).toBeNull();+ const folder = view.getByRole("link", { name: "Q3 reports" });+ expect(folder.getAttribute("href")).toBe("/library?folder=f-q3");+});++test("a list of ids reads as linked names, the unresolved one as its id", async () => {+ renderCard(referenceCard("Move agents"));++ const view = await card();+ const digest = view.getByRole("link", { name: "Morning digest" });+ expect(digest.getAttribute("href")).toBe("/library/agents/lib-digest");+ expect(view.getByText("lib-gone")).toBeDefined();+ expect(view.queryByRole("link", { name: "lib-gone" })).toBeNull();+ expect(view.getByText(/\+2 more/)).toBeDefined();+});++test("a resolved id links to its page", async () => {+ renderCard(referenceCard("Hire expert"));++ const view = await card();+ const template = view.getByRole("link", { name: "Ada" });+ expect(template.getAttribute("href")).toBe("/marketplace/experts/tpl-ada");+});++test("an id nothing resolved stays the raw id with no link", async () => {+ renderCard(referenceCard("Unresolved id"));++ const view = await card();+ expect(view.getByRole("heading", { name: "Delete a preset" })).toBeDefined();+ expect(view.getByText("3f0c9a2e-preset-gone")).toBeDefined();+ expect(view.queryAllByRole("link")).toHaveLength(0);+});++test("a stored link that leaves the app is dropped, the name kept", async () => {+ const review = referenceCard("Hire expert");+ const payload = review.payload as { references: { href: string }[] };+ payload.references[0].href = "https://evil.example/phish";+ renderCard(review);++ const view = await card();+ expect(view.getByText("Ada", { selector: "span" })).toBeDefined();+ expect(view.queryAllByRole("link")).toHaveLength(0);+});++test("hovering a resolved link shows its kind, description, facts and ID", async () => {+ renderCard(referenceCard("Move agents"));++ const view = await card();+ await userEvent.hover(view.getByRole("link", { name: "Morning digest" }));++ const tip = within(await screen.findByRole("tooltip"));+ expect(tip.getByText("Agent")).toBeDefined();+ expect(tip.getByText("Morning digest")).toBeDefined();+ expect(+ tip.getByText("Summarises overnight email and news at 7am."),+ ).toBeDefined();+ expect(+ tip.getByText(/^Version 3 · In Mornings · Last run .+ ago$/),+ ).toBeDefined();+ expect(tip.getByText("lib-digest")).toBeDefined();+});++test("a schedule's card words its cadence and next run for a person", async () => {+ renderCard(referenceCard("Pause schedule"));++ const view = await card();+ await userEvent.hover(view.getByRole("link", { name: "Daily digest" }));++ const tip = await screen.findByRole("tooltip");+ expect(tip.textContent).toContain("Every day at");+ expect(tip.textContent).toMatch(/Next run (in .+|.+ ago)/);+ expect(tip.textContent).not.toContain("0 7 * * *");+});++test("a chat's card says how long ago it was last active", async () => {+ renderCard(referenceCard("Message chat"));++ const view = await card();+ await userEvent.hover(view.getByRole("link", { name: "Q3 planning" }));++ const tip = await screen.findByRole("tooltip");+ expect(tip.textContent).toMatch(/Last active .+ ago/);+ expect(tip.textContent).not.toContain("2026-09-24");+});++test("a template's card lists its skills, as the marketplace card does", async () => {+ renderCard(referenceCard("Hire expert"));++ const view = await card();+ await userEvent.hover(view.getByRole("link", { name: "Ada" }));++ const tip = within(await screen.findByRole("tooltip"));+ expect(+ tip.getByText("Month-end close, Receipt matching, Cash forecast +1 more"),+ ).toBeDefined();+});++test("a card with nothing but its kind shows only the kind, title and ID", async () => {+ renderCard(referenceCard("Remove workflow"));++ const view = await card();+ await userEvent.hover(view.getByRole("link", { name: "Receipt matcher" }));++ const tip = await screen.findByRole("tooltip");+ const lines = [...tip.querySelectorAll("p")].map((p) => p.textContent);+ expect(lines).toEqual(["Expert workflow", "Receipt matcher", "wf-receipts"]);+});++test("a named thing with no page still shows its card, unlinked", async () => {+ renderCard(referenceCard("Confirm team change"));++ const view = await card();+ expect(view.queryAllByRole("link")).toHaveLength(0);+ await userEvent.hover(view.getByText("Grace"));++ const tip = within(await screen.findByRole("tooltip"));+ expect(tip.getByText("New hire")).toBeDefined();+ expect(tip.getByText("Ships on Thursdays.")).toBeDefined();+});++test("an unlinked name's card opens from the keyboard too", async () => {+ renderCard(referenceCard("Confirm team change"));++ const view = await card();+ const grace = view.getByText("Grace");+ expect(grace.getAttribute("tabindex")).toBe("0");+ act(() => grace.focus());++ const tip = within(await screen.findByRole("tooltip"));+ expect(tip.getByText("New hire")).toBeDefined();+});++test("a link with no card has no tooltip, only the ID as its title", async () => {+ const review = referenceCard("Move agents");+ const payload = review.payload as {+ references: { kind: unknown; summary: unknown }[];+ };+ payload.references.forEach((ref) => {+ ref.kind = null;+ ref.summary = null;+ });+ renderCard(review);++ const view = await card();+ const digest = view.getByRole("link", { name: "Morning digest" });+ await userEvent.hover(digest);++ expect(digest.getAttribute("title")).toBe("lib-digest");+ await new Promise((resolve) => setTimeout(resolve, 400));+ expect(screen.queryByRole("tooltip")).toBeNull();+});++test("a list the server clipped still counts every ID it held", async () => {+ const review = referenceCard("Move agents");+ const payload = review.payload as {+ arguments: Record<string, unknown>;+ clipped: string[];+ reference_totals: Record<string, number>;+ };+ payload.arguments.agent_ids = '["lib-digest", "lib-gone", "lib-tri…';+ payload.clipped = ["agent_ids"];+ payload.reference_totals.agent_ids = 120;+ renderCard(review);++ const view = await card();+ expect(view.getByRole("link", { name: "Morning digest" })).toBeDefined();+ expect(view.getByText(/\+115 more/)).toBeDefined();+});++test("unresolved agent IDs stay listed beside a resolved folder headline", async () => {+ const review = referenceCard("Move agents");+ const payload = review.payload as {+ arguments: Record<string, unknown>;+ references: { key: string; name: string | null; href: string | null }[];+ reference_totals: Record<string, number>;+ };+ payload.arguments.agent_ids = ["lib-lost-1", "lib-lost-2"];+ payload.references = [+ payload.references.find((ref) => ref.key === "folder_id")!,+ ...["lib-lost-1", "lib-lost-2"].map((id) => ({+ key: "agent_ids",+ entity: "library_agent",+ id,+ name: null,+ href: null,+ summary: null,+ })),+ ];+ payload.reference_totals = { folder_id: 1, agent_ids: 2 };+ renderCard(review);++ const view = await card();+ expect(+ view.getByRole("heading", {+ name: /Move agents into library folder Archive/,+ }),+ ).toBeDefined();+ expect(view.getByText(/lib-lost-1/)).toBeDefined();+ expect(view.getByText(/lib-lost-2/)).toBeDefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/safeHref.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/safeHref.test.tsnew file mode 100644index 0000000000..a416cac0e8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/safeHref.test.ts@@ -0,0 +1,15 @@+import { expect, test } from "vitest";+import { safeHref } from "../helpers";++test.each([+ ["/library?folder=x", "/library?folder=x"],+ ["/team/exp-1", "/team/exp-1"],+ ["//evil.com", null],+ ["/\\evil.com", null],+ ["\\\\evil.com", null],+ ["https://evil.com", null],+ ["/", null],+ [null, null],+])("safeHref(%j) is %j", (href, expected) => {+ expect(safeHref(href)).toBe(expected);+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsxindex 9f795ffd6c..be529050f2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/components/ApprovalCard/ApprovalCard.tsx@@ -98,6 +98,8 @@ export function ApprovalCard({clipped={item.clipped}hiddenKeys={item.headlineKeys}idsWhenAlone={!item.headline.object}+ references={item.blockId ? [] : item.references}+ referenceTotals={item.referenceTotals}/>)}{actions}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.tsxindex 448abddb95..fcae905741 100644--- 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.tsx@@ -1,3 +1,4 @@+import { ReferenceLink } from "@/components/organisms/ApprovalFields/components/ReferenceLink";import { Text } from "@/components/atoms/Text/Text";import { cn } from "@/lib/utils";import { COPILOT_TOOL_CATALOG } from "../../ToolChain/toolCatalog";@@ -30,7 +31,7 @@ export function ApprovalHeadline({ item, compact = false }: Props) {compact ? "truncate" : "text-pretty",)}>- <HeadlineText item={item} />+ <HeadlineText item={item} linked={!compact} /></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">@@ -41,8 +42,15 @@ export function ApprovalHeadline({ item, compact = false }: Props) {);}-export function HeadlineText({ item }: Props) {+interface HeadlineTextProps {+ item: ApprovalItem;+ // Off wherever the line is itself a button.+ linked?: boolean;+}++export function HeadlineText({ item, linked = false }: HeadlineTextProps) {const { ask, object } = item.headline;+ const reference = linked ? objectReference(item) : null;return (<>{ask}@@ -50,10 +58,20 @@ export function HeadlineText({ item }: Props) {<>{" "}<b className="font-semibold" translate="no">- {object}+ {reference ? (+ <ReferenceLink reference={reference}>{object}</ReferenceLink>+ ) : (+ object+ )}</b></>)}</>);}++// The headline names a resolved id's thing, and its field is hidden, so its link and card live here.+function objectReference(item: ApprovalItem) {+ const [key] = item.headlineKeys;+ return item.references.find((ref) => ref.key === key && ref.name) ?? null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.tsindex f26dd62076..b37e45f171 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/helpers.ts@@ -2,7 +2,9 @@ import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/penimport { COPILOT_GATE_NODE_PREFIX } from "@/components/organisms/PendingReviewsList/PendingReviewsList";import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";import {+ type Fact,isIdKey,+ type Reference,visibleKeys,} from "@/components/organisms/ApprovalFields/helpers";import { beautifyString } from "@/lib/utils";@@ -20,6 +22,9 @@ export interface ApprovalItem {toolCallId: string;args: Record<string, unknown>;fields: { key: string; label: string }[];+ references: Reference[];+ // Ids per argument before the server clipped it.+ referenceTotals: Record<string, number>;clipped: string[];subject: { kind: string; key: string; name: string; irreversible: boolean };blockId: string | null;@@ -64,6 +69,8 @@ export function toApprovalItem(review: PendingHumanReviewModel): ApprovalItem {key: String(f.key),label: str(f, "label") ?? String(f.key),})),+ references: asArray(payload.references).flatMap(toReference),+ referenceTotals: toTotals(payload.reference_totals),clipped: asArray(payload.clipped).filter((k): k is string => typeof k === "string",),@@ -142,6 +149,7 @@ export function shownFieldKeys(item: ApprovalItem) {values: item.args,hiddenKeys: item.headlineKeys,idsWhenAlone: !item.headline.object,+ references: item.references,});}@@ -179,6 +187,61 @@ function isIdOnly(item: ApprovalItem) {return !item.headline.object && keys.length > 0 && keys.every(isIdKey);}+function toReference(value: unknown): Reference[] {+ const ref = asObject(value) ?? {};+ const key = str(ref, "key");+ const id = str(ref, "id");+ if (!key || !id) return [];+ const name = str(ref, "name");+ return [+ {+ key,+ id,+ entity: str(ref, "entity") ?? "",+ name,+ // A link is only ever built for an id that resolved.+ href: name ? safeHref(str(ref, "href")) : null,+ kind: name ? str(ref, "kind") : null,+ description: name ? str(ref, "description") : null,+ meta: name ? asArray(ref.meta).flatMap(toFact) : [],+ avatarURL: name ? str(ref, "avatar_url") : null,+ avatarColor: name ? str(ref, "avatar_color") : null,+ skills: name+ ? asArray(ref.skills).filter((s): s is string => typeof s === "string")+ : [],+ summary: name ? str(ref, "summary") : null,+ },+ ];+}++function toFact(value: unknown): Fact[] {+ const fact = asObject(value) ?? {};+ const text = str(fact, "text");+ if (!text) return [];+ return [+ {+ text,+ cron: str(fact, "cron"),+ label: str(fact, "label"),+ at: str(fact, "at"),+ },+ ];+}++// Only an in-app path: the payload is stored data, never a place to send the user.+// Browsers read a leading /\ as //, a protocol-relative jump off the site.+export function safeHref(href: string | null) {+ return href && /^\/[^/\\]/.test(href) ? href : null;+}++function toTotals(value: unknown): Record<string, number> {+ return Object.fromEntries(+ Object.entries(asObject(value) ?? {}).filter(+ (entry): entry is [string, number] => typeof entry[1] === "number",+ ),+ );+}+function asArray(value: unknown): unknown[] {return Array.isArray(value) ? value : [];}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.tsxindex 57e8c8cd1a..afb547c040 100644--- 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.tsx@@ -16,7 +16,7 @@ const HELD: MessagePart = {tool_name: "create_folder",reason: "Ask First is on.",review_id: "copilot-node-gate-create_folder:abc",- ask: "Create folder",+ ask: "Create library folder",object: "Q3 reports",},} as MessagePart;@@ -36,7 +36,7 @@ test("a held call's row flips from waiting to approved when its late result landexpect(await screen.findByText("Waiting for you")).toBeDefined();expect(- screen.getAllByText('Create folder "Q3 reports"').length,+ screen.getAllByText('Create library folder "Q3 reports"').length,).toBeGreaterThan(0);rerender(@@ -60,8 +60,8 @@ test("a late result for another call leaves the row waiting", async () => {});test.each([- ["rejected", "Rejected", "Didn't create folder"],- ["expired", "Expired", "Didn't create folder"],+ ["rejected", "Rejected", "Didn't create library folder"],+ ["expired", "Expired", "Didn't create library 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();@@ -149,7 +149,7 @@ test("a call that may have run claims neither approval nor refusal", async () =>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();+ expect(screen.queryByText(/Didn't create library folder/)).toBeNull();});test("a held read whose release is unclear stays a read, not an action that may have run", async () => {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 4df603f644..60a1e9d7a8 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@@ -243,8 +243,8 @@ 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" },+ title: "Create library folder “Q3 reports”",+ headline: { ask: "Create library folder", object: "Q3 reports" },},makeApproval(10),]);@@ -253,8 +253,10 @@ test("a held call's row sets its object in semibold, as its card does", async ()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();+ expect(object.parentElement?.textContent).toBe(+ "Create library folder Q3 reports",+ );+ expect(screen.queryByText("Create library 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)/library/__tests__/folder-url.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/folder-url.test.tsxnew file mode 100644index 0000000000..07fbf0fc0e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/folder-url.test.tsx@@ -0,0 +1,88 @@+import userEvent from "@testing-library/user-event";+import { NuqsTestingAdapter, type UrlUpdateEvent } from "nuqs/adapters/testing";+import { expect, test, vi } from "vitest";+import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import {+ getGetV2GetFolderMockHandler,+ getGetV2GetFolderResponseMock,+ getGetV2ListLibraryFoldersMockHandler,+} from "@/app/api/__generated__/endpoints/folders/folders.msw";+import {+ getGetV2ListFavoriteLibraryAgentsMockHandler,+ getGetV2ListLibraryAgentsMockHandler,+ getGetV2ListLibraryAgentsResponseMock,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import type { LibraryFolder } from "@/app/api/__generated__/models/libraryFolder";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import LibraryPage from "../page";++const FOLDER: LibraryFolder = {+ id: "f-q3",+ user_id: "test-user",+ name: "Q3 reports",+ agent_count: 0,+ subfolder_count: 0,+ color: null,+ icon: null,+ parent_id: null,+ created_at: new Date(),+ updated_at: new Date(),+};+const PAGE = { total_items: 0, total_pages: 1, current_page: 1, page_size: 20 };++function serve() {+ const agentQueries: URLSearchParams[] = [];+ server.use(+ getGetV2ListLibraryAgentsMockHandler(({ request }) => {+ agentQueries.push(new URL(request.url).searchParams);+ return {+ ...getGetV2ListLibraryAgentsResponseMock(),+ agents: [],+ pagination: PAGE,+ };+ }),+ getGetV2ListFavoriteLibraryAgentsMockHandler({+ agents: [],+ pagination: PAGE,+ }),+ getGetV2ListLibraryFoldersMockHandler({+ folders: [FOLDER],+ pagination: { ...PAGE, total_items: 1 },+ }),+ getGetV2GetFolderMockHandler(getGetV2GetFolderResponseMock(FOLDER)),+ getGetV1ListAllExecutionsMockHandler([]),+ );+ return agentQueries;+}++test("a library link with ?folder= opens that folder", async () => {+ const agentQueries = serve();++ render(+ <NuqsTestingAdapter searchParams="?folder=f-q3">+ <LibraryPage />+ </NuqsTestingAdapter>,+ );++ await waitFor(() =>+ expect(agentQueries.some((q) => q.get("folder_id") === "f-q3")).toBe(true),+ );+ expect(agentQueries.some((q) => q.get("include_root_only"))).toBe(false);+});++test("opening a folder puts it in the URL", async () => {+ serve();+ const onUrlUpdate = vi.fn<(event: UrlUpdateEvent) => void>();++ render(+ <NuqsTestingAdapter onUrlUpdate={onUrlUpdate}>+ <LibraryPage />+ </NuqsTestingAdapter>,+ );+ await userEvent.click(await screen.findByTestId("library-folder"));++ await waitFor(() =>+ expect(onUrlUpdate.mock.calls.at(-1)?.[0].queryString).toBe("?folder=f-q3"),+ );+});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx b/autogpt_platform/frontend/src/app/(platform)/library/page.tsxindex 7143a50964..db052e68bb 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useState, useCallback } from "react";+import { useQueryState } from "nuqs";import { AgentsTabIntro } from "./components/AgentsTabIntro/AgentsTabIntro";import { LibraryActionHeader } from "./components/LibraryActionHeader/LibraryActionHeader";import { LibraryAgentList } from "./components/LibraryAgentList/LibraryAgentList";@@ -19,7 +20,8 @@ const LIBRARY_TABS: LibraryTab[] = [export default function LibraryPage() {const { searchTerm, setSearchTerm, librarySort, setLibrarySort } =useLibraryListPage();- const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);+ // In the URL, so a link can open a folder (the approval card links one).+ const [selectedFolderId, setSelectedFolderId] = useQueryState("folder");const [activeTab, setActiveTab] = useState(LIBRARY_TABS[0].id);const [statusFilter, setStatusFilter] = useState<AgentStatusFilter>("all");const { agents } = useLibraryAgents();diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsxindex b49f63cba1..cfd4cda0b1 100644--- a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsx+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/ApprovalFields.tsx@@ -3,7 +3,14 @@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";+import { ReferenceValue } from "./components/ReferenceValue";+import {+ type FieldSpec,+ humanize,+ MAX_FIELDS,+ type Reference,+ visibleKeys,+} from "./helpers";interface Props {// Labels and order from the tool's or block's input schema.@@ -14,6 +21,10 @@ interface Props {// Keys the card's headline already names.hiddenKeys?: string[];idsWhenAlone?: boolean;+ // What the id arguments name; one shows as its name, linked when it has a page.+ references?: Reference[];+ // Ids per argument before clipping; a clipped list no longer counts itself.+ referenceTotals?: Record<string, number>;}export function ApprovalFields({@@ -22,6 +33,8 @@ export function ApprovalFields({clipped = [],hiddenKeys = [],idsWhenAlone = false,+ references = [],+ referenceTotals = {},}: Props) {const [showAll, setShowAll] = useState(false);const labels = new Map(fields.map((f) => [f.key, f.label]));@@ -30,6 +43,7 @@ export function ApprovalFields({values,hiddenKeys,idsWhenAlone,+ references,}).map((key) => ({ key, label: labels.get(key) ?? humanize(key) }));if (ordered.length === 0) return null;@@ -43,10 +57,12 @@ export function ApprovalFields({<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+ <FieldOrReferencename={field.key}value={values[field.key]}clipped={clipped.includes(field.key)}+ references={references}+ total={referenceTotals[field.key]}/></dd></div>@@ -65,3 +81,27 @@ export function ApprovalFields({</div>);}++interface FieldOrReferenceProps {+ name: string;+ value: unknown;+ clipped: boolean;+ references: Reference[];+ total?: number;+}++function FieldOrReference({+ name,+ value,+ clipped,+ references,+ total,+}: FieldOrReferenceProps) {+ const refs = references.filter((ref) => ref.key === name);+ if (!refs.some((ref) => ref.name))+ return <FieldValue name={name} value={value} clipped={clipped} />;+ const counted = Array.isArray(value)+ ? value.filter((v) => typeof v === "string" && v.trim()).length+ : refs.length;+ return <ReferenceValue refs={refs} total={total ?? counted} />;+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceCard.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceCard.tsxnew file mode 100644index 0000000000..f3c1718d46--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceCard.tsx@@ -0,0 +1,61 @@+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";+import { factText, type Reference } from "../helpers";++// Named, then a count: the marketplace expert card's skills, in a line.+const NAMED_SKILLS = 3;++interface Props {+ reference: Reference;+}++export function ReferenceCard({ reference }: Props) {+ const facts = reference.kind+ ? reference.meta.map(factText).join(" · ")+ : reference.summary;+ const hasAvatar = Boolean(reference.avatarURL || reference.avatarColor);+ return (+ <div>+ <div className="flex items-center gap-2.5">+ {hasAvatar && (+ <ExpertAvatar+ name={reference.name}+ avatarUrl={reference.avatarURL}+ color={reference.avatarColor}+ size={36}+ className="shrink-0 rounded-full"+ />+ )}+ <div className="min-w-0">+ {reference.kind && <p className="text-zinc-500">{reference.kind}</p>}+ <p translate="no" className="text-sm font-semibold text-zinc-900">+ {reference.name}+ </p>+ </div>+ </div>+ {reference.description && (+ <p className="mt-1 line-clamp-3 text-zinc-700">+ {reference.description}+ </p>+ )}+ {facts && <p className="mt-1.5 text-zinc-500">{facts}</p>}+ {reference.skills.length > 0 && (+ <p className="mt-1.5 text-zinc-700">+ <span className="text-zinc-500">Skills: </span>+ {skillsText(reference.skills)}+ </p>+ )}+ <p+ translate="no"+ className="mt-1.5 font-mono text-[0.6875rem] text-zinc-400"+ >+ {reference.id}+ </p>+ </div>+ );+}++function skillsText(skills: string[]) {+ const named = skills.slice(0, NAMED_SKILLS).join(", ");+ const rest = skills.length - NAMED_SKILLS;+ return rest > 0 ? `${named} +${rest} more` : named;+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceLink.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceLink.tsxnew file mode 100644index 0000000000..937ddc9dcd--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceLink.tsx@@ -0,0 +1,61 @@+import Link from "next/link";+import type { ReactNode } from "react";+import {+ Tooltip,+ TooltipContent,+ TooltipPortal,+ TooltipTrigger,+} from "@/components/atoms/Tooltip/BaseTooltip";+import type { Reference } from "../helpers";+import { ReferenceCard } from "./ReferenceCard";++interface Props {+ reference: Reference;+ children: ReactNode;+}++// With a card the hover carries it and the id; without, the id is the title.+// A thing with no page of its own is named without a link, card and all.+export function ReferenceLink({ reference, children }: Props) {+ // A reference stored before cards had kinds carries only its summary line.+ const hasCard = Boolean(reference.kind || reference.summary);+ const link = reference.href ? (+ <Link+ href={reference.href}+ translate="no"+ title={hasCard ? undefined : reference.id}+ className="underline decoration-zinc-300 underline-offset-2 hover:decoration-zinc-500 focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-300"+ >+ {children}+ </Link>+ ) : (+ <span+ translate="no"+ // Focusable only when it opens a card, so the keyboard reaches it too.+ tabIndex={hasCard ? 0 : undefined}+ title={hasCard ? undefined : reference.id}+ className={+ hasCard+ ? "underline decoration-zinc-400 decoration-dotted underline-offset-2 focus-visible:rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-300"+ : undefined+ }+ >+ {children}+ </span>+ );+ if (!hasCard) return link;+ return (+ <Tooltip delayDuration={300}>+ <TooltipTrigger asChild>{link}</TooltipTrigger>+ <TooltipPortal>+ <TooltipContent+ side="bottom"+ align="start"+ className="w-max max-w-[320px] px-3 py-2.5"+ >+ <ReferenceCard reference={reference} />+ </TooltipContent>+ </TooltipPortal>+ </Tooltip>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceValue.tsx b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceValue.tsxnew file mode 100644index 0000000000..e58dc7268c--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/components/ReferenceValue.tsx@@ -0,0 +1,34 @@+import { Fragment } from "react";+import type { Reference } from "../helpers";+import { ReferenceLink } from "./ReferenceLink";++interface Props {+ refs: Reference[];+ // How many ids the argument held; the server names the first few.+ total: number;+}++export function ReferenceValue({ refs, total }: Props) {+ const more = total - refs.length;+ return (+ <span>+ {refs.map((ref, i) => (+ <Fragment key={`${ref.id}-${i}`}>+ {i > 0 && ", "}+ <ReferenceName reference={ref} />+ </Fragment>+ ))}+ {more > 0 && <span className="text-zinc-500"> +{more} more</span>}+ </span>+ );+}++function ReferenceName({ reference }: { reference: Reference }) {+ if (!reference.name)+ return (+ <span translate="no" className="font-mono text-[0.8125rem]">+ {reference.id}+ </span>+ );+ return <ReferenceLink reference={reference}>{reference.name}</ReferenceLink>;+}diff --git a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.ts b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.tsindex 68be4decde..3b3a7c25a4 100644--- a/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.ts+++ b/autogpt_platform/frontend/src/components/organisms/ApprovalFields/helpers.ts@@ -1,3 +1,6 @@+import { formatDistanceToNow } from "date-fns";+import { humanizeCronExpression } from "@/lib/cron-expression-utils";+export const REDACTED = "[redacted]";export const MAX_FIELDS = 6;export const CLAMP_LINES = 3;@@ -23,6 +26,49 @@ export interface FieldSpec {label: string;}+// What an id argument names, resolved by the server when the call was held.+export interface Reference {+ key: string;+ entity: string;+ id: string;+ name: string | null;+ href: string | null;+ // The hover card: the thing's family, its own prose, and short facts.+ kind: string | null;+ description: string | null;+ meta: Fact[];+ avatarURL: string | null;+ avatarColor: string | null;+ skills: string[];+ summary: string | null;+}++// A card fact: `text` as stored, or a cadence or time the card words for the viewer.+export interface Fact {+ text: string;+ cron: string | null;+ label: string | null;+ at: string | null;+}++export function factText(fact: Fact) {+ if (fact.cron) return cronText(fact.cron) ?? fact.text;+ if (fact.label && fact.at) {+ const at = new Date(fact.at);+ if (!Number.isNaN(at.getTime()))+ return `${fact.label} ${formatDistanceToNow(at, { addSuffix: true })}`;+ }+ return fact.text;+}++function cronText(cron: string) {+ try {+ return humanizeCronExpression(cron);+ } catch {+ return null;+ }+}+export function fieldKind(key: string, value: unknown): FieldKind {if (value === REDACTED) return "secret";if (Array.isArray(value)) {@@ -47,6 +93,7 @@ interface VisibleKeysArgs {hiddenKeys: string[];// Show ids when nothing else would tell this call from another.idsWhenAlone: boolean;+ references?: Reference[];}export function visibleKeys({@@ -54,11 +101,15 @@ export function visibleKeys({values,hiddenKeys,idsWhenAlone,+ references = [],}: VisibleKeysArgs) {const present = [...new Set(keys)].filter((key) => !hiddenKeys.includes(key) && hasValue(values[key]),);- const named = present.filter((key) => !isIdKey(key));+ // An id argument the server looked up is shown whatever it found: its names,+ // or the raw ids when none resolved, even beside a named headline.+ const referenced = new Set(references.map((ref) => ref.key));+ const named = present.filter((key) => !isIdKey(key) || referenced.has(key));return named.length > 0 || !idsWhenAlone ? named : present;}