Skip to content

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): AutoPilot's approval requests belong to their chat, not a made-up graph execution (#14853)

Reinier van der Leer0adcb1dba3f5
diff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
index 95675a400a..d3aa16064c 100644
--- a/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval.py
@@ -19,7 +19,6 @@ from backend.copilot import db as chat_db
from backend.copilot.constants import (
COPILOT_NODE_EXEC_ID_SEPARATOR,
COPILOT_NODE_PREFIX,
- COPILOT_SESSION_PREFIX,
SPEND_REVIEW_MARKER,
)
from backend.data import human_review
@@ -189,10 +188,9 @@ async def open_chat_spend_review(
"""Park a paid ``run_capability`` block run on the session's review rails and return the
review id. An open row for the same expert is reused so a model retry
does not stack cards."""
- synthetic_graph_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
node_id = f"{COPILOT_NODE_PREFIX}{SPEND_REVIEW_MARKER}{needed.expert_id}"
- for review in await human_review.get_pending_reviews_for_execution(
- synthetic_graph_id, user_id
+ for review in await human_review.get_pending_reviews_for_chat_session(
+ session_id, user_id
):
if review.node_id == node_id:
return review.node_exec_id
@@ -200,9 +198,7 @@ async def open_chat_spend_review(
await human_review.get_or_create_human_review(
user_id=user_id,
node_exec_id=review_id,
- graph_exec_id=synthetic_graph_id,
- graph_id=synthetic_graph_id,
- graph_version=1,
+ chat_session_id=session_id,
input_data=_review_payload(needed, block=block_name),
message=needed.headline,
editable=False,
diff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py
index feac321475..2a6eb05716 100644
--- a/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py
@@ -205,7 +205,7 @@ async def test_chat_review_reuses_the_open_row_for_the_expert(mocker) -> None:
)
mocker.patch.object(
sa.human_review,
- "get_pending_reviews_for_execution",
+ "get_pending_reviews_for_chat_session",
AsyncMock(return_value=[existing]),
)
create = mocker.patch.object(
@@ -223,7 +223,9 @@ async def test_chat_review_reuses_the_open_row_for_the_expert(mocker) -> None:
@pytest.mark.asyncio
async def test_chat_review_opens_on_the_session_rails(mocker) -> None:
mocker.patch.object(
- sa.human_review, "get_pending_reviews_for_execution", AsyncMock(return_value=[])
+ sa.human_review,
+ "get_pending_reviews_for_chat_session",
+ AsyncMock(return_value=[]),
)
create = mocker.patch.object(
sa.human_review, "get_or_create_human_review", AsyncMock()
@@ -236,6 +238,7 @@ async def test_chat_review_opens_on_the_session_rails(mocker) -> None:
kwargs = create.await_args.kwargs
assert review_id == kwargs["node_exec_id"]
assert review_id.startswith("copilot-node-expert-spend:e-1:")
- assert kwargs["graph_exec_id"] == "copilot-session-s-1"
+ assert kwargs["chat_session_id"] == "s-1"
+ assert "graph_exec_id" not in kwargs
assert kwargs["editable"] is False
assert kwargs["input_data"]["block"] == "Send Email"
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
index b97b43e6ea..12521fa2a6 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py
@@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Any, Dict, List, Union
from prisma.enums import ReviewStatus
from pydantic import BaseModel, Field, field_validator, model_validator
+from backend.copilot.constants import legacy_chat_session_id
+
if TYPE_CHECKING:
from prisma.models import PendingHumanReview
@@ -43,9 +45,14 @@ class PendingHumanReviewModel(BaseModel):
default="", # Temporary default for test compatibility
)
user_id: str = Field(description="User ID associated with the review")
- graph_exec_id: str = Field(description="Graph execution ID")
- graph_id: str = Field(description="Graph ID")
- graph_version: int = Field(description="Graph version")
+ graph_exec_id: str | None = Field(
+ default=None, description="Graph execution ID; None for a chat review"
+ )
+ graph_id: str | None = Field(default=None, description="Graph ID")
+ graph_version: int | None = Field(default=None, description="Graph version")
+ session_id: str | None = Field(
+ default=None, description="Chat session ID; None for a graph review"
+ )
payload: SafeJsonData = Field(description="The actual data payload awaiting review")
instructions: str | None = Field(
description="Instructions or message for the reviewer", default=None
@@ -64,9 +71,6 @@ class PendingHumanReviewModel(BaseModel):
default=None, description="Display name of the agent that requested the review"
)
library_agent_id: str | None = Field(default=None, description="For run deep links")
- session_id: str | None = Field(
- default=None, description="Chat session id for copilot run_capability reviews"
- )
was_edited: bool | None = Field(
description="Whether the data was modified during review", default=None
)
@@ -98,13 +102,17 @@ class PendingHumanReviewModel(BaseModel):
review: Database review object
node_id: Node definition ID (fetched from NodeExecution)
"""
+ # A row written in the old synthetic-graph shape reads as a chat review.
+ legacy_session_id = legacy_chat_session_id(review.graphExecId)
+ is_graph = legacy_session_id is None and review.chatSessionId is None
return cls(
node_exec_id=review.nodeExecId,
node_id=node_id,
user_id=review.userId,
- graph_exec_id=review.graphExecId,
- graph_id=review.graphId,
- graph_version=review.graphVersion,
+ graph_exec_id=review.graphExecId if is_graph else None,
+ graph_id=review.graphId if is_graph else None,
+ graph_version=review.graphVersion if is_graph else None,
+ session_id=review.chatSessionId or legacy_session_id,
payload=review.payload,
instructions=review.instructions,
editable=review.editable,
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
index 94cff74959..2e9f2b6906 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py
@@ -154,6 +154,143 @@ async def test_get_pending_reviews_for_execution_not_available(
assert "not found" in response.json()["detail"]
+_ROUTES = "backend.api.features.graph_executions.review.routes"
+
+
+def _chat_review(user_id: str, status: ReviewStatus) -> PendingHumanReviewModel:
+ return PendingHumanReviewModel(
+ node_exec_id="copilot-node-blk:ab12",
+ node_id="copilot-node-blk",
+ user_id=user_id,
+ session_id="chat-1",
+ payload={"path": "/reports"},
+ editable=True,
+ status=status,
+ created_at=FIXED_NOW,
+ )
+
+
[email protected](loop_scope="session")
+async def test_get_pending_reviews_for_chat_session(
+ client: httpx.AsyncClient,
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ lookup = mocker.patch(
+ f"{_ROUTES}.get_pending_reviews_for_chat_session",
+ return_value=[_chat_review(test_user_id, ReviewStatus.WAITING)],
+ )
+
+ response = await client.get("/api/review/session/chat-1")
+
+ assert response.status_code == 200
+ [review] = response.json()
+ assert review["session_id"] == "chat-1"
+ assert review["graph_exec_id"] is None
+ lookup.assert_awaited_once_with("chat-1", test_user_id)
+
+
[email protected](loop_scope="session")
+async def test_old_synthetic_execution_id_is_answered_from_the_chat(
+ client: httpx.AsyncClient,
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ by_session = mocker.patch(
+ f"{_ROUTES}.get_pending_reviews_for_chat_session", return_value=[]
+ )
+ by_execution = mocker.patch(f"{_ROUTES}.get_pending_reviews_for_execution")
+ graph_exec_meta = mocker.patch(f"{_ROUTES}.get_graph_execution_meta")
+
+ response = await client.get("/api/review/execution/copilot-session-chat-1")
+
+ assert response.status_code == 200
+ by_session.assert_awaited_once_with("chat-1", test_user_id)
+ by_execution.assert_not_called()
+ graph_exec_meta.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_approving_a_chat_review_resumes_no_graph_and_scopes_auto_approval(
+ client: httpx.AsyncClient,
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ waiting = _chat_review(test_user_id, ReviewStatus.WAITING)
+ mocker.patch(
+ f"{_ROUTES}.get_reviews_by_node_exec_ids",
+ return_value={waiting.node_exec_id: waiting},
+ )
+ mocker.patch(
+ f"{_ROUTES}.process_all_reviews_for_execution",
+ return_value={
+ waiting.node_exec_id: _chat_review(test_user_id, ReviewStatus.APPROVED)
+ },
+ )
+ auto_approve = mocker.patch(f"{_ROUTES}.create_auto_approval_record")
+ graph_exec_meta = mocker.patch(f"{_ROUTES}.get_graph_execution_meta")
+ resume = mocker.patch(f"{_ROUTES}.add_graph_execution")
+
+ response = await client.post(
+ "/api/review/action",
+ json={
+ "reviews": [
+ {
+ "node_exec_id": waiting.node_exec_id,
+ "approved": True,
+ "auto_approve_future": True,
+ }
+ ]
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["approved_count"] == 1
+ graph_exec_meta.assert_not_called()
+ resume.assert_not_called()
+ auto_approve.assert_awaited_once()
+ kwargs = auto_approve.await_args.kwargs
+ assert (kwargs["chat_session_id"], kwargs["graph_exec_id"]) == ("chat-1", None)
+ assert kwargs["node_id"] == "copilot-node-blk"
+
+
+ "other",
+ [
+ {"session_id": None, "graph_exec_id": "ge-1", "graph_id": "g-1"},
+ {"session_id": "chat-2"},
+ ],
+ ids=["chat-and-graph", "two-chats"],
+)
[email protected](loop_scope="session")
+async def test_one_request_cannot_act_on_reviews_from_two_scopes(
+ client: httpx.AsyncClient,
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+ other: dict,
+) -> None:
+ chat = _chat_review(test_user_id, ReviewStatus.WAITING)
+ second = chat.model_copy(update={"node_exec_id": "second", **other})
+ mocker.patch(
+ f"{_ROUTES}.get_reviews_by_node_exec_ids",
+ return_value={chat.node_exec_id: chat, second.node_exec_id: second},
+ )
+ process = mocker.patch(f"{_ROUTES}.process_all_reviews_for_execution")
+
+ response = await client.post(
+ "/api/review/action",
+ json={
+ "reviews": [
+ {"node_exec_id": chat.node_exec_id, "approved": True},
+ {"node_exec_id": "second", "approved": True},
+ ]
+ },
+ )
+
+ assert response.status_code == 409
+ process.assert_not_called()
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_process_review_action_approve_success(
client: httpx.AsyncClient,
@@ -712,6 +849,7 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(
graph_exec_id="test_graph_exec_456",
graph_id="test_graph_789",
graph_version=1,
+ chat_session_id=None,
node_id="test_node_def_456",
payload={"data": "test payload"},
)
@@ -1012,6 +1150,7 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie
graph_exec_id="test_graph_exec_456",
graph_id="test_graph_789",
graph_version=1,
+ chat_session_id=None,
node_id="test_node_def_approved",
payload={"data": "approved"},
)
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
index 76152eaafc..84a3d711ea 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.py
@@ -6,10 +6,7 @@ import autogpt_libs.auth as autogpt_auth_lib
from fastapi import APIRouter, HTTPException, Query, Security, status
from prisma.enums import ReviewStatus
-from backend.copilot.constants import (
- is_copilot_synthetic_id,
- parse_node_id_from_exec_id,
-)
+from backend.copilot.constants import legacy_chat_session_id, parse_node_id_from_exec_id
from backend.data.execution import (
ExecutionContext,
ExecutionStatus,
@@ -19,6 +16,7 @@ from backend.data.execution import (
from backend.data.graph import get_graph_settings
from backend.data.human_review import (
create_auto_approval_record,
+ get_pending_reviews_for_chat_session,
get_pending_reviews_for_execution,
get_pending_reviews_for_user,
get_reviews_by_node_exec_ids,
@@ -43,18 +41,17 @@ router = APIRouter(
async def _resolve_node_ids(
node_exec_ids: list[str],
- graph_exec_id: str,
- is_copilot: bool,
+ graph_exec_id: str | None,
) -> dict[str, str]:
"""Resolve node_exec_id -> node_id for auto-approval records.
- CoPilot synthetic IDs encode node_id in the format "{node_id}:{random}".
- Graph executions look up node_id from NodeExecution records.
+ A chat review's id encodes its node id as "{node_id}:{random}"; graph
+ executions look up node_id from NodeExecution records.
"""
if not node_exec_ids:
return {}
- if is_copilot:
+ if graph_exec_id is None:
return {neid: parse_node_id_from_exec_id(neid) for neid in node_exec_ids}
node_execs = await get_node_executions(
@@ -146,21 +143,44 @@ async def list_pending_reviews_for_execution(
Reviews with invalid status are excluded with warning logs.
"""
- # Verify user owns the graph execution before returning reviews
- # (CoPilot synthetic IDs don't have graph execution records)
- if not is_copilot_synthetic_id(graph_exec_id):
- graph_exec = await get_graph_execution_meta(
- user_id=user_id, execution_id=graph_exec_id
+ # Clients built before chat reviews had their own route ask for a chat
+ # under its old synthetic id.
+ if session_id := legacy_chat_session_id(graph_exec_id):
+ return await get_pending_reviews_for_chat_session(session_id, user_id)
+
+ graph_exec = await get_graph_execution_meta(
+ user_id=user_id, execution_id=graph_exec_id
+ )
+ if not graph_exec:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"Graph execution #{graph_exec_id} not found",
)
- if not graph_exec:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Graph execution #{graph_exec_id} not found",
- )
return await get_pending_reviews_for_execution(graph_exec_id, user_id)
+ "/session/{chat_session_id}",
+ summary="Get Pending Reviews for Chat Session",
+ response_model=List[PendingHumanReviewModel],
+ responses={
+ 200: {"description": "List of pending reviews for the chat session"},
+ 500: {"description": "Server error", "content": {"application/json": {}}},
+ },
+)
+async def list_pending_reviews_for_chat_session(
+ chat_session_id: str,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> List[PendingHumanReviewModel]:
+ """Get the reviews an AutoPilot chat is waiting on, oldest first.
+
+ Only the caller's own reviews are returned, so another user's chat session
+ id yields an empty list.
+ """
+ return await get_pending_reviews_for_chat_session(chat_session_id, user_id)
+
+
@router.post("/action", response_model=ReviewResponse)
async def process_review_action(
request: ReviewRequest,
@@ -190,19 +210,20 @@ async def process_review_action(
detail=f"Review(s) not found: {', '.join(missing_ids)}",
)
- # Validate all reviews belong to the same execution
- graph_exec_ids = {review.graph_exec_id for review in reviews_map.values()}
- if len(graph_exec_ids) > 1:
+ # Validate all reviews belong to the same execution or chat
+ scopes = {
+ (review.graph_exec_id, review.session_id) for review in reviews_map.values()
+ }
+ if len(scopes) > 1:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="All reviews in a single request must belong to the same execution.",
)
- graph_exec_id = next(iter(graph_exec_ids))
- is_copilot = is_copilot_synthetic_id(graph_exec_id)
+ graph_exec_id, _ = next(iter(scopes))
- # Validate execution status for graph executions (skip for CoPilot synthetic IDs)
- if not is_copilot:
+ # Validate execution status for graph executions; a chat has none
+ if graph_exec_id is not None:
graph_exec_meta = await get_graph_execution_meta(
user_id=user_id, execution_id=graph_exec_id
)
@@ -257,11 +278,12 @@ async def process_review_action(
try:
await create_auto_approval_record(
user_id=user_id,
+ node_id=node_id,
+ payload=review_result.payload,
graph_exec_id=review_result.graph_exec_id,
graph_id=review_result.graph_id,
graph_version=review_result.graph_version,
- node_id=node_id,
- payload=review_result.payload,
+ chat_session_id=review_result.session_id,
)
return (node_id, True)
except Exception as e:
@@ -280,7 +302,7 @@ async def process_review_action(
]
node_id_map = await _resolve_node_ids(
- node_exec_ids_needing_auto_approval, graph_exec_id, is_copilot
+ node_exec_ids_needing_auto_approval, graph_exec_id
)
# Deduplicate by node_id — one auto-approval per node
@@ -322,13 +344,14 @@ async def process_review_action(
if review.status == ReviewStatus.REJECTED
)
- # Resume graph execution only for real graph executions (not CoPilot)
- # CoPilot sessions are resumed by the LLM retrying run_block with review_id
- if not is_copilot and updated_reviews:
+ # Resume graph execution only for real graph executions; a chat is resumed
+ # by the LLM calling resume_capability with the review_id
+ if graph_exec_id is not None and updated_reviews:
still_has_pending = await has_pending_reviews_for_graph_exec(graph_exec_id)
if not still_has_pending:
first_review = next(iter(updated_reviews.values()))
+ assert first_review.graph_id and first_review.graph_version is not None
try:
user = await get_user_by_id(user_id)
diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.py
index aa4443201c..382c69e6ce 100644
--- a/autogpt_platform/backend/backend/api/features/home/attention.py
+++ b/autogpt_platform/backend/backend/api/features/home/attention.py
@@ -218,6 +218,6 @@ def _attention_sort_key(item: HomeAttentionItem) -> tuple[int, datetime]:
def _review_link(review: PendingHumanReviewModel) -> str:
if review.session_id:
return f"/copilot?sessionId={quote(review.session_id)}"
- if review.library_agent_id:
+ if review.library_agent_id and review.graph_exec_id:
return run_link(review.library_agent_id, review.graph_exec_id) or "/library"
return "/library"
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index 6d1af50717..a4327d9508 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -75,7 +75,7 @@ async def build_home_dashboard(
)
graph_ids = list(
{execution.graph_id for execution in data.executions}
- | {review.graph_id for review in data.reviews}
+ | {review.graph_id for review in data.reviews if review.graph_id}
)
work_session_ids = list(
{event.session_id for event in data.work_events if event.session_id}
diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.py
index f459b3ceac..7d2a92b891 100644
--- a/autogpt_platform/backend/backend/blocks/_base.py
+++ b/autogpt_platform/backend/backend/blocks/_base.py
@@ -817,9 +817,9 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
user_id: str,
node_id: str,
node_exec_id: str,
- graph_exec_id: str,
- graph_id: str,
- graph_version: int,
+ graph_exec_id: str | None,
+ graph_id: str | None,
+ graph_version: int | None,
execution_context: "ExecutionContext",
is_graph_execution: bool = True,
**kwargs,
@@ -853,6 +853,9 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
is_graph_execution=is_graph_execution,
organization_id=execution_context.organization_id,
team_id=execution_context.team_id,
+ chat_session_id=(
+ None if is_graph_execution else execution_context.session_id
+ ),
)
if decision is None:
diff --git a/autogpt_platform/backend/backend/blocks/helpers/review.py b/autogpt_platform/backend/backend/blocks/helpers/review.py
index 329d6bd20b..e01e63fde9 100644
--- a/autogpt_platform/backend/backend/blocks/helpers/review.py
+++ b/autogpt_platform/backend/backend/blocks/helpers/review.py
@@ -62,14 +62,15 @@ class HITLReviewHelper:
user_id: str,
node_id: str,
node_exec_id: str,
- graph_exec_id: str,
- graph_id: str,
- graph_version: int,
+ graph_exec_id: Optional[str],
+ graph_id: Optional[str],
+ graph_version: Optional[int],
block_name: str = "Block",
editable: bool = False,
is_graph_execution: bool = True,
organization_id: Optional[str] = None,
team_id: Optional[str] = None,
+ chat_session_id: Optional[str] = None,
) -> Optional[ReviewResult]:
"""
Handle a review request for a block that requires human review.
@@ -82,6 +83,7 @@ class HITLReviewHelper:
graph_exec_id: ID of the graph execution
graph_id: ID of the graph
graph_version: Version of the graph
+ chat_session_id: The chat asking, when not a graph execution
block_name: Name of the block requesting review
editable: Whether the reviewer can edit the data
@@ -101,10 +103,11 @@ class HITLReviewHelper:
# Check if this node has already been approved (normal or auto-approval)
if approval_result := await HITLReviewHelper.check_approval(
node_exec_id=node_exec_id,
- graph_exec_id=graph_exec_id,
node_id=node_id,
user_id=user_id,
input_data=input_data,
+ graph_exec_id=graph_exec_id,
+ chat_session_id=chat_session_id,
):
logger.info(
f"Block {block_name} skipping review for node {node_exec_id} - "
@@ -137,6 +140,7 @@ class HITLReviewHelper:
graph_exec_id=graph_exec_id,
graph_id=graph_id,
graph_version=graph_version,
+ chat_session_id=chat_session_id,
input_data=input_data,
message=block_name, # Use block_name directly as the message
editable=editable,
@@ -169,14 +173,15 @@ class HITLReviewHelper:
user_id: str,
node_id: str,
node_exec_id: str,
- graph_exec_id: str,
- graph_id: str,
- graph_version: int,
+ graph_exec_id: Optional[str],
+ graph_id: Optional[str],
+ graph_version: Optional[int],
block_name: str = "Block",
editable: bool = False,
is_graph_execution: bool = True,
organization_id: Optional[str] = None,
team_id: Optional[str] = None,
+ chat_session_id: Optional[str] = None,
) -> Optional[ReviewDecision]:
"""
Handle a review request and return the decision in a single call.
@@ -189,6 +194,7 @@ class HITLReviewHelper:
graph_exec_id: ID of the graph execution
graph_id: ID of the graph
graph_version: Version of the graph
+ chat_session_id: The chat asking, when not a graph execution
block_name: Name of the block requesting review
editable: Whether the reviewer can edit the data
@@ -209,6 +215,7 @@ class HITLReviewHelper:
is_graph_execution=is_graph_execution,
organization_id=organization_id,
team_id=team_id,
+ chat_session_id=chat_session_id,
)
if review_result is None:
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.py
index a8a97f69d8..af122b18b0 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py
@@ -11,7 +11,6 @@ from pydantic import ValidationError
from backend.api.features.experts.models import Expert
from backend.api.features.graph_executions.review.model import PendingHumanReviewModel
-from backend.copilot.constants import COPILOT_SESSION_PREFIX
from backend.data.db_accessors import (
execution_db,
experts_db,
@@ -101,20 +100,21 @@ def compose_briefing(
# every later LLM turn of that session. The renderer points the overflow
# at the needs-attention list.
for review in reviews[:_MAX_DECISION_ITEMS]:
- if review.graph_exec_id.startswith(COPILOT_SESSION_PREFIX):
- session_id = review.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)
- link = f"/copilot?sessionId={quote(session_id)}"
+ if review.session_id:
+ link = f"/copilot?sessionId={quote(review.session_id)}"
else:
- info = agent_info_by_graph_id.get(review.graph_id)
+ info = agent_info_by_graph_id.get(review.graph_id or "")
link = (
- run_link(info.library_agent_id if info else None, review.graph_exec_id)
+ run_link(
+ info.library_agent_id if info else None, review.graph_exec_id or ""
+ )
or _LIBRARY_LINK
)
# _enrich_pending_reviews already resolved expert attribution on the
# review model (including copilot-session reviews and executions older
# than the 24h window); the local lookup only backfills gaps.
fallback = experts_by_id.get(
- review.expert_id or expert_id_by_exec.get(review.graph_exec_id) or ""
+ review.expert_id or expert_id_by_exec.get(review.graph_exec_id or "") or ""
)
decision_items.append(
BriefingDecisionItem(
@@ -221,7 +221,9 @@ async def _compose_fresh_briefing(
# Resolve only the graphs actually referenced, rather than paging the
# library: paging it would drop the very agent being briefed for a user
# with >100 agents, leaving an unlinkable "Agent" row.
- graph_ids = list({e.graph_id for e in executions} | {r.graph_id for r in reviews})
+ graph_ids = list(
+ {e.graph_id for e in executions} | {r.graph_id for r in reviews if r.graph_id}
+ )
refs = await library_db().get_library_agent_refs_by_graph_ids(user_id, graph_ids)
agent_info: dict[str, AgentInfo] = {
ref.graph_id: AgentInfo(ref.name or DEFAULT_AGENT_NAME, ref.id) for ref in refs
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
index b700234119..da3b02efe2 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
@@ -82,6 +82,7 @@ def make_review(
expert_id=None,
expert_name=None,
expert_avatar_url=None,
+ session_id=None,
):
from unittest.mock import MagicMock
@@ -92,6 +93,7 @@ def make_review(
instructions,
)
r.graph_id = graph_id
+ r.session_id = session_id
# Explicit None defaults matter: MagicMock auto-attributes are truthy and
# would short-circuit compose_briefing's enriched-attribution preference.
r.expert_id = expert_id
@@ -155,7 +157,7 @@ def test_copilot_review_links_to_session():
content = compose_briefing(
experts=[make_expert()],
executions=[make_exec()],
- reviews=[make_review(graph_exec_id="copilot-session-abc123")],
+ reviews=[make_review(graph_exec_id=None, graph_id=None, session_id="abc123")],
agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},
generated_at=NOW,
tz_name="UTC",
@@ -171,7 +173,9 @@ def test_decision_prefers_enriched_expert_attribution():
executions=[],
reviews=[
make_review(
- graph_exec_id="copilot-session-abc123",
+ graph_exec_id=None,
+ graph_id=None,
+ session_id="abc123",
expert_id="exp-2",
expert_name="Bob",
expert_avatar_url="https://a/b.png",
diff --git a/autogpt_platform/backend/backend/copilot/briefing/models.py b/autogpt_platform/backend/backend/copilot/briefing/models.py
index a79c9cab32..405f306feb 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/models.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/models.py
@@ -33,7 +33,7 @@ class BriefingRunItem(BaseModel):
class BriefingDecisionItem(BaseModel):
node_exec_id: str
- graph_exec_id: str
+ graph_exec_id: str | None
title: str
expert_id: str | None
expert_name: str | None
diff --git a/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
index 7b84518ba3..55c4638b34 100644
--- a/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
+++ b/autogpt_platform/backend/backend/copilot/capabilities/mcp_review.py
@@ -19,7 +19,6 @@ from pydantic import BaseModel
from backend.copilot.constants import (
COPILOT_NODE_EXEC_ID_SEPARATOR,
- COPILOT_SESSION_PREFIX,
COPILOT_SYNTHETIC_ID_PREFIX,
)
from backend.data.db_accessors import review_db
@@ -79,11 +78,10 @@ async def open_mcp_review(
An identical pending call (same server, tool and arguments) reuses its
review so a retried ``run_capability`` does not stack approvals.
"""
- graph_exec_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
node_id = mcp_review_node_id(host)
data = payload.model_dump()
- for review in await review_db().get_pending_reviews_for_execution(
- graph_exec_id, user_id
+ for review in await review_db().get_pending_reviews_for_chat_session(
+ session_id, user_id
):
if (
review.node_id == node_id
@@ -95,9 +93,7 @@ async def open_mcp_review(
await review_db().get_or_create_human_review(
user_id=user_id,
node_exec_id=review_id,
- graph_exec_id=graph_exec_id,
- graph_id=graph_exec_id,
- graph_version=1,
+ chat_session_id=session_id,
input_data=data,
message=(
f"Run MCP tool '{payload.tool}' on {host} with the shown arguments? "
diff --git a/autogpt_platform/backend/backend/copilot/constants.py b/autogpt_platform/backend/backend/copilot/constants.py
index 4d30b520d4..2978dc6f91 100644
--- a/autogpt_platform/backend/backend/copilot/constants.py
+++ b/autogpt_platform/backend/backend/copilot/constants.py
@@ -37,7 +37,9 @@ STREAM_ERROR_MARKER = f"{COPILOT_SYSTEM_PREFIX} The assistant ran into an error
# in PendingHumanReview and other tables.
COPILOT_SYNTHETIC_ID_PREFIX = "copilot-"
-# Sub-prefixes for session-scoped and node-scoped synthetic IDs.
+# Sub-prefixes for session-scoped and node-scoped synthetic IDs. The session
+# prefix names a chat's block runs in credit history; reviews carry a real
+# session id instead and only read it back from rows written before that.
COPILOT_SESSION_PREFIX = f"{COPILOT_SYNTHETIC_ID_PREFIX}session-"
COPILOT_NODE_PREFIX = f"{COPILOT_SYNTHETIC_ID_PREFIX}node-"
@@ -85,6 +87,13 @@ def is_copilot_synthetic_id(id_value: str) -> bool:
return id_value.startswith(COPILOT_SYNTHETIC_ID_PREFIX)
+def legacy_chat_session_id(graph_exec_id: str | None) -> str | None:
+ """The chat session behind an old ``copilot-session-<id>`` graph exec id."""
+ if graph_exec_id and graph_exec_id.startswith(COPILOT_SESSION_PREFIX):
+ return graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)
+ return None
+
+
def parse_node_id_from_exec_id(node_exec_id: str) -> str:
"""Extract node_id from a synthetic node_exec_id.
diff --git a/autogpt_platform/backend/backend/copilot/tools/block_display_test.py b/autogpt_platform/backend/backend/copilot/tools/block_display_test.py
index 8dce2b7831..ec92beae69 100644
--- a/autogpt_platform/backend/backend/copilot/tools/block_display_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/block_display_test.py
@@ -6,7 +6,6 @@ import pytest
from prisma.enums import ReviewStatus
from backend.blocks._base import BlockType
-from backend.copilot.constants import COPILOT_SESSION_PREFIX
from backend.copilot.model import ChatSession
from backend.copilot.tool_display import tool_display_context
from backend.copilot.tools.continue_run_block import ContinueRunBlockTool
@@ -166,7 +165,7 @@ async def test_unavailable_continuation_does_not_emit_a_name(unavailable: str):
if unavailable == "review_missing":
database.get_reviews_by_node_exec_ids.return_value = {}
elif unavailable == "wrong_session":
- review.graph_exec_id = "another-session"
+ review.session_id = "another-session"
elif unavailable in ("waiting", "rejected"):
review.status = (
ReviewStatus.WAITING if unavailable == "waiting" else ReviewStatus.REJECTED
@@ -226,7 +225,7 @@ def _review_database(session: ChatSession, review_id: str) -> MagicMock:
database.get_reviews_by_node_exec_ids = AsyncMock(
return_value={
review_id: MagicMock(
- graph_exec_id=f"{COPILOT_SESSION_PREFIX}{session.session_id}",
+ session_id=session.session_id,
status=ReviewStatus.APPROVED,
payload={},
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
index b3cd7d5684..53d0fac273 100644
--- a/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/capability_tools_test.py
@@ -15,7 +15,6 @@ from backend.copilot.capabilities.mcp_review import COPILOT_MCP_NODE_PREFIX
from backend.copilot.capabilities.ranking import ConnectionState
from backend.copilot.capabilities.registry import get_registry
from backend.copilot.capabilities.sources import EAGER_CORE
-from backend.copilot.constants import COPILOT_SESSION_PREFIX
from backend.copilot.context import set_execution_context
from backend.copilot.permissions import CopilotPermissions
from backend.copilot.prompting import SHARED_TOOL_NOTES
@@ -737,7 +736,7 @@ def _review(
review.node_exec_id = review_id
review.status = status
review.payload = payload
- review.graph_exec_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
+ review.session_id = session_id
return review
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
index fefa125a4c..ed7800b0d5 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
@@ -6,11 +6,7 @@ from typing import Any
from prisma.enums import ReviewStatus
from backend.blocks import get_block
-from backend.copilot.constants import (
- COPILOT_NODE_PREFIX,
- COPILOT_SESSION_PREFIX,
- parse_node_id_from_exec_id,
-)
+from backend.copilot.constants import COPILOT_NODE_PREFIX, parse_node_id_from_exec_id
from backend.copilot.model import ChatSession
from backend.copilot.tool_display import emit_tool_display_name
from backend.data.db_accessors import review_db
@@ -87,8 +83,7 @@ class ContinueRunBlockTool(BaseTool):
)
# Validate the review belongs to this session
- expected_graph_exec_id = f"{COPILOT_SESSION_PREFIX}{session_id}"
- if review.graph_exec_id != expected_graph_exec_id:
+ if review.session_id != session_id:
return ErrorResponse(
message="Review does not belong to this session.",
session_id=session_id,
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
index 4ef0a45726..8a827dafb6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block_test.py
@@ -16,14 +16,14 @@ def _make_review_model(
node_exec_id: str,
status: ReviewStatus = ReviewStatus.APPROVED,
payload: dict | None = None,
- graph_exec_id: str = "",
+ session_id: str = "",
):
"""Create a mock PendingHumanReviewModel."""
mock = MagicMock()
mock.node_exec_id = node_exec_id
mock.status = status
mock.payload = payload or {"text": "hello"}
- mock.graph_exec_id = graph_exec_id
+ mock.session_id = session_id
return mock
@@ -68,9 +68,8 @@ class TestContinueRunBlock:
tool = ContinueRunBlockTool()
session = make_session(user_id=_TEST_USER_ID)
review_id = "copilot-node-some-block:abc12345"
- graph_exec_id = f"copilot-session-{session.session_id}"
review = _make_review_model(
- review_id, status=ReviewStatus.WAITING, graph_exec_id=graph_exec_id
+ review_id, status=ReviewStatus.WAITING, session_id=session.session_id
)
mock_db = MagicMock()
@@ -96,9 +95,8 @@ class TestContinueRunBlock:
tool = ContinueRunBlockTool()
session = make_session(user_id=_TEST_USER_ID)
review_id = "copilot-node-some-block:abc12345"
- graph_exec_id = f"copilot-session-{session.session_id}"
review = _make_review_model(
- review_id, status=ReviewStatus.REJECTED, graph_exec_id=graph_exec_id
+ review_id, status=ReviewStatus.REJECTED, session_id=session.session_id
)
mock_db = MagicMock()
@@ -124,13 +122,12 @@ class TestContinueRunBlock:
tool = ContinueRunBlockTool()
session = make_session(user_id=_TEST_USER_ID)
review_id = "copilot-node-delete-branch-id:abc12345"
- graph_exec_id = f"copilot-session-{session.session_id}"
input_data = {"repo_url": "https://github.com/test/repo", "branch": "main"}
review = _make_review_model(
review_id,
status=ReviewStatus.APPROVED,
payload=input_data,
- graph_exec_id=graph_exec_id,
+ session_id=session.session_id,
)
mock_block = MagicMock()
@@ -193,9 +190,7 @@ async def test_continuation_resolves_credentials_under_the_experts_grants():
tool = ContinueRunBlockTool()
session = make_session(user_id=_TEST_USER_ID, expert_id="expert-a")
review_id = "copilot-node-some-block:abc12345"
- review = _make_review_model(
- review_id, graph_exec_id=f"copilot-session-{session.session_id}"
- )
+ review = _make_review_model(review_id, session_id=session.session_id)
mock_db = MagicMock()
mock_db.get_reviews_by_node_exec_ids = AsyncMock(return_value={review_id: review})
block = MagicMock()
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index d9b3f3b4f6..ae53842a87 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -1007,13 +1007,12 @@ async def check_hitl_review(
"""
block = prep.block
block_id = prep.block_id
- synthetic_graph_id = prep.synthetic_graph_id
synthetic_node_id = prep.synthetic_node_id
input_data = prep.input_data
# Reuse an existing WAITING review for identical input (LLM retry guard)
- existing_reviews = await review_db().get_pending_reviews_for_execution(
- synthetic_graph_id, user_id
+ existing_reviews = await review_db().get_pending_reviews_for_chat_session(
+ session_id, user_id
)
existing_review = next(
(
@@ -1036,7 +1035,6 @@ async def check_hitl_review(
block_id=block_id,
block_name=block.name,
review_id=existing_review.node_exec_id,
- graph_exec_id=synthetic_graph_id,
input_data=input_data,
)
@@ -1046,11 +1044,9 @@ async def check_hitl_review(
review_context = ExecutionContext(
user_id=user_id,
- graph_id=synthetic_graph_id,
- graph_exec_id=synthetic_graph_id,
- graph_version=1,
node_id=synthetic_node_id,
node_exec_id=synthetic_node_exec_id,
+ session_id=session_id,
sensitive_action_safe_mode=True,
organization_id=organization_id,
team_id=team_id,
@@ -1060,9 +1056,9 @@ async def check_hitl_review(
user_id=user_id,
node_id=synthetic_node_id,
node_exec_id=synthetic_node_exec_id,
- graph_exec_id=synthetic_graph_id,
- graph_id=synthetic_graph_id,
- graph_version=1,
+ graph_exec_id=None,
+ graph_id=None,
+ graph_version=None,
execution_context=review_context,
is_graph_execution=False,
)
@@ -1077,7 +1073,6 @@ async def check_hitl_review(
block_id=block_id,
block_name=block.name,
review_id=synthetic_node_exec_id,
- graph_exec_id=synthetic_graph_id,
input_data=input_data,
)
@@ -1118,7 +1113,6 @@ async def check_spend_approval(
block_id=prep.block_id,
block_name=prep.block.name,
review_id=review_id,
- graph_exec_id=prep.synthetic_graph_id,
input_data=prep.input_data,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index f61e6aaa91..91f9a79a7f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -997,7 +997,7 @@ def _make_hitl_prep(
async def test_check_hitl_no_review_needed() -> None:
prep = _make_hitl_prep(input_data={"action": "read"}, needs_review=False)
mock_rdb = MagicMock()
- mock_rdb.get_pending_reviews_for_execution = AsyncMock(return_value=[])
+ mock_rdb.get_pending_reviews_for_chat_session = AsyncMock(return_value=[])
with patch("backend.copilot.tools.helpers.review_db", return_value=mock_rdb):
result = await check_hitl_review(prep, "user1", "hitl-sess")
@@ -1012,13 +1012,22 @@ async def test_check_hitl_no_review_needed() -> None:
async def test_check_hitl_review_required() -> None:
prep = _make_hitl_prep(input_data={"action": "delete"}, needs_review=True)
mock_rdb = MagicMock()
- mock_rdb.get_pending_reviews_for_execution = AsyncMock(return_value=[])
+ mock_rdb.get_pending_reviews_for_chat_session = AsyncMock(return_value=[])
with patch("backend.copilot.tools.helpers.review_db", return_value=mock_rdb):
result = await check_hitl_review(prep, "user1", "hitl-sess")
assert isinstance(result, ReviewRequiredResponse)
assert result.block_id == "blk-hitl"
+ assert "graph_exec_id" not in result.model_dump()
+ kwargs = prep.block.is_block_exec_need_review.await_args.kwargs
+ assert (kwargs["graph_exec_id"], kwargs["graph_id"]) == (None, None)
+ assert kwargs["is_graph_execution"] is False
+ assert kwargs["execution_context"].session_id == "hitl-sess"
+ assert kwargs["execution_context"].graph_exec_id is None
+ mock_rdb.get_pending_reviews_for_chat_session.assert_awaited_once_with(
+ "hitl-sess", "user1"
+ )
@pytest.mark.asyncio
@@ -1032,7 +1041,7 @@ async def test_check_hitl_reuses_existing_waiting_review() -> None:
existing.node_exec_id = "existing-review-42"
mock_rdb = MagicMock()
- mock_rdb.get_pending_reviews_for_execution = AsyncMock(return_value=[existing])
+ mock_rdb.get_pending_reviews_for_chat_session = AsyncMock(return_value=[existing])
with patch("backend.copilot.tools.helpers.review_db", return_value=mock_rdb):
result = await check_hitl_review(prep, "user1", "hitl-sess")
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 0094e15d35..b285882361 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -1018,9 +1018,6 @@ class ReviewRequiredResponse(ToolResponseBase):
block_id: str
block_name: str
review_id: str = Field(description="The review ID for tracking approval status")
- graph_exec_id: str = Field(
- description="The graph execution ID for fetching review status"
- )
input_data: dict[str, Any] = Field(
description="The input data that requires review"
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/resume_capability.py b/autogpt_platform/backend/backend/copilot/tools/resume_capability.py
index 17366d9953..f3377ee916 100644
--- a/autogpt_platform/backend/backend/copilot/tools/resume_capability.py
+++ b/autogpt_platform/backend/backend/copilot/tools/resume_capability.py
@@ -20,7 +20,6 @@ from backend.copilot.capabilities.mcp_review import (
)
from backend.copilot.constants import (
COPILOT_NODE_PREFIX,
- COPILOT_SESSION_PREFIX,
SPEND_REVIEW_MARKER,
parse_node_id_from_exec_id,
)
@@ -138,7 +137,7 @@ async def _load_approved_review(
),
session_id=session_id,
)
- if review.graph_exec_id != f"{COPILOT_SESSION_PREFIX}{session_id}":
+ if review.session_id != session_id:
return ErrorResponse(
message="Review does not belong to this session.", session_id=session_id
)
@@ -203,7 +202,6 @@ async def _resume_mcp(
block_id=payload.server_url,
block_name=f"{host}/{payload.tool}",
review_id=new_id,
- graph_exec_id=f"{COPILOT_SESSION_PREFIX}{session.session_id}",
input_data=fresh.model_dump(),
)
result = await RunMCPToolTool()._execute(
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index d803360850..08852c221a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -1676,7 +1676,7 @@ class TestSpendApproval:
assert isinstance(response, ReviewRequiredResponse)
assert response.review_id == "copilot-node-expert-spend:expert-1:abcd1234"
- assert response.graph_exec_id.startswith("copilot-session-")
+ assert "graph_exec_id" not in response.model_dump()
assert not block.executed
gate.spend_approval_required.assert_awaited_once_with(_TEST_USER_ID, "expert-1")
assert (
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_capability.py b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
index 959247d6bc..b3dc3039c1 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_capability.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_capability.py
@@ -21,7 +21,6 @@ from backend.copilot.capabilities.models import SKILL_TOOL, CapabilityEntry
from backend.copilot.capabilities.registry import configured_tool, get_registry
from backend.copilot.capabilities.resolve import resolve_entry
from backend.copilot.capabilities.sources.mcp_catalog import setup_hint
-from backend.copilot.constants import COPILOT_SESSION_PREFIX
from backend.copilot.model import ChatSession
from backend.copilot.permissions import BLOCK_GATE, MCP_GATE
from backend.copilot.tool_display import emit_tool_display_name
@@ -282,7 +281,6 @@ async def _run_mcp(
block_id=entry.id if entry else server_url,
block_name=f"{host}/{tool_name}",
review_id=review_id,
- graph_exec_id=f"{COPILOT_SESSION_PREFIX}{session.session_id}",
input_data=review.model_dump(),
)
if tool_name:
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index cbbd06cefa..d5e0d6f626 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -133,6 +133,7 @@ from backend.data.human_review import (
check_approval,
delete_review_by_node_exec_id,
get_or_create_human_review,
+ get_pending_reviews_for_chat_session,
get_pending_reviews_for_execution,
get_pending_reviews_for_user,
get_reviews_by_node_exec_ids,
@@ -370,6 +371,7 @@ class DatabaseManager(AppService):
delete_review_by_node_exec_id = _(delete_review_by_node_exec_id)
get_or_create_human_review = _(get_or_create_human_review)
get_pending_reviews_for_execution = _(get_pending_reviews_for_execution)
+ get_pending_reviews_for_chat_session = _(get_pending_reviews_for_chat_session)
get_pending_reviews_for_user = _(get_pending_reviews_for_user)
get_reviews_by_node_exec_ids = _(get_reviews_by_node_exec_ids)
has_pending_reviews_for_graph_exec = _(has_pending_reviews_for_graph_exec)
@@ -774,6 +776,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
delete_review_by_node_exec_id = d.delete_review_by_node_exec_id
get_or_create_human_review = d.get_or_create_human_review
get_pending_reviews_for_execution = d.get_pending_reviews_for_execution
+ get_pending_reviews_for_chat_session = d.get_pending_reviews_for_chat_session
get_pending_reviews_for_user = d.get_pending_reviews_for_user
get_reviews_by_node_exec_ids = d.get_reviews_by_node_exec_ids
update_review_processed_status = d.update_review_processed_status
diff --git a/autogpt_platform/backend/backend/data/human_review.py b/autogpt_platform/backend/backend/data/human_review.py
index 98cca0a5d0..92b8612767 100644
--- a/autogpt_platform/backend/backend/data/human_review.py
+++ b/autogpt_platform/backend/backend/data/human_review.py
@@ -26,6 +26,7 @@ from backend.api.features.graph_executions.review.model import (
from backend.copilot.constants import (
COPILOT_SESSION_PREFIX,
is_copilot_synthetic_id,
+ legacy_chat_session_id,
parse_node_id_from_exec_id,
)
from backend.data.execution import get_graph_execution_meta
@@ -48,7 +49,9 @@ class ReviewResult(BaseModel):
node_exec_id: str
-async def _sync_awaiting_review_safely(user_id: str, graph_id: str) -> None:
+async def _sync_awaiting_review_safely(
+ user_id: str, graph_id: str | None, chat_session_id: str | None = None
+) -> None:
"""Keep the awaiting-review alert from deciding whether a review succeeds.
The alert is a notification side effect. Raising here would report failure
@@ -57,26 +60,28 @@ async def _sync_awaiting_review_safely(user_id: str, graph_id: str) -> None:
the caller back over a notification problem.
"""
try:
- await sync_awaiting_review(user_id, graph_id)
+ await sync_awaiting_review(user_id, graph_id, chat_session_id=chat_session_id)
except Exception:
logger.warning(
- "Could not sync the awaiting-review alert for graph %s",
- graph_id,
+ "Could not sync the awaiting-review alert for %s",
+ chat_session_id or graph_id,
exc_info=True,
)
-def get_auto_approve_key(graph_exec_id: str, node_id: str) -> str:
- """Generate the special nodeExecId key for auto-approval records."""
- return f"auto_approve_{graph_exec_id}_{node_id}"
+def get_auto_approve_key(scope_id: str, node_id: str) -> str:
+ """The nodeExecId of an auto-approval record; ``scope_id`` is the graph
+ execution or the chat session the approval holds for."""
+ return f"auto_approve_{scope_id}_{node_id}"
async def check_approval(
node_exec_id: str,
- graph_exec_id: str,
node_id: str,
user_id: str,
input_data: SafeJsonData | None = None,
+ graph_exec_id: str | None = None,
+ chat_session_id: str | None = None,
) -> Optional[ReviewResult]:
"""
Check if there's an existing approval for this node execution.
@@ -87,22 +92,30 @@ async def check_approval(
Args:
node_exec_id: ID of the node execution
- graph_exec_id: ID of the graph execution
node_id: ID of the node definition (not execution)
user_id: ID of the user (for data isolation)
input_data: Current input data (used for auto-approvals to avoid stale data)
+ graph_exec_id / chat_session_id: the graph execution or chat asking; one of them
Returns:
ReviewResult if approval found (either normal or auto), None otherwise
"""
- auto_approve_key = get_auto_approve_key(graph_exec_id, node_id)
+ graph_exec_id, chat_session_id = _review_scope(graph_exec_id, chat_session_id)
+ scope_id = graph_exec_id or chat_session_id
+ assert scope_id
+ auto_approve_keys = [get_auto_approve_key(scope_id, node_id)]
+ if chat_session_id:
+ # Records made before chat reviews had a session of their own.
+ auto_approve_keys.append(
+ get_auto_approve_key(f"{COPILOT_SESSION_PREFIX}{chat_session_id}", node_id)
+ )
# Check for either normal approval or auto-approval in a single query
existing_review = await PendingHumanReview.prisma().find_first(
where={
"OR": [
{"nodeExecId": node_exec_id},
- {"nodeExecId": auto_approve_key},
+ *({"nodeExecId": key} for key in auto_approve_keys),
],
"status": ReviewStatus.APPROVED,
"userId": user_id,
@@ -110,10 +123,10 @@ async def check_approval(
)
if existing_review:
- is_auto_approval = existing_review.nodeExecId == auto_approve_key
+ is_auto_approval = existing_review.nodeExecId in auto_approve_keys
logger.info(
f"Found {'auto-' if is_auto_approval else ''}approval for node {node_id} "
- f"(exec: {node_exec_id}) in execution {graph_exec_id}"
+ f"(exec: {node_exec_id}) in {scope_id}"
)
# For auto-approvals, use current input_data to avoid replaying stale payload
# For normal approvals, use the stored payload (which may have been edited)
@@ -138,11 +151,12 @@ async def check_approval(
async def create_auto_approval_record(
user_id: str,
- graph_exec_id: str,
- graph_id: str,
- graph_version: int,
node_id: str,
payload: SafeJsonData,
+ graph_exec_id: str | None = None,
+ graph_id: str | None = None,
+ graph_version: int | None = None,
+ chat_session_id: str | None = None,
) -> None:
"""
Create an auto-approval record for a node in this execution.
@@ -153,18 +167,19 @@ async def create_auto_approval_record(
Raises:
ValueError: If the graph execution doesn't belong to the user
"""
- # Validate ownership: if a graph execution record exists, it must belong
- # to this user. Non-graph executions (e.g. CoPilot) won't have a record.
- if not is_copilot_synthetic_id(
- graph_exec_id
- ) and not await get_graph_execution_meta(
+ graph_exec_id, chat_session_id = _review_scope(graph_exec_id, chat_session_id)
+ # A chat review's session is the caller's by construction (the review row
+ # was looked up by userId); a graph execution is checked here.
+ if graph_exec_id is not None and not await get_graph_execution_meta(
user_id=user_id, execution_id=graph_exec_id
):
raise ValueError(
f"Graph execution {graph_exec_id} not found or doesn't belong to user {user_id}"
)
- auto_approve_key = get_auto_approve_key(graph_exec_id, node_id)
+ scope_id = graph_exec_id or chat_session_id
+ assert scope_id
+ auto_approve_key = get_auto_approve_key(scope_id, node_id)
await PendingHumanReview.prisma().upsert(
where={"nodeExecId": auto_approve_key},
@@ -172,9 +187,9 @@ async def create_auto_approval_record(
"create": {
"nodeExecId": auto_approve_key,
"userId": user_id,
- "graphExecId": graph_exec_id,
- "graphId": graph_id,
- "graphVersion": graph_version,
+ **_scope_columns(
+ graph_exec_id, graph_id, graph_version, chat_session_id
+ ),
"payload": SafeJson(payload),
"instructions": "Auto-approval record",
"editable": False,
@@ -190,12 +205,13 @@ async def create_auto_approval_record(
async def get_or_create_human_review(
user_id: str,
node_exec_id: str,
- graph_exec_id: str,
- graph_id: str,
- graph_version: int,
input_data: SafeJsonData,
message: str,
editable: bool,
+ graph_exec_id: str | None = None,
+ graph_id: str | None = None,
+ graph_version: int | None = None,
+ chat_session_id: str | None = None,
organization_id: str | None = None,
team_id: str | None = None,
) -> Optional[ReviewResult]:
@@ -207,16 +223,18 @@ async def get_or_create_human_review(
Args:
user_id: ID of the user who owns this review
node_exec_id: ID of the node execution
- graph_exec_id: ID of the graph execution
- graph_id: ID of the graph template
- graph_version: Version of the graph template
input_data: The data to be reviewed
message: Instructions for the reviewer
editable: Whether the data can be edited
+ graph_exec_id, graph_id, graph_version: the graph execution asking, or
+ chat_session_id: the chat asking — exactly one of the two
Returns:
ReviewResult if the review is complete, None if waiting for human input
"""
+ graph_exec_id, chat_session_id = _review_scope(graph_exec_id, chat_session_id)
+ if chat_session_id:
+ graph_id = graph_version = None
try:
logger.debug(f"Getting or creating review for node {node_exec_id}")
@@ -227,9 +245,9 @@ async def get_or_create_human_review(
"create": {
"userId": user_id,
"nodeExecId": node_exec_id,
- "graphExecId": graph_exec_id,
- "graphId": graph_id,
- "graphVersion": graph_version,
+ **_scope_columns(
+ graph_exec_id, graph_id, graph_version, chat_session_id
+ ),
"payload": SafeJson(input_data),
"instructions": message,
"editable": editable,
@@ -258,7 +276,7 @@ async def get_or_create_human_review(
if review.status == ReviewStatus.WAITING:
# Nothing sends until a human acts, which is exactly the shape of an
# Alert. The engine debounces and coalesces from here.
- await _sync_awaiting_review_safely(user_id, graph_id)
+ await _sync_awaiting_review_safely(user_id, graph_id, chat_session_id)
return None
else:
return ReviewResult(
@@ -270,6 +288,56 @@ async def get_or_create_human_review(
)
+def _review_scope(
+ graph_exec_id: str | None, chat_session_id: str | None
+) -> tuple[str | None, str | None]:
+ """``(graph_exec_id, chat_session_id)`` with exactly one set.
+
+ Callers that still pass a chat as ``copilot-session-<id>`` in
+ ``graph_exec_id`` are converted here, so their rows land in the chat shape.
+ """
+ legacy_session_id = legacy_chat_session_id(graph_exec_id)
+ if legacy_session_id:
+ return None, chat_session_id or legacy_session_id
+ if (graph_exec_id is None) == (chat_session_id is None):
+ raise ValueError("A review needs a graph execution or a chat session")
+ return graph_exec_id, chat_session_id
+
+
+def _alert_scope(
+ review: PendingHumanReview,
+) -> tuple[str, str | None, str | None]:
+ """``(user, graph id, session id)`` of the alert a review counts toward;
+ a chat's legacy and new rows share one."""
+ chat_session_id = review.chatSessionId or legacy_chat_session_id(review.graphExecId)
+ if chat_session_id:
+ return review.userId, None, chat_session_id
+ return review.userId, review.graphId, None
+
+
+def _scope_columns(
+ graph_exec_id: str | None,
+ graph_id: str | None,
+ graph_version: int | None,
+ chat_session_id: str | None,
+) -> dict:
+ if chat_session_id:
+ # The legacy graph values let pods on the previous deploy, which read
+ # these columns as non-null, still load the row; drop with the cleanup.
+ legacy_id = f"{COPILOT_SESSION_PREFIX}{chat_session_id}"
+ return {
+ "chatSessionId": chat_session_id,
+ "graphExecId": legacy_id,
+ "graphId": legacy_id,
+ "graphVersion": 1,
+ }
+ return {
+ "graphExecId": graph_exec_id,
+ "graphId": graph_id,
+ "graphVersion": graph_version,
+ }
+
+
async def get_pending_review_by_node_exec_id(
node_exec_id: str, user_id: str
) -> Optional[PendingHumanReviewModel]:
@@ -427,18 +495,11 @@ async def _enrich_pending_reviews(
- expert attribution (from the graph execution, or from the chat
session for CoPilot run_capability reviews)
- the requesting agent's display name and library agent id
- - the chat session id, for CoPilot run_capability reviews
Mutates and returns the given models in place.
"""
- real_exec_ids = [
- r.graph_exec_id for r in reviews if not is_copilot_synthetic_id(r.graph_exec_id)
- ]
- session_ids = [
- r.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)
- for r in reviews
- if r.graph_exec_id.startswith(COPILOT_SESSION_PREFIX)
- ]
+ real_exec_ids = [r.graph_exec_id for r in reviews if r.graph_exec_id]
+ session_ids = [r.session_id for r in reviews if r.session_id]
real_node_exec_ids = [
r.node_exec_id for r in reviews if not is_copilot_synthetic_id(r.node_exec_id)
]
@@ -484,7 +545,7 @@ async def _enrich_pending_reviews(
else:
r.node_id = node_id_by_exec.get(r.node_exec_id, r.node_exec_id)
- execution = exec_by_id.get(r.graph_exec_id)
+ execution = exec_by_id.get(r.graph_exec_id) if r.graph_exec_id else None
if execution:
r.expert_id = execution.expertId
if execution.Expert:
@@ -497,10 +558,8 @@ async def _enrich_pending_reviews(
r.agent_name = (lib_agent.name if lib_agent else None) or (
execution.AgentGraph.name if execution.AgentGraph else None
)
- elif r.graph_exec_id.startswith(COPILOT_SESSION_PREFIX):
- session_id = r.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)
- r.session_id = session_id
- session = session_by_id.get(session_id)
+ elif r.session_id:
+ session = session_by_id.get(r.session_id)
if session:
r.expert_id = session.expertId
if session.Expert:
@@ -559,9 +618,8 @@ async def get_pending_reviews_for_execution(
Returns:
List of pending review models with node_id included
"""
- # Local import to avoid event loop conflicts in tests
- from backend.data.execution import get_node_execution
-
+ if chat_session_id := legacy_chat_session_id(graph_exec_id):
+ return await get_pending_reviews_for_chat_session(chat_session_id, user_id)
reviews = await PendingHumanReview.prisma().find_many(
where={
"userId": user_id,
@@ -570,6 +628,33 @@ async def get_pending_reviews_for_execution(
},
order={"createdAt": "asc"},
)
+ return await _with_node_ids(reviews)
+
+
+async def get_pending_reviews_for_chat_session(
+ chat_session_id: str, user_id: str
+) -> list[PendingHumanReviewModel]:
+ """The reviews a chat is waiting on, oldest first."""
+ reviews = await PendingHumanReview.prisma().find_many(
+ where={
+ "userId": user_id,
+ "OR": [
+ {"chatSessionId": chat_session_id},
+ # Rows an older deploy wrote in the synthetic-graph shape.
+ {"graphExecId": f"{COPILOT_SESSION_PREFIX}{chat_session_id}"},
+ ],
+ "status": ReviewStatus.WAITING,
+ },
+ order={"createdAt": "asc"},
+ )
+ return await _with_node_ids(reviews)
+
+
+async def _with_node_ids(
+ reviews: list[PendingHumanReview],
+) -> list[PendingHumanReviewModel]:
+ # Local import to avoid event loop conflicts in tests
+ from backend.data.execution import get_node_execution
# Fetch node_id for each review from NodeExecution
result = []
@@ -676,8 +761,8 @@ async def process_all_reviews_for_execution(
# Re-derive the "waiting on your review" alert from the live queue, so
# clearing the last item resolves it rather than leaving a stale alert.
- for review in {(r.userId, r.graphId) for r in reviews_to_process}:
- await _sync_awaiting_review_safely(review[0], review[1])
+ for scope in {_alert_scope(r) for r in reviews_to_process}:
+ await _sync_awaiting_review_safely(*scope)
# Note: Execution resumption is now handled at the API layer after ALL reviews
# for an execution are processed (both approved and rejected)
diff --git a/autogpt_platform/backend/backend/data/human_review_enrichment_test.py b/autogpt_platform/backend/backend/data/human_review_enrichment_test.py
index 8e376353e3..30b2fb75d3 100644
--- a/autogpt_platform/backend/backend/data/human_review_enrichment_test.py
+++ b/autogpt_platform/backend/backend/data/human_review_enrichment_test.py
@@ -25,7 +25,7 @@ from prisma.models import (
User,
)
-from backend.copilot.constants import COPILOT_NODE_PREFIX, COPILOT_SESSION_PREFIX
+from backend.copilot.constants import COPILOT_NODE_PREFIX
from backend.copilot.db import create_chat_session
from backend.data.human_review import get_pending_reviews_for_user
from backend.util.json import SafeJson
@@ -122,7 +122,6 @@ async def test_pending_reviews_are_enriched(server: SpinTestServer):
f"sess-{uuid4().hex[:8]}", user_id, expert_id=ana.id
)
session_ids.append(session.session_id)
- copilot_exec_id = f"{COPILOT_SESSION_PREFIX}{session.session_id}"
await PendingHumanReview.prisma().create(
data={
@@ -140,9 +139,7 @@ async def test_pending_reviews_are_enriched(server: SpinTestServer):
data={
"nodeExecId": f"{COPILOT_NODE_PREFIX}some-block:{uuid4().hex[:8]}",
"userId": user_id,
- "graphExecId": copilot_exec_id,
- "graphId": copilot_exec_id,
- "graphVersion": 1,
+ "chatSessionId": session.session_id,
"payload": SafeJson({"foo": "bar"}),
"editable": True,
"status": ReviewStatus.WAITING,
@@ -150,9 +147,7 @@ async def test_pending_reviews_are_enriched(server: SpinTestServer):
)
reviews = await get_pending_reviews_for_user(user_id, 1, 25)
- by_exec = {r.graph_exec_id: r for r in reviews}
-
- real = by_exec[real_exec_id]
+ real = next(r for r in reviews if r.graph_exec_id == real_exec_id)
assert real.expert_id == ana.id
assert real.expert_name == "Ana"
assert real.expert_avatar_url == "https://example.com/ana.png"
@@ -160,8 +155,8 @@ async def test_pending_reviews_are_enriched(server: SpinTestServer):
assert real.library_agent_id == lib_agent.id
assert real.session_id is None
- copilot = by_exec[copilot_exec_id]
- assert copilot.session_id == session.session_id
+ copilot = next(r for r in reviews if r.session_id == session.session_id)
+ assert copilot.graph_exec_id is None
assert copilot.expert_id == ana.id
assert copilot.expert_name == "Ana"
finally:
diff --git a/autogpt_platform/backend/backend/data/human_review_scope_test.py b/autogpt_platform/backend/backend/data/human_review_scope_test.py
new file mode 100644
index 0000000000..f320072f2e
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/human_review_scope_test.py
@@ -0,0 +1,276 @@
+"""A review belongs to a graph execution or to a chat, never to both.
+
+Chat reviews used to be stored under a synthetic ``copilot-session-<id>``
+graph execution; these tests pin the chat shape, the graph shape, and the
+reading of rows (and callers) still in the old shape.
+"""
+
+from uuid import uuid4
+
+import pytest
+from prisma.enums import ReviewStatus
+from prisma.errors import PrismaError, UniqueViolationError
+from prisma.models import PendingHumanReview, User
+from pydantic import BaseModel
+
+from backend.data.human_review import (
+ check_approval,
+ create_auto_approval_record,
+ get_or_create_human_review,
+ get_pending_reviews_for_chat_session,
+ get_pending_reviews_for_execution,
+)
+from backend.util.json import SafeJson
+from backend.util.test import SpinTestServer
+
+pytestmark = pytest.mark.asyncio(loop_scope="session")
+
+
+async def user_id(server: SpinTestServer):
+ user_id = f"review-scope-{uuid4()}"
+ try:
+ await User.prisma().create(
+ data={"id": user_id, "email": f"{user_id}@example.com", "name": "Scope"}
+ )
+ except UniqueViolationError:
+ pass
+ yield user_id
+ await PendingHumanReview.prisma().delete_many(where={"userId": user_id})
+ await User.prisma().delete_many(where={"id": user_id})
+
+
+async def test_chat_review_has_no_graph_fields_and_is_found_by_its_chat(user_id):
+ session_id = f"chat-{uuid4()}"
+
+ await get_or_create_human_review(
+ user_id=user_id,
+ node_exec_id=f"copilot-node-blk:{uuid4().hex[:8]}",
+ chat_session_id=session_id,
+ input_data={"path": "/reports"},
+ message="Create Folder",
+ editable=True,
+ )
+
+ [review] = await get_pending_reviews_for_chat_session(session_id, user_id)
+ assert review.session_id == session_id
+ assert (review.graph_exec_id, review.graph_id, review.graph_version) == (
+ None,
+ None,
+ None,
+ )
+ assert review.node_id == "copilot-node-blk"
+ row = await PendingHumanReview.prisma().find_unique(
+ where={"nodeExecId": review.node_exec_id}
+ )
+ assert row and row.chatSessionId == session_id
+ assert row.graphExecId == f"copilot-session-{session_id}"
+
+
+async def test_graph_review_keeps_its_graph_execution(user_id):
+ graph_exec_id = str(uuid4())
+
+ await get_or_create_human_review(
+ user_id=user_id,
+ node_exec_id=str(uuid4()),
+ graph_exec_id=graph_exec_id,
+ graph_id="graph-1",
+ graph_version=3,
+ input_data={"a": 1},
+ message="Send",
+ editable=False,
+ )
+
+ [review] = await get_pending_reviews_for_execution(graph_exec_id, user_id)
+ assert (review.graph_exec_id, review.graph_id, review.graph_version) == (
+ graph_exec_id,
+ "graph-1",
+ 3,
+ )
+ assert review.session_id is None
+
+
+async def test_a_caller_passing_the_old_synthetic_id_writes_a_chat_review(user_id):
+ session_id = f"chat-{uuid4()}"
+
+ await get_or_create_human_review(
+ user_id=user_id,
+ node_exec_id=f"copilot-node-gate-bash_exec:{uuid4().hex[:8]}",
+ graph_exec_id=f"copilot-session-{session_id}",
+ graph_id=f"copilot-session-{session_id}",
+ graph_version=1,
+ input_data={},
+ message="Run a command",
+ editable=False,
+ )
+
+ [review] = await get_pending_reviews_for_chat_session(session_id, user_id)
+ assert review.graph_exec_id is None
+ row = await PendingHumanReview.prisma().find_unique(
+ where={"nodeExecId": review.node_exec_id}
+ )
+ assert row and row.chatSessionId == session_id
+ assert row.graphId == f"copilot-session-{session_id}"
+ # ...and the same caller finds it again by the id it passed.
+ old_id = f"copilot-session-{session_id}"
+ found = await get_pending_reviews_for_execution(old_id, user_id)
+ assert [r.node_exec_id for r in found] == [review.node_exec_id]
+
+
+async def test_a_row_in_the_old_shape_still_resolves_to_its_chat(user_id):
+ session_id = f"chat-{uuid4()}"
+ old_id = f"copilot-session-{session_id}"
+ await PendingHumanReview.prisma().create(
+ data={
+ "nodeExecId": f"copilot-node-blk:{uuid4().hex[:8]}",
+ "userId": user_id,
+ "graphExecId": old_id,
+ "graphId": old_id,
+ "graphVersion": 1,
+ "payload": SafeJson({}),
+ "status": ReviewStatus.WAITING,
+ }
+ )
+
+ [review] = await get_pending_reviews_for_chat_session(session_id, user_id)
+ assert review.session_id == session_id
+ assert review.graph_exec_id is None and review.graph_id is None
+ assert [
+ r.node_exec_id for r in await get_pending_reviews_for_execution(old_id, user_id)
+ ] == [review.node_exec_id]
+
+
+async def test_auto_approval_holds_for_its_chat_only(user_id):
+ session_id = f"chat-{uuid4()}"
+ node_id = "copilot-node-blk"
+
+ await create_auto_approval_record(
+ user_id=user_id, node_id=node_id, payload={}, chat_session_id=session_id
+ )
+
+ approved = await check_approval(
+ node_exec_id=f"{node_id}:new",
+ node_id=node_id,
+ user_id=user_id,
+ chat_session_id=session_id,
+ )
+ other_chat = await check_approval(
+ node_exec_id=f"{node_id}:new",
+ node_id=node_id,
+ user_id=user_id,
+ chat_session_id=f"chat-{uuid4()}",
+ )
+ assert approved is not None and approved.status == ReviewStatus.APPROVED
+ assert other_chat is None
+
+
+async def test_a_backfilled_row_reads_as_its_chat(user_id):
+ # The migration keeps the legacy graph columns beside the new chatSessionId.
+ session_id = f"chat-{uuid4()}"
+ old_id = f"copilot-session-{session_id}"
+ await PendingHumanReview.prisma().create(
+ data={
+ "nodeExecId": f"copilot-node-blk:{uuid4().hex[:8]}",
+ "userId": user_id,
+ "graphExecId": old_id,
+ "graphId": old_id,
+ "graphVersion": 1,
+ "chatSessionId": session_id,
+ "payload": SafeJson({}),
+ "status": ReviewStatus.WAITING,
+ }
+ )
+
+ [review] = await get_pending_reviews_for_chat_session(session_id, user_id)
+ assert review.session_id == session_id
+ assert (review.graph_exec_id, review.graph_id, review.graph_version) == (
+ None,
+ None,
+ None,
+ )
+
+
+async def test_an_auto_approval_made_before_the_migration_still_holds(user_id):
+ session_id = f"chat-{uuid4()}"
+ node_id = "copilot-node-blk"
+ old_id = f"copilot-session-{session_id}"
+ await PendingHumanReview.prisma().create(
+ data={
+ "nodeExecId": f"auto_approve_{old_id}_{node_id}",
+ "userId": user_id,
+ "graphExecId": old_id,
+ "graphId": old_id,
+ "graphVersion": 1,
+ "chatSessionId": session_id,
+ "payload": SafeJson({}),
+ "status": ReviewStatus.APPROVED,
+ "processed": True,
+ }
+ )
+
+ approved = await check_approval(
+ node_exec_id=f"{node_id}:new",
+ node_id=node_id,
+ user_id=user_id,
+ chat_session_id=session_id,
+ )
+ assert approved is not None and approved.status == ReviewStatus.APPROVED
+
+
+class _PreviousDeployReview(BaseModel):
+ """The graph fields as the review model before this change required them."""
+
+ node_exec_id: str
+ graph_exec_id: str
+ graph_id: str
+ graph_version: int
+
+
+async def test_a_new_chat_review_loads_on_the_previous_deploy_too(user_id):
+ session_id = f"chat-{uuid4()}"
+ await get_or_create_human_review(
+ user_id=user_id,
+ node_exec_id=f"copilot-node-blk:{uuid4().hex[:8]}",
+ chat_session_id=session_id,
+ input_data={},
+ message="Create Folder",
+ editable=True,
+ )
+ [review] = await get_pending_reviews_for_chat_session(session_id, user_id)
+ row = await PendingHumanReview.prisma().find_unique(
+ where={"nodeExecId": review.node_exec_id}
+ )
+ assert row
+
+ _PreviousDeployReview(
+ node_exec_id=row.nodeExecId,
+ graph_exec_id=row.graphExecId,
+ graph_id=row.graphId,
+ graph_version=row.graphVersion,
+ )
+ assert review.session_id == session_id and review.graph_exec_id is None
+
+
+ "scope",
+ [
+ {},
+ {
+ "graphExecId": "ge-1",
+ "graphId": "g-1",
+ "graphVersion": 1,
+ "chatSessionId": "s",
+ },
+ ],
+ ids=["neither", "both"],
+)
+async def test_the_database_refuses_a_review_without_exactly_one_scope(user_id, scope):
+ with pytest.raises(PrismaError, match="graph_or_chat_session_check"):
+ await PendingHumanReview.prisma().create(
+ data={
+ "nodeExecId": f"bad-{uuid4()}",
+ "userId": user_id,
+ "payload": SafeJson({}),
+ **scope,
+ }
+ )
diff --git a/autogpt_platform/backend/backend/data/human_review_test.py b/autogpt_platform/backend/backend/data/human_review_test.py
index 60f97bce3b..bcc0b74cdc 100644
--- a/autogpt_platform/backend/backend/data/human_review_test.py
+++ b/autogpt_platform/backend/backend/data/human_review_test.py
@@ -21,6 +21,7 @@ def sample_db_review():
mock_review.nodeExecId = "test_node_123"
mock_review.userId = "test-user-123"
mock_review.graphExecId = "test_graph_exec_456"
+ mock_review.chatSessionId = None
mock_review.graphId = "test_graph_789"
mock_review.graphVersion = 1
mock_review.payload = {"data": "test payload"}
@@ -209,6 +210,7 @@ async def test_process_all_reviews_for_execution_success(
updated_review.nodeExecId = "test_node_123"
updated_review.userId = "test-user-123"
updated_review.graphExecId = "test_graph_exec_456"
+ updated_review.chatSessionId = None
updated_review.graphId = "test_graph_789"
updated_review.graphVersion = 1
updated_review.payload = {"data": "modified"}
@@ -307,6 +309,7 @@ async def test_process_all_reviews_mixed_approval_rejection(
second_review.nodeExecId = "test_node_456"
second_review.userId = "test-user-123"
second_review.graphExecId = "test_graph_exec_456"
+ second_review.chatSessionId = None
second_review.graphId = "test_graph_789"
second_review.graphVersion = 1
second_review.payload = {"data": "original"}
@@ -331,6 +334,7 @@ async def test_process_all_reviews_mixed_approval_rejection(
approved_review.nodeExecId = "test_node_123"
approved_review.userId = "test-user-123"
approved_review.graphExecId = "test_graph_exec_456"
+ approved_review.chatSessionId = None
approved_review.graphId = "test_graph_789"
approved_review.graphVersion = 1
approved_review.payload = {"data": "modified"}
@@ -348,6 +352,7 @@ async def test_process_all_reviews_mixed_approval_rejection(
rejected_review.nodeExecId = "test_node_456"
rejected_review.userId = "test-user-123"
rejected_review.graphExecId = "test_graph_exec_456"
+ rejected_review.chatSessionId = None
rejected_review.graphId = "test_graph_789"
rejected_review.graphVersion = 1
rejected_review.payload = {"data": "original"}
@@ -387,3 +392,55 @@ async def test_process_all_reviews_mixed_approval_rejection(
assert "test_node_456" in result
assert result["test_node_123"].node_id == "test_node_def_789"
assert result["test_node_456"].node_id == "test_node_def_789"
+
+
[email protected](loop_scope="function")
+async def test_a_chat_with_legacy_and_new_rows_syncs_one_alert(
+ mocker: pytest_mock.MockFixture,
+):
+ def row(node_exec_id, graph_exec_id, graph_id, session_id):
+ r = Mock()
+ r.nodeExecId = node_exec_id
+ r.userId = "u1"
+ r.graphExecId = graph_exec_id
+ r.graphId = graph_id
+ r.graphVersion = 1 if graph_id else None
+ r.chatSessionId = session_id
+ r.payload = {}
+ r.instructions = "Review"
+ r.editable = True
+ r.status = ReviewStatus.WAITING
+ r.reviewMessage = None
+ r.wasEdited = False
+ r.processed = False
+ r.createdAt = r.updatedAt = r.reviewedAt = datetime.datetime.now(
+ datetime.timezone.utc
+ )
+ return r
+
+ rows = [
+ row("copilot-node-a:1", "copilot-session-s1", "copilot-session-s1", None),
+ row("copilot-node-b:2", None, None, "s1"),
+ row("copilot-node-c:3", "copilot-session-s1", "copilot-session-s1", "s1"),
+ row("node-exec-g", "ge-1", "g1", None),
+ ]
+ mock_prisma = mocker.patch("backend.data.human_review.PendingHumanReview.prisma")
+ mock_prisma.return_value.find_many = AsyncMock(return_value=rows)
+ mock_prisma.return_value.update = AsyncMock()
+ mocker.patch(
+ "backend.data.human_review.asyncio.gather", new=AsyncMock(return_value=[])
+ )
+ sync = mocker.patch(
+ "backend.data.human_review._sync_awaiting_review_safely", new=AsyncMock()
+ )
+
+ await process_all_reviews_for_execution(
+ user_id="u1",
+ review_decisions={
+ r.nodeExecId: (ReviewStatus.APPROVED, None, None) for r in rows
+ },
+ )
+
+ calls = [c.args for c in sync.await_args_list]
+ assert len(calls) == 2
+ assert set(calls) == {("u1", None, "s1"), ("u1", "g1", None)}
diff --git a/autogpt_platform/backend/backend/notifications/review_alerts.py b/autogpt_platform/backend/backend/notifications/review_alerts.py
index 62558c9a42..c3f2829025 100644
--- a/autogpt_platform/backend/backend/notifications/review_alerts.py
+++ b/autogpt_platform/backend/backend/notifications/review_alerts.py
@@ -9,10 +9,13 @@ behind.
"""
import logging
+from urllib.parse import quote
from prisma.enums import AlertCause, ReviewStatus
from prisma.models import PendingHumanReview
+from prisma.types import PendingHumanReviewWhereInput
+from backend.copilot.constants import AUTOPILOT_NAME, COPILOT_SESSION_PREFIX
from backend.data import alerts as alerts_db
from backend.data.graph import get_graph_metadata
from backend.notifications.alert_causes import AwaitingReviewCause
@@ -21,31 +24,54 @@ from backend.util.logging import TruncatedLogger
logger = TruncatedLogger(logging.getLogger(__name__), prefix="[ReviewAlerts]")
-async def sync_awaiting_review(user_id: str, graph_id: str) -> None:
- """Raise, update or clear the review-queue alert for one agent.
+async def sync_awaiting_review(
+ user_id: str, graph_id: str | None = None, *, chat_session_id: str | None = None
+) -> None:
+ """Raise, update or clear the review-queue alert for one agent or one chat.
Never raises: a notification must not fail the review flow that triggered
it.
"""
+ scope = f"chat {chat_session_id}" if chat_session_id else f"agent {graph_id}"
try:
+ if chat_session_id:
+ where: PendingHumanReviewWhereInput = {
+ "OR": [
+ {"chatSessionId": chat_session_id},
+ # Rows an older deploy wrote in the synthetic-graph shape.
+ {"graphExecId": f"{COPILOT_SESSION_PREFIX}{chat_session_id}"},
+ ]
+ }
+ cause_key = f"awaiting_review:chat:{chat_session_id}"
+ # The alert an older deploy raised for this chat, keyed as an agent.
+ await alerts_db.resolve_alert_condition(
+ user_id, f"awaiting_review:{COPILOT_SESSION_PREFIX}{chat_session_id}"
+ )
+ elif graph_id:
+ where = {"graphId": graph_id}
+ cause_key = f"awaiting_review:{graph_id}"
+ else:
+ return
waiting = await PendingHumanReview.prisma().find_many(
- where={
- "userId": user_id,
- "graphId": graph_id,
- "status": ReviewStatus.WAITING,
- },
+ where={**where, "userId": user_id, "status": ReviewStatus.WAITING},
order={"createdAt": "asc"},
)
- cause_key = f"awaiting_review:{graph_id}"
if not waiting:
await alerts_db.resolve_alert_condition(user_id, cause_key)
return
oldest = waiting[0].createdAt
- metadata = await get_graph_metadata(graph_id=graph_id)
+ if chat_session_id:
+ agent = AUTOPILOT_NAME
+ cta_path = f"/copilot?sessionId={quote(chat_session_id)}"
+ else:
+ assert graph_id
+ metadata = await get_graph_metadata(graph_id=graph_id)
+ agent = metadata.name if metadata else f"Agent {graph_id[:8]}"
+ cta_path = f"/library/agents/{graph_id}/reviews"
cause = AwaitingReviewCause(
- cta_path=f"/library/agents/{graph_id}/reviews",
- agent=metadata.name if metadata else f"Agent {graph_id[:8]}",
+ cta_path=cta_path,
+ agent=agent,
count=len(waiting),
since_label=f"{oldest.day} {oldest.strftime('%b')}, {oldest.strftime('%H:%M')}",
)
@@ -57,7 +83,6 @@ async def sync_awaiting_review(user_id: str, graph_id: str) -> None:
)
except Exception:
logger.warning(
- f"Could not sync the awaiting-review alert for user {user_id} agent "
- f"{graph_id}",
+ f"Could not sync the awaiting-review alert for user {user_id} {scope}",
exc_info=True,
)
diff --git a/autogpt_platform/backend/backend/notifications/review_alerts_test.py b/autogpt_platform/backend/backend/notifications/review_alerts_test.py
new file mode 100644
index 0000000000..cb81b2df30
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/review_alerts_test.py
@@ -0,0 +1,51 @@
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from backend.notifications import review_alerts
+
+
+def alerts(mocker):
+ db = MagicMock(
+ resolve_alert_condition=AsyncMock(), raise_alert_condition=AsyncMock()
+ )
+ mocker.patch.object(review_alerts, "alerts_db", db)
+ return db
+
+
+def _waiting(mocker, rows):
+ find_many = AsyncMock(return_value=rows)
+ mocker.patch.object(
+ review_alerts.PendingHumanReview,
+ "prisma",
+ return_value=MagicMock(find_many=find_many),
+ )
+ return find_many
+
+
+async def test_a_chat_alert_counts_old_shape_rows_and_clears_the_old_key(
+ mocker, alerts
+):
+ find_many = _waiting(mocker, [])
+
+ await review_alerts.sync_awaiting_review("u1", chat_session_id="s1")
+
+ where = find_many.await_args.kwargs["where"]
+ assert {"chatSessionId": "s1"} in where["OR"]
+ assert {"graphExecId": "copilot-session-s1"} in where["OR"]
+ resolved = [c.args[1] for c in alerts.resolve_alert_condition.await_args_list]
+ assert resolved == ["awaiting_review:copilot-session-s1", "awaiting_review:chat:s1"]
+
+
+async def test_a_waiting_chat_review_raises_a_chat_alert(mocker, alerts):
+ _waiting(mocker, [MagicMock(createdAt=datetime(2026, 9, 24, tzinfo=timezone.utc))])
+
+ await review_alerts.sync_awaiting_review("u1", chat_session_id="s1")
+
+ kwargs = alerts.raise_alert_condition.await_args.kwargs
+ assert kwargs["cause_key"] == "awaiting_review:chat:s1"
+ assert kwargs["data"]["cta_path"] == "/copilot?sessionId=s1"
diff --git a/autogpt_platform/backend/migrations/20260924000000_pending_human_review_session_scope/migration.sql b/autogpt_platform/backend/migrations/20260924000000_pending_human_review_session_scope/migration.sql
new file mode 100644
index 0000000000..21650932f7
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260924000000_pending_human_review_session_scope/migration.sql
@@ -0,0 +1,27 @@
+-- Chat reviews were stored under a synthetic graph execution
+-- ("copilot-session-<session id>"); they now carry the chat's session id.
+-- Additive only: this runs before the new pods roll out, and the old model
+-- reads graphExecId/graphId/graphVersion as non-null, so existing rows keep
+-- their legacy values alongside the new chatSessionId.
+ALTER TABLE "PendingHumanReview"
+ ALTER COLUMN "graphExecId" DROP NOT NULL,
+ ALTER COLUMN "graphId" DROP NOT NULL,
+ ALTER COLUMN "graphVersion" DROP NOT NULL,
+ ADD COLUMN "chatSessionId" TEXT;
+
+UPDATE "PendingHumanReview"
+SET "chatSessionId" = substr("graphExecId", length('copilot-session-') + 1)
+WHERE "graphExecId" LIKE 'copilot-session-%';
+
+-- A review is a graph execution's or a chat's; a legacy chat row keeps its
+-- synthetic graph id beside the session until a cleanup migration clears it.
+-- NOT VALID keeps the existing-row scan out of this migration's lock; the
+-- next migration validates it.
+ALTER TABLE "PendingHumanReview"
+ ADD CONSTRAINT "PendingHumanReview_graph_or_chat_session_check"
+ CHECK (
+ ("graphExecId" IS NULL) <> ("chatSessionId" IS NULL)
+ OR COALESCE("graphExecId" LIKE 'copilot-session-%', false)
+ ) NOT VALID;
+
+CREATE INDEX "PendingHumanReview_chatSessionId_status_idx" ON "PendingHumanReview"("chatSessionId", "status");
diff --git a/autogpt_platform/backend/migrations/20260924000001_validate_pending_human_review_session_scope/migration.sql b/autogpt_platform/backend/migrations/20260924000001_validate_pending_human_review_session_scope/migration.sql
new file mode 100644
index 0000000000..5ac4b3be9d
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260924000001_validate_pending_human_review_session_scope/migration.sql
@@ -0,0 +1,4 @@
+-- Validate the check added NOT VALID in 20260924000000_pending_human_review_session_scope.
+-- Its own transaction, so the scan holds only a SHARE UPDATE EXCLUSIVE lock
+-- and review reads and writes proceed.
+ALTER TABLE "PendingHumanReview" VALIDATE CONSTRAINT "PendingHumanReview_graph_or_chat_session_check";
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 202c72e466..1222180a0a 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -1668,9 +1668,12 @@ enum ReviewStatus {
model PendingHumanReview {
nodeExecId String @id
userId String
- graphExecId String
- graphId String
- graphVersion Int
+ // A review belongs to a graph execution (the three graph columns) or to a
+ // chat (chatSessionId); a check constraint enforces exactly one.
+ graphExecId String?
+ graphId String?
+ graphVersion Int?
+ chatSessionId String?
payload Json // The actual payload data to be reviewed
instructions String? // Instructions/message for the reviewer
editable Boolean @default(true) // Whether the reviewer can edit the data
@@ -1691,6 +1694,7 @@ model PendingHumanReview {
@@unique([nodeExecId]) // One pending review per node execution
@@index([userId, status])
@@index([graphExecId, status])
+ @@index([chatSessionId, status])
@@index([organizationId])
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
index 8514523a0a..fb890ad41d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
@@ -148,16 +148,17 @@ interface Props {
showThreadHeader?: boolean;
}
+type ReviewTarget = { kind: "chat" } | { kind: "graph"; graphExecId: string };
+
/**
- * Extract graph_exec_id from tool outputs that need review.
- * Handles both:
- * - run_block ReviewRequiredResponse (has graph_exec_id directly)
- * - run_agent ExecutionStartedResponse with status "REVIEW" (has execution_id)
+ * Which review queue the latest tool output that needs review belongs to:
+ * the chat's own (a `review_required` output) or an agent run's (run_agent
+ * with status "REVIEW").
*/
-function extractGraphExecId(
+function extractReviewTarget(
messages: UIMessage<unknown, UIDataTypes, UITools>[],
-): string | null {
- // Scan backwards — the most recent review output has the ID
+): ReviewTarget | null {
+ // Scan backwards — the most recent review output decides
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
for (const part of msg.parts) {
@@ -173,17 +174,18 @@ function extractGraphExecId(
})()
: part.output;
if (out && typeof out === "object") {
- // run_block: ReviewRequiredResponse has graph_exec_id
- if ("graph_exec_id" in out) {
- return (out as { graph_exec_id: string }).graph_exec_id;
+ if ((out as { type?: unknown }).type === "review_required") {
+ return { kind: "chat" };
}
- // run_agent: ExecutionStartedResponse with status "REVIEW"
if (
"execution_id" in out &&
"status" in out &&
(out as { status: string }).status === "REVIEW"
) {
- return (out as { execution_id: string }).execution_id;
+ return {
+ kind: "graph",
+ graphExecId: (out as { execution_id: string }).execution_id,
+ };
}
}
}
@@ -387,7 +389,7 @@ export function ChatMessagesContainer({
const lastUserMessageID = showPendingSend
? PENDING_UPLOAD_MESSAGE_ID
: (renderRows.findLast((row) => row.role === "user")?.id ?? null);
- const graphExecId = useMemo(() => extractGraphExecId(messages), [messages]);
+ const reviewTarget = useMemo(() => extractReviewTarget(messages), [messages]);
// The backend appends a persisted error marker to ``session.messages`` AND
// yields a ``StreamError`` SSE event on final-failure paths. Both surface
@@ -863,8 +865,11 @@ export function ChatMessagesContainer({
</MessageContent>
</Message>
)}
- {!readOnly && graphExecId && (
- <CopilotPendingReviews graphExecId={graphExecId} />
+ {!readOnly && reviewTarget?.kind === "graph" && (
+ <CopilotPendingReviews graphExecId={reviewTarget.graphExecId} />
+ )}
+ {!readOnly && reviewTarget?.kind === "chat" && sessionID && (
+ <CopilotPendingReviews chatSessionId={sessionID} />
)}
{!readOnly &&
queuedMessages?.map((msg, idx) => (
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
index 8059f4df36..eaf6e1a5bf 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
@@ -131,7 +131,9 @@ vi.mock("../../JobStatsBar/useElapsedTimer", () => ({
useElapsedTimer: () => ({ elapsedSeconds: 0 }),
}));
vi.mock("../../CopilotPendingReviews/CopilotPendingReviews", () => ({
- CopilotPendingReviews: () => null,
+ CopilotPendingReviews: (props: object) => (
+ <span data-testid="pending-reviews" data-props={JSON.stringify(props)} />
+ ),
}));
// Tests below override this default by re-mocking ../helpers as needed.
vi.mock("../helpers", () => ({
@@ -1447,3 +1449,87 @@ describe("ChatMessagesContainer — mid-turn follow-up", () => {
expect(renderedRowIds()).toEqual(["user-1", "assistant-1"]);
});
});
+
+describe("ChatMessagesContainer — pending reviews", () => {
+ function withToolOutput(output: object): Message[] {
+ return [
+ {
+ id: "assistant-review",
+ role: "assistant",
+ parts: [
+ {
+ type: "tool-run_capability",
+ toolCallId: "call-1",
+ state: "output-available",
+ input: {},
+ output: JSON.stringify(output),
+ },
+ ],
+ } as Message,
+ ];
+ }
+
+ function mountedProps() {
+ const el = screen.queryByTestId("pending-reviews");
+ return el ? JSON.parse(el.getAttribute("data-props") ?? "{}") : null;
+ }
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("finds a chat review by the chat's session, with no graph execution", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ messages={withToolOutput({
+ type: "review_required",
+ review_id: "copilot-node-blk:ab12",
+ block_id: "blk",
+ block_name: "Create Folder",
+ input_data: {},
+ })}
+ />,
+ );
+
+ expect(mountedProps()).toEqual({ chatSessionId: "sess-123" });
+ });
+
+ it("finds a chat review stored before it had a session id of its own", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ messages={withToolOutput({
+ type: "review_required",
+ review_id: "copilot-node-blk:ab12",
+ graph_exec_id: "copilot-session-sess-123",
+ })}
+ />,
+ );
+
+ expect(mountedProps()).toEqual({ chatSessionId: "sess-123" });
+ });
+
+ it("finds an agent run's reviews by its graph execution", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ messages={withToolOutput({ execution_id: "exec-9", status: "REVIEW" })}
+ />,
+ );
+
+ expect(mountedProps()).toEqual({ graphExecId: "exec-9" });
+ });
+
+ it("mounts nothing in a read-only transcript", () => {
+ render(
+ <ChatMessagesContainer
+ {...baseProps}
+ readOnly
+ messages={withToolOutput({ type: "review_required", review_id: "r" })}
+ />,
+ );
+
+ expect(mountedProps()).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
index 132bee7ccf..5525b1a1b2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx
@@ -3,27 +3,34 @@
import { useCallback } from "react";
import { PendingReviewsList } from "@/components/organisms/PendingReviewsList/PendingReviewsList";
import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";
-import { usePendingReviewsForExecution } from "@/hooks/usePendingReviews";
+import {
+ usePendingReviewsForExecution,
+ usePendingReviewsForChatSession,
+} from "@/hooks/usePendingReviews";
import { okData } from "@/app/api/helpers";
-interface Props {
- graphExecId: string;
-}
+type Props = { graphExecId: string } | { chatSessionId: string };
+
+const POLL = { refetchInterval: 2000 };
/**
- * Renders a single consolidated PendingReviewsList for all pending copilot
- * reviews in a session — mirrors the non-copilot review page behavior.
- * Works for both run_capability (synthetic copilot-session-*) and run_agent (real graph exec) reviews.
+ * Renders a single consolidated PendingReviewsList for the chat's own reviews
+ * (run_capability, MCP, spend approval) or for an agent run the chat started
+ * — mirrors the non-copilot review page behavior.
*/
-export function CopilotPendingReviews({ graphExecId }: Props) {
+export function CopilotPendingReviews(props: Props) {
const { onSend } = useCopilotChatActions();
- const { pendingReviews, refetch } = usePendingReviewsForExecution(
- graphExecId,
- { enabled: !!graphExecId, refetchInterval: 2000 },
- );
-
- // Graph executions auto-resume after approval; capability reviews need resume_capability.
- const isGraphExecution = !graphExecId.startsWith("copilot-session-");
+ const graphExecId = "graphExecId" in props ? props.graphExecId : "";
+ const chatSessionId = "chatSessionId" in props ? props.chatSessionId : "";
+ const forRun = usePendingReviewsForExecution(graphExecId, {
+ ...POLL,
+ enabled: !!graphExecId,
+ });
+ const forChat = usePendingReviewsForChatSession(chatSessionId, {
+ ...POLL,
+ enabled: !!chatSessionId,
+ });
+ const { pendingReviews, refetch } = graphExecId ? forRun : forChat;
const handleReviewComplete = useCallback(async () => {
// Brief delay for the server to propagate the approval
@@ -33,7 +40,8 @@ export function CopilotPendingReviews({ graphExecId }: Props) {
if (remaining.length > 0) return;
- if (isGraphExecution) {
+ // Graph executions auto-resume after approval; chat reviews need resume_capability.
+ if (graphExecId) {
onSend(
`All pending reviews have been processed. ` +
`The agent execution will resume automatically for approved reviews. ` +
@@ -46,7 +54,7 @@ export function CopilotPendingReviews({ graphExecId }: Props) {
`For rejected reviews, no further action is needed.`,
);
}
- }, [refetch, onSend, isGraphExecution, graphExecId]);
+ }, [refetch, onSend, graphExecId]);
if (pendingReviews.length === 0) return null;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx
new file mode 100644
index 0000000000..a3a65e1ff7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx
@@ -0,0 +1,94 @@
+import userEvent from "@testing-library/user-event";
+import { afterEach, expect, test, vi } from "vitest";
+import {
+ getGetV2GetPendingReviewsForChatSessionMockHandler,
+ getGetV2GetPendingReviewsForExecutionMockHandler,
+ getPostV2ProcessReviewActionMockHandler200,
+} from "@/app/api/__generated__/endpoints/executions/executions.msw";
+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";
+import { server } from "@/mocks/mock-server";
+import {
+ cleanup,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { CopilotPendingReviews } from "../CopilotPendingReviews";
+
+const onSend = vi.fn();
+vi.mock("../../CopilotChatActionsProvider/useCopilotChatActions", () => ({
+ useCopilotChatActions: () => ({ onSend }),
+}));
+
+afterEach(() => {
+ cleanup();
+ onSend.mockReset();
+});
+
+function makeReview(
+ overrides: Partial<PendingHumanReviewModel> = {},
+): PendingHumanReviewModel {
+ return {
+ node_exec_id: "copilot-node-blk:ab12",
+ node_id: "copilot-node-blk",
+ user_id: "u-1",
+ session_id: "chat-1",
+ graph_exec_id: null,
+ graph_id: null,
+ graph_version: null,
+ payload: { path: "/reports" },
+ instructions: "Create Folder",
+ editable: true,
+ status: "WAITING",
+ created_at: new Date(),
+ ...overrides,
+ };
+}
+
+test("a chat's queue is read from the chat, and the resume is AutoPilot's", async () => {
+ let waiting = [makeReview()];
+ server.use(
+ getGetV2GetPendingReviewsForChatSessionMockHandler(() => waiting),
+ getGetV2GetPendingReviewsForExecutionMockHandler([
+ makeReview({ instructions: "Not this chat's review" }),
+ ]),
+ getPostV2ProcessReviewActionMockHandler200(() => {
+ waiting = [];
+ return { approved_count: 1, rejected_count: 0, failed_count: 0 };
+ }),
+ );
+
+ render(<CopilotPendingReviews chatSessionId="chat-1" />);
+
+ expect(await screen.findByText("Create Folder")).toBeDefined();
+ expect(screen.queryByText("Not this chat's review")).toBeNull();
+
+ await userEvent.click(screen.getAllByRole("button", { name: /^Approve/ })[0]);
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1), {
+ timeout: 3000,
+ });
+ expect(onSend.mock.calls[0][0]).toContain("resume_capability");
+});
+
+test("an agent run's queue is read from its execution", async () => {
+ server.use(
+ getGetV2GetPendingReviewsForExecutionMockHandler([
+ makeReview({
+ session_id: null,
+ graph_exec_id: "exec-9",
+ graph_id: "g-1",
+ graph_version: 1,
+ instructions: "Send Email",
+ }),
+ ]),
+ getGetV2GetPendingReviewsForChatSessionMockHandler([
+ makeReview({ instructions: "Not the run's review" }),
+ ]),
+ );
+
+ render(<CopilotPendingReviews graphExecId="exec-9" />);
+
+ expect(await screen.findByText("Send Email")).toBeDefined();
+ expect(screen.queryByText("Not the run's review")).toBeNull();
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx
index cfd3723964..5fbf287e62 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx
@@ -37,7 +37,6 @@ export interface ReviewRequiredResponse {
block_id: string;
block_name: string;
review_id: string;
- graph_exec_id: string;
input_data: Record<string, unknown>;
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/useAttentionDecisions.ts b/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/useAttentionDecisions.ts
index 1c5b361f05..444402e980 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/useAttentionDecisions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/NeedsYou/useAttentionDecisions.ts
@@ -33,7 +33,7 @@ export function useAttentionDecisions() {
auto_approve_future: false,
},
],
- [item.review.graph_exec_id],
+ [item.review],
);
if (response.status !== 200 || response.data.failed_count > 0) {
const message = response.status === 200 ? response.data.error : null;
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 438027682f..7b8ce81a94 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -13821,6 +13821,54 @@
}
}
},
+ "/api/review/session/{chat_session_id}": {
+ "get": {
+ "tags": ["v2", "executions", "review", "v2", "executions", "review"],
+ "summary": "Get Pending Reviews for Chat Session",
+ "description": "Get the reviews an AutoPilot chat is waiting on, oldest first.\n\nOnly the caller's own reviews are returned, so another user's chat session\nid yields an empty list.",
+ "operationId": "getV2Get pending reviews for chat session",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "chat_session_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Chat Session Id" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of pending reviews for the chat session",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PendingHumanReviewModel"
+ },
+ "title": "Response Getv2Get Pending Reviews For Chat Session"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": {
+ "description": "Server error",
+ "content": { "application/json": {} }
+ }
+ }
+ }
+ },
"/api/schedules": {
"get": {
"tags": ["v1", "schedules"],
@@ -18640,7 +18688,10 @@
"BriefingDecisionItem": {
"properties": {
"node_exec_id": { "type": "string", "title": "Node Exec Id" },
- "graph_exec_id": { "type": "string", "title": "Graph Exec Id" },
+ "graph_exec_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Exec Id"
+ },
"title": { "type": "string", "title": "Title" },
"expert_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
@@ -26549,20 +26600,25 @@
"description": "User ID associated with the review"
},
"graph_exec_id": {
- "type": "string",
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Graph Exec Id",
- "description": "Graph execution ID"
+ "description": "Graph execution ID; None for a chat review"
},
"graph_id": {
- "type": "string",
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Graph Id",
"description": "Graph ID"
},
"graph_version": {
- "type": "integer",
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
"title": "Graph Version",
"description": "Graph version"
},
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id",
+ "description": "Chat session ID; None for a graph review"
+ },
"payload": {
"anyOf": [
{ "additionalProperties": true, "type": "object" },
@@ -26618,11 +26674,6 @@
"title": "Library Agent Id",
"description": "For run deep links"
},
- "session_id": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Session Id",
- "description": "Chat session id for copilot run_capability reviews"
- },
"was_edited": {
"anyOf": [{ "type": "boolean" }, { "type": "null" }],
"title": "Was Edited",
@@ -26661,9 +26712,6 @@
"required": [
"node_exec_id",
"user_id",
- "graph_exec_id",
- "graph_id",
- "graph_version",
"payload",
"editable",
"status",
diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts
index 1a7c2f3778..f6dec4f757 100644
--- a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts
+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts
@@ -43,7 +43,7 @@ export function useNeedsAttentionList() {
auto_approve_future: false,
},
],
- [review.graph_exec_id],
+ [review],
);
// The mutation resolves rather than throws on a non-200, and a 200 can
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
index 0666ff2b01..a512571236 100644
--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
@@ -155,10 +155,7 @@ export function PendingReviewsList({
}
try {
- const res = await submitReviewAction(
- reviewItems,
- groupReviews.map((review) => review.graph_exec_id),
- );
+ const res = await submitReviewAction(reviewItems, groupReviews);
if (res.status !== 200) {
toast({
diff --git a/autogpt_platform/frontend/src/hooks/usePendingReviews.ts b/autogpt_platform/frontend/src/hooks/usePendingReviews.ts
index b9d7d711a1..0143ca20cc 100644
--- a/autogpt_platform/frontend/src/hooks/usePendingReviews.ts
+++ b/autogpt_platform/frontend/src/hooks/usePendingReviews.ts
@@ -1,5 +1,6 @@
import {
useGetV2GetPendingReviews,
+ useGetV2GetPendingReviewsForChatSession,
useGetV2GetPendingReviewsForExecution,
} from "@/app/api/__generated__/endpoints/executions/executions";
import { okData } from "@/app/api/helpers";
@@ -39,3 +40,23 @@ export function usePendingReviewsForExecution(
refetch: query.refetch,
};
}
+
+export function usePendingReviewsForChatSession(
+ chatSessionId: string,
+ options?: UsePendingReviewsForExecutionOptions,
+) {
+ const query = useGetV2GetPendingReviewsForChatSession(chatSessionId, {
+ query: {
+ enabled: options?.enabled ?? !!chatSessionId,
+ refetchInterval: options?.refetchInterval,
+ refetchIntervalInBackground: !!options?.refetchInterval,
+ },
+ });
+
+ return {
+ pendingReviews: okData(query.data) || [],
+ isLoading: query.isLoading,
+ error: query.error,
+ refetch: query.refetch,
+ };
+}
diff --git a/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx b/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx
index ff9c5f137b..6816101e90 100644
--- a/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx
+++ b/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx
@@ -4,6 +4,7 @@ import { HttpResponse, http } from "msw";
import type { ReactNode } from "react";
import { expect, test, vi } from "vitest";
import {
+ getGetV2GetPendingReviewsForChatSessionQueryKey,
getGetV2GetPendingReviewsForExecutionQueryKey,
getGetV2GetPendingReviewsQueryKey,
} from "@/app/api/__generated__/endpoints/executions/executions";
@@ -49,7 +50,8 @@ test("invalidates both the user-wide and the per-execution review queries", asyn
);
const { result, invalidatedKeys } = setup();
- await result.current.processReviews([item], ["run-1", "run-1"]);
+ const run = { graph_exec_id: "run-1" };
+ await result.current.processReviews([item], [run, run]);
const keys = invalidatedKeys();
expect(keys).toContainEqual(getGetV2GetPendingReviewsQueryKey());
@@ -61,6 +63,28 @@ test("invalidates both the user-wide and the per-execution review queries", asyn
).toHaveLength(1);
});
+test("a chat review invalidates its session's queue, not an execution's", async () => {
+ server.use(
+ getPostV2ProcessReviewActionMockHandler200({
+ approved_count: 1,
+ rejected_count: 0,
+ failed_count: 0,
+ }),
+ );
+ const { result, invalidatedKeys } = setup();
+
+ await result.current.processReviews(
+ [item],
+ [{ graph_exec_id: null, session_id: "chat-1" }],
+ );
+
+ const keys = invalidatedKeys();
+ expect(keys).toContainEqual(
+ getGetV2GetPendingReviewsForChatSessionQueryKey("chat-1"),
+ );
+ expect(keys).toHaveLength(2);
+});
+
test("still invalidates when the mutation rejects", async () => {
server.use(
http.post("/api/proxy/api/review/action", () => HttpResponse.error()),
@@ -68,7 +92,7 @@ test("still invalidates when the mutation rejects", async () => {
const { result, invalidatedKeys } = setup();
await expect(
- result.current.processReviews([item], ["run-1"]),
+ result.current.processReviews([item], [{ graph_exec_id: "run-1" }]),
).rejects.toBeDefined();
expect(invalidatedKeys()).toContainEqual(getGetV2GetPendingReviewsQueryKey());
diff --git a/autogpt_platform/frontend/src/hooks/useProcessReviews.ts b/autogpt_platform/frontend/src/hooks/useProcessReviews.ts
index b089b53d19..749f1b0340 100644
--- a/autogpt_platform/frontend/src/hooks/useProcessReviews.ts
+++ b/autogpt_platform/frontend/src/hooks/useProcessReviews.ts
@@ -1,18 +1,25 @@
import {
+ getGetV2GetPendingReviewsForChatSessionQueryKey,
getGetV2GetPendingReviewsForExecutionQueryKey,
getGetV2GetPendingReviewsQueryKey,
usePostV2ProcessReviewAction,
} from "@/app/api/__generated__/endpoints/executions/executions";
+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";
import type { ReviewItem } from "@/app/api/__generated__/models/reviewItem";
import { useQueryClient } from "@tanstack/react-query";
+type ReviewScope = Pick<
+ PendingHumanReviewModel,
+ "graph_exec_id" | "session_id"
+>;
+
export function useProcessReviews({
onSettled,
}: { onSettled?: () => void } = {}) {
const queryClient = useQueryClient();
const { mutateAsync, isPending } = usePostV2ProcessReviewAction();
- async function processReviews(items: ReviewItem[], graphExecIds: string[]) {
+ async function processReviews(items: ReviewItem[], scopes: ReviewScope[]) {
try {
return await mutateAsync({ data: { reviews: items } });
} finally {
@@ -23,11 +30,8 @@ export function useProcessReviews({
queryClient.invalidateQueries({
queryKey: getGetV2GetPendingReviewsQueryKey(),
}),
- ...[...new Set(graphExecIds)].map((graphExecId) =>
- queryClient.invalidateQueries({
- queryKey:
- getGetV2GetPendingReviewsForExecutionQueryKey(graphExecId),
- }),
+ ...scopeQueryKeys(scopes).map((queryKey) =>
+ queryClient.invalidateQueries({ queryKey }),
),
]);
onSettled?.();
@@ -36,3 +40,16 @@ export function useProcessReviews({
return { processReviews, isProcessing: isPending };
}
+
+function scopeQueryKeys(scopes: ReviewScope[]) {
+ const keys = new Map<string, readonly unknown[]>();
+ for (const { graph_exec_id, session_id } of scopes) {
+ const key = session_id
+ ? getGetV2GetPendingReviewsForChatSessionQueryKey(session_id)
+ : graph_exec_id
+ ? getGetV2GetPendingReviewsForExecutionQueryKey(graph_exec_id)
+ : null;
+ if (key) keys.set(JSON.stringify(key), key);
+ }
+ return [...keys.values()];
+}
diff --git a/autogpt_platform/frontend/src/lib/review-links.ts b/autogpt_platform/frontend/src/lib/review-links.ts
index f53f4caef8..739d7bfa3e 100644
--- a/autogpt_platform/frontend/src/lib/review-links.ts
+++ b/autogpt_platform/frontend/src/lib/review-links.ts
@@ -7,9 +7,8 @@ import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pen
* home, thread, library) share one definition of these routes instead of
* each embedding path literals.
*
- * Both ids come from the backend's review enrichment: `session_id` is set
- * for every CoPilot `run_block` review, `library_agent_id` for reviews
- * raised by a real graph execution.
+ * `session_id` is set on every chat review; `library_agent_id` comes from
+ * the backend's enrichment of reviews raised by a real graph execution.
*
* The library route selects a run via `activeTab`/`activeItem` — those are
* the params `NewAgentLibraryView` actually parses, so anything else lands
@@ -23,7 +22,7 @@ export function getReviewLink(review: PendingHumanReviewModel): string {
if (review.session_id) {
return `/copilot?sessionId=${encodeURIComponent(review.session_id)}`;
}
- if (review.library_agent_id) {
+ if (review.library_agent_id && review.graph_exec_id) {
return (
`/library/agents/${encodeURIComponent(review.library_agent_id)}` +
`?activeTab=runs&activeItem=${encodeURIComponent(review.graph_exec_id)}`