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): show cost breakdown in agent briefing panel (#13129)

Ubbe1f22a0badf6c
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 869a750ba1..9eaae0f953 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -80,6 +80,10 @@ from backend.data.credit import (
sync_subscription_schedule_from_stripe,
sync_tier_from_checkout_session,
)
+from backend.data.execution_cost_summary import (
+ UserExecutionCostSummary,
+ get_user_cost_summary,
+)
from backend.data.graph import GraphSettings
from backend.data.model import CredentialsMetaInput, UserOnboarding
from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
@@ -1906,6 +1910,43 @@ async def list_graphs_executions(
return filtered_executions
+@v1_router.get(
+ path="/executions/cost-summary",
+ summary="User cost summary",
+ tags=["graphs"],
+ dependencies=[Security(requires_user)],
+)
+async def get_executions_cost_summary(
+ user_id: Annotated[str, Security(get_user_id)],
+ since: datetime | None = Query(
+ None,
+ description="Window start (UTC). Defaults to start of current calendar month.",
+ ),
+ until: datetime | None = Query(
+ None,
+ description="Window end (UTC). Defaults to now.",
+ ),
+ top_runs_limit: int = Query(
+ 10,
+ ge=1,
+ le=50,
+ description="Maximum number of top-cost runs to return.",
+ ),
+) -> UserExecutionCostSummary:
+ """Aggregated cost breakdown for the calling user's graph executions."""
+ if since is not None and until is not None and since > until:
+ raise HTTPException(
+ status_code=422,
+ detail="`since` must be earlier than or equal to `until`.",
+ )
+ return await get_user_cost_summary(
+ user_id=user_id,
+ since=since,
+ until=until,
+ top_runs_limit=top_runs_limit,
+ )
+
+
@v1_router.get(
path="/graphs/{graph_id}/executions",
summary="List graph executions",
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index 140cf3fab4..c4e32c7ec0 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -530,6 +530,141 @@ def test_list_invoices_default_limit(mocker: pytest_mock.MockFixture) -> None:
assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}
+# Executions cost summary tests
+def test_executions_cost_summary_returns_payload(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """The /executions/cost-summary route returns the aggregated payload."""
+ from prisma.enums import AgentExecutionStatus
+
+ from backend.data.execution_cost_summary import (
+ UserAgentCostRollup,
+ UserDailyCost,
+ UserExecutionCostSummary,
+ UserTopRun,
+ )
+
+ summary = UserExecutionCostSummary(
+ total_cents=4200,
+ run_count=12,
+ billable_run_count=10,
+ failed_cost_cents=500,
+ by_agent=[
+ UserAgentCostRollup(graph_id="g-1", cost_cents=3000, run_count=8),
+ UserAgentCostRollup(graph_id="g-2", cost_cents=1200, run_count=4),
+ ],
+ top_runs=[
+ UserTopRun(
+ execution_id="exec-1",
+ graph_id="g-1",
+ cost_cents=2500,
+ started_at=datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc),
+ status=AgentExecutionStatus.COMPLETED,
+ duration_seconds=45.5,
+ node_error_count=0,
+ ),
+ ],
+ daily=[
+ UserDailyCost(date="2026-05-10", cost_cents=3000, run_count=8),
+ UserDailyCost(date="2026-05-11", cost_cents=1200, run_count=4),
+ ],
+ )
+
+ mock_fn = mocker.patch(
+ "backend.api.features.v1.get_user_cost_summary",
+ AsyncMock(return_value=summary),
+ )
+
+ response = client.get("/executions/cost-summary")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["total_cents"] == 4200
+ assert payload["run_count"] == 12
+ assert payload["billable_run_count"] == 10
+ assert payload["failed_cost_cents"] == 500
+ assert len(payload["by_agent"]) == 2
+ assert payload["by_agent"][0]["graph_id"] == "g-1"
+ assert payload["by_agent"][0]["cost_cents"] == 3000
+ assert len(payload["top_runs"]) == 1
+ assert payload["top_runs"][0]["execution_id"] == "exec-1"
+ assert payload["top_runs"][0]["cost_cents"] == 2500
+ assert len(payload["daily"]) == 2
+ assert payload["daily"][0]["date"] == "2026-05-10"
+ mock_fn.assert_awaited_once()
+
+
+def test_executions_cost_summary_forwards_since_until(
+ mocker: pytest_mock.MockFixture,
+ test_user_id: str,
+) -> None:
+ """since/until query params should reach get_user_cost_summary."""
+ from backend.data.execution_cost_summary import UserExecutionCostSummary
+
+ mock_fn = mocker.patch(
+ "backend.api.features.v1.get_user_cost_summary",
+ AsyncMock(
+ return_value=UserExecutionCostSummary(
+ total_cents=0,
+ run_count=0,
+ billable_run_count=0,
+ failed_cost_cents=0,
+ by_agent=[],
+ top_runs=[],
+ daily=[],
+ )
+ ),
+ )
+
+ response = client.get(
+ "/executions/cost-summary"
+ "?since=2026-05-01T00:00:00Z"
+ "&until=2026-05-15T00:00:00Z"
+ "&top_runs_limit=5"
+ )
+
+ assert response.status_code == 200
+ kwargs = mock_fn.await_args.kwargs
+ assert kwargs["user_id"] == test_user_id
+ assert kwargs["since"] == datetime(2026, 5, 1, tzinfo=timezone.utc)
+ assert kwargs["until"] == datetime(2026, 5, 15, tzinfo=timezone.utc)
+ assert kwargs["top_runs_limit"] == 5
+
+
+def test_executions_cost_summary_rejects_out_of_range_limit(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """top_runs_limit must be within [1, 50]."""
+ mock_fn = mocker.patch(
+ "backend.api.features.v1.get_user_cost_summary",
+ AsyncMock(),
+ )
+
+ response = client.get("/executions/cost-summary?top_runs_limit=500")
+
+ assert response.status_code == 422
+ mock_fn.assert_not_awaited()
+
+
+def test_executions_cost_summary_rejects_inverted_window(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """`since > until` is bad client input — surface 422, don't quietly return zeros."""
+ mock_fn = mocker.patch(
+ "backend.api.features.v1.get_user_cost_summary",
+ AsyncMock(),
+ )
+
+ response = client.get(
+ "/executions/cost-summary"
+ "?since=2026-05-15T00:00:00Z"
+ "&until=2026-05-01T00:00:00Z"
+ )
+
+ assert response.status_code == 422
+ mock_fn.assert_not_awaited()
+
+
# Graphs endpoints tests
def test_get_graphs(
mocker: pytest_mock.MockFixture,
diff --git a/autogpt_platform/backend/backend/data/execution_cost_summary.py b/autogpt_platform/backend/backend/data/execution_cost_summary.py
new file mode 100644
index 0000000000..3526430fa4
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/execution_cost_summary.py
@@ -0,0 +1,175 @@
+"""Per-user execution cost aggregation models and query."""
+
+import asyncio
+from datetime import date, datetime, timezone
+
+from prisma.enums import AgentExecutionStatus
+from pydantic import BaseModel
+
+from .db import query_raw_with_schema
+
+
+class UserAgentCostRollup(BaseModel):
+ graph_id: str
+ cost_cents: int
+ run_count: int
+
+
+class UserTopRun(BaseModel):
+ execution_id: str
+ graph_id: str
+ cost_cents: int
+ started_at: datetime
+ status: AgentExecutionStatus
+ duration_seconds: float
+ node_error_count: int
+
+
+class UserDailyCost(BaseModel):
+ date: date
+ cost_cents: int
+ run_count: int
+
+
+class UserExecutionCostSummary(BaseModel):
+ total_cents: int
+ run_count: int
+ billable_run_count: int
+ failed_cost_cents: int
+ by_agent: list[UserAgentCostRollup]
+ top_runs: list[UserTopRun]
+ daily: list[UserDailyCost]
+
+
+_MAX_BY_AGENT_ROWS = 50
+_MAX_TOP_RUNS = 50
+
+
+async def get_user_cost_summary(
+ *,
+ user_id: str,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ top_runs_limit: int = 10,
+) -> UserExecutionCostSummary:
+ """Aggregate per-user execution costs from AgentGraphExecution.stats JSON.
+
+ Defaults to the current calendar month (UTC) when `since`/`until` are not provided.
+ Dry-run executions are excluded.
+
+ Window filters use `createdAt` so the existing
+ `@@index([userId, isDeleted, createdAt])` is hit on `AgentGraphExecution`
+ — bucketing by `startedAt` instead would force a full per-user scan for
+ heavy users.
+ """
+ # Hard cap top_runs_limit here too, not just at the FastAPI layer, since
+ # this function is callable directly and an unbounded LIMIT would scan
+ # the whole per-user history on the cost-ordered `top_runs` query.
+ top_runs_limit = max(1, min(_MAX_TOP_RUNS, top_runs_limit))
+
+ now = datetime.now(timezone.utc)
+ if since is None:
+ since = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+ if until is None:
+ until = now
+
+ base_where = (
+ '"userId" = $1'
+ ' AND "isDeleted" = false'
+ ' AND "createdAt" >= $2::timestamp'
+ ' AND "createdAt" <= $3::timestamp'
+ " AND COALESCE((stats->>'is_dry_run')::boolean, false) = false"
+ )
+ params = (user_id, since, until)
+
+ totals_rows, by_agent_rows, top_runs_rows, daily_rows = await asyncio.gather(
+ query_raw_with_schema(
+ "SELECT"
+ " COALESCE(SUM((stats->>'cost')::numeric), 0)::bigint AS total_cents,"
+ " COUNT(*)::bigint AS run_count,"
+ " COUNT(*) FILTER (WHERE COALESCE((stats->>'cost')::numeric, 0) > 0)::bigint"
+ " AS billable_run_count,"
+ " COALESCE(SUM(CASE WHEN \"executionStatus\" IN ('FAILED', 'TERMINATED')"
+ " THEN (stats->>'cost')::numeric ELSE 0 END), 0)::bigint"
+ " AS failed_cost_cents"
+ ' FROM {schema_prefix}"AgentGraphExecution"'
+ f" WHERE {base_where}",
+ *params,
+ ),
+ query_raw_with_schema(
+ "SELECT"
+ ' "agentGraphId" AS graph_id,'
+ " COALESCE(SUM((stats->>'cost')::numeric), 0)::bigint AS cost_cents,"
+ " COUNT(*)::bigint AS run_count"
+ ' FROM {schema_prefix}"AgentGraphExecution"'
+ f" WHERE {base_where}"
+ ' GROUP BY "agentGraphId"'
+ " ORDER BY cost_cents DESC"
+ f" LIMIT {_MAX_BY_AGENT_ROWS}",
+ *params,
+ ),
+ query_raw_with_schema(
+ "SELECT"
+ " id AS execution_id,"
+ ' "agentGraphId" AS graph_id,'
+ " COALESCE((stats->>'cost')::numeric, 0)::bigint AS cost_cents,"
+ ' COALESCE("startedAt", "createdAt") AS started_at,'
+ ' "executionStatus" AS status,'
+ " COALESCE((stats->>'duration')::numeric, 0) AS duration_seconds,"
+ " COALESCE((stats->>'node_error_count')::int, 0) AS node_error_count"
+ ' FROM {schema_prefix}"AgentGraphExecution"'
+ f" WHERE {base_where}"
+ " AND COALESCE((stats->>'cost')::numeric, 0) > 0"
+ ' ORDER BY cost_cents DESC, "createdAt" DESC'
+ " LIMIT $4",
+ *params,
+ top_runs_limit,
+ ),
+ query_raw_with_schema(
+ "SELECT"
+ ' ("createdAt" AT TIME ZONE \'UTC\')::date AS "date",'
+ " COALESCE(SUM((stats->>'cost')::numeric), 0)::bigint AS cost_cents,"
+ " COUNT(*)::bigint AS run_count"
+ ' FROM {schema_prefix}"AgentGraphExecution"'
+ f" WHERE {base_where}"
+ " GROUP BY (\"createdAt\" AT TIME ZONE 'UTC')::date"
+ ' ORDER BY "date" ASC',
+ *params,
+ ),
+ )
+
+ totals = totals_rows[0] if totals_rows else {}
+ return UserExecutionCostSummary(
+ total_cents=int(totals.get("total_cents") or 0),
+ run_count=int(totals.get("run_count") or 0),
+ billable_run_count=int(totals.get("billable_run_count") or 0),
+ failed_cost_cents=int(totals.get("failed_cost_cents") or 0),
+ by_agent=[
+ UserAgentCostRollup(
+ graph_id=r["graph_id"],
+ cost_cents=int(r.get("cost_cents") or 0),
+ run_count=int(r.get("run_count") or 0),
+ )
+ for r in by_agent_rows
+ ],
+ top_runs=[
+ UserTopRun(
+ execution_id=r["execution_id"],
+ graph_id=r["graph_id"],
+ cost_cents=int(r.get("cost_cents") or 0),
+ started_at=r["started_at"],
+ status=AgentExecutionStatus(r["status"]),
+ duration_seconds=float(r.get("duration_seconds") or 0),
+ node_error_count=int(r.get("node_error_count") or 0),
+ )
+ for r in top_runs_rows
+ ],
+ daily=[
+ UserDailyCost(
+ date=r["date"],
+ cost_cents=int(r.get("cost_cents") or 0),
+ run_count=int(r.get("run_count") or 0),
+ )
+ for r in daily_rows
+ ],
+ )
diff --git a/autogpt_platform/backend/backend/data/execution_cost_summary_test.py b/autogpt_platform/backend/backend/data/execution_cost_summary_test.py
new file mode 100644
index 0000000000..0377b5be24
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/execution_cost_summary_test.py
@@ -0,0 +1,351 @@
+"""Integration tests for the SQL-aggregated user cost summary."""
+
+import logging
+from datetime import date, datetime, timedelta, timezone
+from uuid import uuid4
+
+import pytest
+from prisma.enums import AgentExecutionStatus
+from prisma.errors import UniqueViolationError
+from prisma.models import AgentGraph, AgentGraphExecution, User
+
+from backend.data.execution_cost_summary import get_user_cost_summary
+from backend.util.json import SafeJson
+from backend.util.test import SpinTestServer
+
+logger = logging.getLogger(__name__)
+
+
+async def _create_user(user_id: str) -> None:
+ try:
+ await User.prisma().create(
+ data={
+ "id": user_id,
+ "email": f"cost-summary-{user_id}@example.com",
+ "name": "Cost Summary Test",
+ }
+ )
+ except UniqueViolationError:
+ pass
+
+
+async def _create_graph(graph_id: str, user_id: str, name: str = "Test") -> None:
+ try:
+ await AgentGraph.prisma().create(
+ data={
+ "id": graph_id,
+ "version": 1,
+ "name": name,
+ "description": "test",
+ "userId": user_id,
+ "isActive": True,
+ }
+ )
+ except UniqueViolationError:
+ pass
+
+
+async def _create_run(
+ *,
+ run_id: str,
+ user_id: str,
+ graph_id: str,
+ status: AgentExecutionStatus,
+ cost_cents: int,
+ started_at: datetime,
+ duration: float = 1.0,
+ node_error_count: int = 0,
+ is_dry_run: bool = False,
+ created_at: datetime | None = None,
+) -> None:
+ stats = {
+ "cost": cost_cents,
+ "duration": duration,
+ "node_error_count": node_error_count,
+ }
+ if is_dry_run:
+ stats["is_dry_run"] = True
+ await AgentGraphExecution.prisma().create(
+ data={
+ "id": run_id,
+ "agentGraphId": graph_id,
+ "agentGraphVersion": 1,
+ "executionStatus": status,
+ "userId": user_id,
+ "createdAt": created_at if created_at is not None else started_at,
+ "startedAt": started_at,
+ "endedAt": started_at + timedelta(seconds=duration),
+ "stats": SafeJson(stats),
+ }
+ )
+
+
+async def _cleanup(user_id: str, graph_ids: list[str]) -> None:
+ try:
+ await AgentGraphExecution.prisma().delete_many(where={"userId": user_id})
+ for gid in graph_ids:
+ await AgentGraph.prisma().delete_many(where={"id": gid})
+ await User.prisma().delete_many(where={"id": user_id})
+ except Exception as exc:
+ logger.warning("cleanup for %s failed: %s", user_id, exc)
+
+
[email protected](loop_scope="session")
+async def test_empty_window_returns_zeroed_summary(server: SpinTestServer):
+ user_id = f"cs-empty-{uuid4()}"
+ await _create_user(user_id)
+ try:
+ now = datetime.now(timezone.utc)
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=now - timedelta(days=1),
+ until=now,
+ )
+ assert summary.total_cents == 0
+ assert summary.run_count == 0
+ assert summary.billable_run_count == 0
+ assert summary.failed_cost_cents == 0
+ assert summary.by_agent == []
+ assert summary.top_runs == []
+ assert summary.daily == []
+ finally:
+ await _cleanup(user_id, [])
+
+
[email protected](loop_scope="session")
+async def test_aggregates_by_agent_and_top_runs(server: SpinTestServer):
+ user_id = f"cs-agg-{uuid4()}"
+ graph_a = f"cs-g-a-{uuid4()}"
+ graph_b = f"cs-g-b-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_a, user_id, "Alpha")
+ await _create_graph(graph_b, user_id, "Beta")
+ try:
+ now = datetime.now(timezone.utc)
+ since = now - timedelta(days=3)
+
+ await _create_run(
+ run_id=f"e1-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_a,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=300,
+ started_at=now - timedelta(hours=2),
+ )
+ await _create_run(
+ run_id=f"e2-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_a,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=200,
+ started_at=now - timedelta(hours=1),
+ )
+ big_run_id = f"e3-{uuid4()}"
+ await _create_run(
+ run_id=big_run_id,
+ user_id=user_id,
+ graph_id=graph_b,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=1000,
+ started_at=now - timedelta(minutes=30),
+ )
+ failed_run_id = f"e4-{uuid4()}"
+ await _create_run(
+ run_id=failed_run_id,
+ user_id=user_id,
+ graph_id=graph_b,
+ status=AgentExecutionStatus.FAILED,
+ cost_cents=50,
+ started_at=now - timedelta(minutes=15),
+ node_error_count=2,
+ )
+ # TERMINATED is also "wasted" cost — locks the `IN ('FAILED', 'TERMINATED')`
+ # branch in the failed_cost_cents aggregator.
+ terminated_run_id = f"e5-{uuid4()}"
+ await _create_run(
+ run_id=terminated_run_id,
+ user_id=user_id,
+ graph_id=graph_b,
+ status=AgentExecutionStatus.TERMINATED,
+ cost_cents=20,
+ started_at=now - timedelta(minutes=10),
+ )
+ # Zero-cost run — included in run_count but excluded from billable_run_count,
+ # so the frontend Avg / run denominator stays honest.
+ await _create_run(
+ run_id=f"e6-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_a,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=0,
+ started_at=now - timedelta(minutes=5),
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=since,
+ until=now + timedelta(minutes=1),
+ top_runs_limit=3,
+ )
+
+ assert summary.total_cents == 1570
+ assert summary.run_count == 6
+ assert summary.billable_run_count == 5
+ # 50 FAILED + 20 TERMINATED
+ assert summary.failed_cost_cents == 70
+
+ by_agent = {row.graph_id: row for row in summary.by_agent}
+ assert by_agent[graph_a].cost_cents == 500
+ # 2 paid runs + 1 zero-cost run on graph_a
+ assert by_agent[graph_a].run_count == 3
+ assert by_agent[graph_b].cost_cents == 1070
+ assert by_agent[graph_b].run_count == 3
+ # graph_b leads on total spend so it sorts first
+ assert summary.by_agent[0].graph_id == graph_b
+
+ # Top runs ordered by cost desc; limit honored
+ assert summary.top_runs[0].execution_id == big_run_id
+ assert summary.top_runs[0].cost_cents == 1000
+ assert len(summary.top_runs) == 3
+ finally:
+ await _cleanup(user_id, [graph_a, graph_b])
+
+
[email protected](loop_scope="session")
+async def test_excludes_dry_runs_and_outside_window(server: SpinTestServer):
+ user_id = f"cs-filter-{uuid4()}"
+ graph_id = f"cs-g-f-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_id, user_id)
+ try:
+ now = datetime.now(timezone.utc)
+
+ # In window, real run -> counted
+ await _create_run(
+ run_id=f"in-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=400,
+ started_at=now - timedelta(hours=1),
+ )
+ # In window, dry run -> excluded
+ await _create_run(
+ run_id=f"dry-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=900,
+ started_at=now - timedelta(hours=1),
+ is_dry_run=True,
+ )
+ # Outside window -> excluded
+ await _create_run(
+ run_id=f"old-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=700,
+ started_at=now - timedelta(days=10),
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=now - timedelta(days=1),
+ until=now + timedelta(minutes=1),
+ )
+
+ assert summary.total_cents == 400
+ assert summary.run_count == 1
+ finally:
+ await _cleanup(user_id, [graph_id])
+
+
[email protected](loop_scope="session")
+async def test_daily_buckets_group_by_utc_date(server: SpinTestServer):
+ user_id = f"cs-daily-{uuid4()}"
+ graph_id = f"cs-g-d-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_id, user_id)
+ try:
+ day1 = datetime(2026, 1, 10, 9, 0, tzinfo=timezone.utc)
+ day2 = datetime(2026, 1, 11, 9, 0, tzinfo=timezone.utc)
+
+ await _create_run(
+ run_id=f"d1a-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=100,
+ started_at=day1,
+ )
+ await _create_run(
+ run_id=f"d1b-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=250,
+ started_at=day1,
+ )
+ await _create_run(
+ run_id=f"d2-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=400,
+ started_at=day2,
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=day1 - timedelta(hours=1),
+ until=day2 + timedelta(hours=1),
+ )
+
+ assert [d.date for d in summary.daily] == [
+ date(2026, 1, 10),
+ date(2026, 1, 11),
+ ]
+ assert summary.daily[0].cost_cents == 350
+ assert summary.daily[0].run_count == 2
+ assert summary.daily[1].cost_cents == 400
+ assert summary.daily[1].run_count == 1
+ finally:
+ await _cleanup(user_id, [graph_id])
+
+
[email protected](loop_scope="session")
+async def test_daily_buckets_follow_created_at_not_started_at(
+ server: SpinTestServer,
+):
+ # A queued-then-started run lands in the createdAt bucket, not the
+ # startedAt bucket — locks the index-hit invariant documented in
+ # backend/data/execution_cost_summary.py get_user_cost_summary docstring.
+ user_id = f"cs-created-{uuid4()}"
+ graph_id = f"cs-g-c-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_id, user_id)
+ try:
+ created_day = datetime(2026, 2, 5, 23, 30, tzinfo=timezone.utc)
+ started_day = datetime(2026, 2, 7, 9, 0, tzinfo=timezone.utc)
+
+ await _create_run(
+ run_id=f"q-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=600,
+ started_at=started_day,
+ created_at=created_day,
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=created_day - timedelta(hours=1),
+ until=started_day + timedelta(hours=1),
+ )
+
+ assert [d.date for d in summary.daily] == [date(2026, 2, 5)]
+ assert summary.daily[0].cost_cents == 600
+ finally:
+ await _cleanup(user_id, [graph_id])
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts
index 239085f39a..c459a5a466 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/route.ts
@@ -28,6 +28,10 @@ export async function GET(request: Request) {
: {
message_type: "oauth_popup_result",
success: false,
+ // Echo back `state` when present so the originating page's
+ // state-keyed listeners route the failure to the right flow
+ // instead of timing out silently.
+ ...(state ? { state } : {}),
message: `Incomplete query: ${searchParams.toString()}`,
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/types.ts b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/types.ts
index 9000adf392..b9a009d757 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/types.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/oauth_callback/types.ts
@@ -6,6 +6,10 @@ export type OAuthPopupResultMessage = { message_type: "oauth_popup_result" } & (
}
| {
success: false;
+ // Optional — present when the callback received a `state` token even
+ // though it could not produce a successful result. Listeners filter
+ // payloads by state, so an error without it would be silently dropped.
+ state?: string;
message: string;
}
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/briefing.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/briefing.test.tsx
index 635bd137c7..e89515e0fd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/briefing.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/briefing.test.tsx
@@ -1,9 +1,3 @@
-// Force a non-UTC timezone so the UTC-month boundary logic in
-// `startOfCurrentMonth` can be distinguished from a hypothetical local-month
-// implementation. Node reads TZ on each Date operation on Linux (CI), so this
-// takes effect before any `new Date(...)` below.
-process.env.TZ = "America/Los_Angeles";
-
import { afterEach, describe, expect, test, vi } from "vitest";
import { within } from "@testing-library/react";
import { render, screen } from "@/tests/integrations/test-utils";
@@ -18,13 +12,13 @@ import {
getGetV2ListLibraryFoldersMockHandler,
getGetV2ListLibraryFoldersResponseMock,
} from "@/app/api/__generated__/endpoints/folders/folders.msw";
-import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";
+import {
+ getGetV1ListAllExecutionsMockHandler,
+ getGetV1UserCostSummaryMockHandler,
+} from "@/app/api/__generated__/endpoints/graphs/graphs.msw";
import { Flag } from "@/services/feature-flags/use-get-flag";
import LibraryPage from "../page";
-// Defensive teardown: if a test fails before its final `vi.useRealTimers()`,
-// later tests would inherit fake timers. Global `cleanup()` is handled in
-// `src/tests/integrations/vitest.setup.tsx`.
afterEach(() => {
vi.useRealTimers();
});
@@ -39,9 +33,7 @@ vi.mock("@/services/feature-flags/use-get-flag", async () => {
};
});
-function setupHandlers(
- executions: Parameters<typeof getGetV1ListAllExecutionsMockHandler>[0],
-) {
+function setupHandlers({ totalCents }: { totalCents: number }) {
const agents = [
{ ...getGetV2ListLibraryAgentsResponseMock().agents[0], graph_id: "g-1" },
];
@@ -77,77 +69,25 @@ function setupHandlers(
},
}),
),
- getGetV1ListAllExecutionsMockHandler(executions),
+ getGetV1ListAllExecutionsMockHandler([]),
+ getGetV1UserCostSummaryMockHandler({
+ total_cents: totalCents,
+ run_count: totalCents > 0 ? 3 : 0,
+ billable_run_count: totalCents > 0 ? 3 : 0,
+ failed_cost_cents: 0,
+ by_agent:
+ totalCents > 0
+ ? [{ graph_id: "g-1", cost_cents: totalCents, run_count: 3 }]
+ : [],
+ top_runs: [],
+ daily: [],
+ }),
);
}
describe("LibraryPage — AgentBriefingPanel 'Spent this month' tile", () => {
- test("sums execution costs from the current UTC month and formats as currency", async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- vi.setSystemTime(new Date("2026-04-15T12:00:00.000Z"));
-
- setupHandlers([
- {
- id: "this-month-a",
- user_id: "test-user",
- graph_id: "g-1",
- graph_version: 1,
- inputs: {},
- credential_inputs: {},
- nodes_input_masks: {},
- preset_id: null,
- status: "COMPLETED",
- started_at: new Date("2026-04-02T10:00:00.000Z"),
- ended_at: new Date("2026-04-02T10:05:00.000Z"),
- stats: { cost: 250 },
- },
- {
- id: "this-month-b",
- user_id: "test-user",
- graph_id: "g-1",
- graph_version: 1,
- inputs: {},
- credential_inputs: {},
- nodes_input_masks: {},
- preset_id: null,
- status: "COMPLETED",
- started_at: new Date("2026-04-10T10:00:00.000Z"),
- ended_at: new Date("2026-04-10T10:02:00.000Z"),
- stats: { cost: 75 },
- },
- {
- // April 1 in UTC, but March 31 22:00 in America/Los_Angeles.
- // A buggy local-month implementation would exclude this execution
- // under TZ=America/Los_Angeles; the correct UTC-month logic includes
- // it. Contributes 500 cents to the expected $8.25 total.
- id: "utc-vs-local-boundary",
- user_id: "test-user",
- graph_id: "g-1",
- graph_version: 1,
- inputs: {},
- credential_inputs: {},
- nodes_input_masks: {},
- preset_id: null,
- status: "COMPLETED",
- started_at: new Date("2026-04-01T05:00:00.000Z"),
- ended_at: new Date("2026-04-01T05:02:00.000Z"),
- stats: { cost: 500 },
- },
- {
- id: "previous-month",
- user_id: "test-user",
- graph_id: "g-1",
- graph_version: 1,
- inputs: {},
- credential_inputs: {},
- nodes_input_masks: {},
- preset_id: null,
- status: "COMPLETED",
- started_at: new Date("2026-03-31T23:59:00.000Z"),
- ended_at: new Date("2026-04-01T00:00:00.000Z"),
- stats: { cost: 9999 },
- },
- ]);
+ test("shows monthly spend from the cost-summary endpoint", async () => {
+ setupHandlers({ totalCents: 825 });
render(<LibraryPage />);
@@ -157,19 +97,11 @@ describe("LibraryPage — AgentBriefingPanel 'Spent this month' tile", () => {
if (!tile) {
throw new Error("Spent this month tile should render inside a button");
}
- // 250 + 75 + 500 = 825 cents = $8.25. The late-March UTC execution must
- // NOT contribute, and the April-1-UTC/March-31-local execution MUST
- // contribute (confirms UTC-month boundary under a non-UTC test zone).
expect(within(tile).getByText("$8.25")).toBeDefined();
-
- vi.useRealTimers();
});
- test("renders $0.00 when no executions ran this month", async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- vi.setSystemTime(new Date("2026-04-15T12:00:00.000Z"));
-
- setupHandlers([]);
+ test("renders $0.00 when the endpoint reports zero spend", async () => {
+ setupHandlers({ totalCents: 0 });
render(<LibraryPage />);
@@ -180,7 +112,5 @@ describe("LibraryPage — AgentBriefingPanel 'Spent this month' tile", () => {
throw new Error("Spent this month tile should render inside a button");
}
expect(within(tile).getByText("$0.00")).toBeDefined();
-
- vi.useRealTimers();
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx
index 760a0563a8..c985d020e1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx
@@ -18,6 +18,7 @@ import type { AgentStatusFilter } from "../../types";
import { Text } from "@/components/atoms/Text/Text";
import Link from "next/link";
import { useState } from "react";
+import { CostsBreakdown } from "./CostsBreakdown/CostsBreakdown";
interface Props {
activeTab: AgentStatusFilter;
@@ -26,7 +27,7 @@ interface Props {
export function BriefingTabContent({ activeTab, agents }: Props) {
if (activeTab === "all") {
- return <UsageSection />;
+ return <UsageSection agents={agents} />;
}
if (
@@ -40,7 +41,7 @@ export function BriefingTabContent({ activeTab, agents }: Props) {
return <AgentListSection activeTab={activeTab} agents={agents} />;
}
-function UsageSection() {
+function UsageSection({ agents }: { agents: LibraryAgent[] }) {
const { data: usage, isSuccess } = useGetV2GetCopilotUsage({
query: {
select: (res) => res.data as CoPilotUsagePublic,
@@ -51,48 +52,55 @@ function UsageSection() {
const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
- if (!isSuccess || !usage) return null;
- if (!usage.daily && !usage.weekly) return null;
-
- const tierLabel = formatTierLabel(usage.tier);
+ const hasUsageMeters = isSuccess && usage && (usage.daily || usage.weekly);
+ const tierLabel = hasUsageMeters ? formatTierLabel(usage.tier) : null;
return (
<div className="py-2">
- <div className="flex items-center gap-2">
- <Text variant="h5" className="text-neutral-800">
- Usage limits
- </Text>
- {tierLabel && (
- <Badge variant="info" size="small" className={TIER_BADGE_CLASS_NAME}>
- {tierLabel} plan
- </Badge>
- )}
- <div className="flex-1" />
- {isBillingEnabled && (
- <Link
- href="/settings/billing"
- className="text-sm text-blue-600 hover:underline"
- >
- Manage billing
- </Link>
- )}
- </div>
- <div className="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2">
- {usage.daily && (
- <UsageMeter
- label="Today"
- percentUsed={usage.daily.percent_used}
- resetsAt={usage.daily.resets_at}
- />
- )}
- {usage.weekly && (
- <UsageMeter
- label="This week"
- percentUsed={usage.weekly.percent_used}
- resetsAt={usage.weekly.resets_at}
- />
- )}
- </div>
+ {hasUsageMeters && (
+ <>
+ <div className="flex items-center gap-2">
+ <Text variant="h5" className="text-neutral-800">
+ Usage limits
+ </Text>
+ {tierLabel && (
+ <Badge
+ variant="info"
+ size="small"
+ className={TIER_BADGE_CLASS_NAME}
+ >
+ {tierLabel} plan
+ </Badge>
+ )}
+ <div className="flex-1" />
+ {isBillingEnabled && (
+ <Link
+ href="/settings/billing"
+ className="text-sm text-blue-600 hover:underline"
+ >
+ Manage billing
+ </Link>
+ )}
+ </div>
+ <div className="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2">
+ {usage.daily && (
+ <UsageMeter
+ label="Today"
+ percentUsed={usage.daily.percent_used}
+ resetsAt={usage.daily.resets_at}
+ />
+ )}
+ {usage.weekly && (
+ <UsageMeter
+ label="This week"
+ percentUsed={usage.weekly.percent_used}
+ resetsAt={usage.weekly.resets_at}
+ />
+ )}
+ </div>
+ </>
+ )}
+ <CostsBreakdown agents={agents} />
</div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/CostsBreakdown.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/CostsBreakdown.tsx
new file mode 100644
index 0000000000..4c19564610
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/CostsBreakdown.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { Button } from "@/components/atoms/Button/Button";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import { formatCents } from "@/app/(platform)/copilot/components/usageHelpers";
+import { CaretDownIcon } from "@phosphor-icons/react";
+import { useState } from "react";
+import { SpendByAgentList } from "./components/SpendByAgentList";
+import { TopRunsList } from "./components/TopRunsList";
+import { useCostsBreakdown } from "./useCostsBreakdown";
+
+interface Props {
+ agents: LibraryAgent[];
+}
+
+export function CostsBreakdown({ agents }: Props) {
+ const [isExpanded, setIsExpanded] = useState(false);
+ const { summary, agentLookup, isLoading, isError, hasAnySpend } =
+ useCostsBreakdown(agents, { enabled: isExpanded });
+
+ return (
+ <section className="mt-6 flex flex-col gap-4">
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={() => setIsExpanded((prev) => !prev)}
+ aria-expanded={isExpanded}
+ className="w-fit gap-1 px-0 text-neutral-800 hover:bg-transparent"
+ >
+ {isExpanded ? "Hide costs breakdown" : "See costs breakdown"}
+ <CaretDownIcon
+ size={14}
+ className={`transition-transform ${isExpanded ? "rotate-180" : ""}`}
+ />
+ </Button>
+
+ {isExpanded && (
+ <ExpandedBody
+ summary={summary}
+ agentLookup={agentLookup}
+ isLoading={isLoading}
+ isError={isError}
+ hasAnySpend={hasAnySpend}
+ />
+ )}
+ </section>
+ );
+}
+
+interface ExpandedBodyProps {
+ summary: ReturnType<typeof useCostsBreakdown>["summary"];
+ agentLookup: ReturnType<typeof useCostsBreakdown>["agentLookup"];
+ isLoading: boolean;
+ isError: boolean;
+ hasAnySpend: boolean;
+}
+
+function ExpandedBody({
+ summary,
+ agentLookup,
+ isLoading,
+ isError,
+ hasAnySpend,
+}: ExpandedBodyProps) {
+ if (isError) {
+ return (
+ <Text variant="body" className="text-neutral-500">
+ Couldn&apos;t load cost breakdown.
+ </Text>
+ );
+ }
+
+ if (isLoading || !summary) {
+ return (
+ <div className="flex flex-col gap-3">
+ <Skeleton className="h-16 w-full" />
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
+ <Skeleton className="h-48 w-full" />
+ <Skeleton className="h-48 w-full" />
+ </div>
+ </div>
+ );
+ }
+
+ if (!hasAnySpend) {
+ return (
+ <Text variant="body" className="text-neutral-500">
+ No spend this month yet.
+ </Text>
+ );
+ }
+
+ // Divide by billable_run_count (runs with cost>0), not run_count, so the
+ // average isn't deflated by zero-cost runs that contribute to the count
+ // but nothing to the total.
+ const avgCostCents =
+ summary.billable_run_count > 0
+ ? summary.total_cents / summary.billable_run_count
+ : 0;
+
+ return (
+ <>
+ <StatRow
+ items={[
+ {
+ label: "Total this month",
+ value: formatCents(summary.total_cents),
+ },
+ { label: "Runs", value: String(summary.run_count) },
+ {
+ label: "Avg / run",
+ value: formatCents(Math.round(avgCostCents)),
+ },
+ {
+ label: "Wasted on failed",
+ value: formatCents(summary.failed_cost_cents),
+ tone: summary.failed_cost_cents > 0 ? "warn" : undefined,
+ },
+ ]}
+ />
+
+ <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
+ <TopRunsList runs={summary.top_runs} agentLookup={agentLookup} />
+ <SpendByAgentList
+ rollups={summary.by_agent}
+ agentLookup={agentLookup}
+ />
+ </div>
+ </>
+ );
+}
+
+interface StatItem {
+ label: string;
+ value: string;
+ tone?: "warn";
+}
+
+function StatRow({ items }: { items: StatItem[] }) {
+ return (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {items.map((item) => (
+ <div
+ key={item.label}
+ className="flex flex-col gap-0.5 rounded-medium border border-zinc-100 bg-white p-3"
+ >
+ <Text variant="small" className="text-neutral-500">
+ {item.label}
+ </Text>
+ <Text
+ variant="body-medium"
+ className={
+ item.tone === "warn"
+ ? "tabular-nums text-orange-600"
+ : "tabular-nums text-neutral-800"
+ }
+ >
+ {item.value}
+ </Text>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..5bd10e0d69
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/__tests__/helpers.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+
+import { buildAgentLookup, formatRelativeDate } from "../helpers";
+
+describe("buildAgentLookup", () => {
+ test("maps each library agent by graph_id", () => {
+ const agents = [
+ {
+ id: "lib-1",
+ graph_id: "graph-a",
+ name: "Agent A",
+ image_url: "https://example.test/a.png",
+ },
+ {
+ id: "lib-2",
+ graph_id: "graph-b",
+ name: "Agent B",
+ image_url: null,
+ },
+ ] as unknown as LibraryAgent[];
+
+ const lookup = buildAgentLookup(agents);
+
+ expect(lookup.size).toBe(2);
+ expect(lookup.get("graph-a")).toEqual({
+ libraryAgentId: "lib-1",
+ name: "Agent A",
+ imageUrl: "https://example.test/a.png",
+ });
+ expect(lookup.get("graph-b")?.imageUrl).toBeNull();
+ });
+
+ test("returns an empty map for no agents", () => {
+ expect(buildAgentLookup([]).size).toBe(0);
+ });
+});
+
+describe("formatRelativeDate", () => {
+ const NOW = new Date("2026-05-15T12:00:00.000Z");
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("returns 'just now' for <1 minute ago", () => {
+ expect(formatRelativeDate(new Date(NOW.getTime() - 20_000))).toBe(
+ "just now",
+ );
+ });
+
+ test("returns minutes for <1 hour ago", () => {
+ expect(formatRelativeDate(new Date(NOW.getTime() - 5 * 60_000))).toBe(
+ "5m ago",
+ );
+ });
+
+ test("returns hours for <1 day ago", () => {
+ expect(formatRelativeDate(new Date(NOW.getTime() - 3 * 3_600_000))).toBe(
+ "3h ago",
+ );
+ });
+
+ test("returns days for <30 days ago", () => {
+ expect(formatRelativeDate(new Date(NOW.getTime() - 4 * 86_400_000))).toBe(
+ "4d ago",
+ );
+ });
+
+ test("returns absolute month+day when older than 30 days", () => {
+ const out = formatRelativeDate(new Date("2026-03-10T12:00:00.000Z"));
+ expect(out).toMatch(/Mar/);
+ expect(out).toMatch(/10/);
+ });
+
+ test("accepts ISO string input", () => {
+ expect(formatRelativeDate("2026-05-15T11:50:00.000Z")).toBe("10m ago");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/SpendByAgentList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/SpendByAgentList.tsx
new file mode 100644
index 0000000000..ff495f11f8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/SpendByAgentList.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import type { UserAgentCostRollup } from "@/app/api/__generated__/models/userAgentCostRollup";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { formatCents } from "@/app/(platform)/copilot/components/usageHelpers";
+import Link from "next/link";
+import { useState } from "react";
+import type { AgentLookupEntry } from "../helpers";
+
+interface Props {
+ rollups: UserAgentCostRollup[];
+ agentLookup: Map<string, AgentLookupEntry>;
+}
+
+const INITIAL_VISIBLE = 5;
+
+export function SpendByAgentList({ rollups, agentLookup }: Props) {
+ const [showAll, setShowAll] = useState(false);
+ if (rollups.length === 0) return null;
+
+ const maxCost = Math.max(...rollups.map((r) => r.cost_cents), 1);
+ const visible = showAll ? rollups : rollups.slice(0, INITIAL_VISIBLE);
+ const hasMore = rollups.length > INITIAL_VISIBLE;
+
+ return (
+ <section className="flex flex-col gap-2 lg:mt-[1rem]">
+ <Text variant="body-medium" className="text-neutral-800 lg:mb-[.5rem]">
+ Spend by agent
+ </Text>
+ <ul className="flex flex-col gap-4">
+ {visible.map((rollup) => {
+ const agent = agentLookup.get(rollup.graph_id);
+ const label = agent?.name ?? `Agent ${rollup.graph_id.slice(0, 8)}`;
+ const widthPct = Math.max(
+ 2,
+ Math.round((rollup.cost_cents / maxCost) * 100),
+ );
+ const href = agent ? `/library/agents/${agent.libraryAgentId}` : null;
+
+ const row = (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-baseline justify-between gap-3">
+ <Text variant="body" className="truncate text-neutral-800">
+ {label}
+ </Text>
+ <Text
+ variant="body-medium"
+ className="tabular-nums text-neutral-800"
+ >
+ {formatCents(rollup.cost_cents)}
+ <Text
+ variant="small"
+ as="span"
+ className="ml-2 text-neutral-400"
+ >
+ {rollup.run_count} run{rollup.run_count === 1 ? "" : "s"}
+ </Text>
+ </Text>
+ </div>
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-zinc-100">
+ <div
+ className="h-full rounded-full bg-blue-500"
+ style={{ width: `${widthPct}%` }}
+ aria-hidden="true"
+ />
+ </div>
+ </div>
+ );
+
+ return (
+ <li key={rollup.graph_id}>
+ {href ? (
+ <Link
+ href={href}
+ className="-m-1 block rounded-small p-1 hover:bg-zinc-50"
+ >
+ {row}
+ </Link>
+ ) : (
+ row
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {hasMore && (
+ <div className="flex justify-center">
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setShowAll(!showAll)}
+ >
+ {showAll ? "Collapse" : `Show all (${rollups.length})`}
+ </Button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/TopRunsList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/TopRunsList.tsx
new file mode 100644
index 0000000000..7cc81e0c20
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/components/TopRunsList.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import type { UserTopRun } from "@/app/api/__generated__/models/userTopRun";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { formatCents } from "@/app/(platform)/copilot/components/usageHelpers";
+import Link from "next/link";
+import { useState } from "react";
+import { formatRelativeDate, type AgentLookupEntry } from "../helpers";
+
+interface Props {
+ runs: UserTopRun[];
+ agentLookup: Map<string, AgentLookupEntry>;
+}
+
+const INITIAL_VISIBLE = 5;
+
+export function TopRunsList({ runs, agentLookup }: Props) {
+ const [showAll, setShowAll] = useState(false);
+ if (runs.length === 0) return null;
+
+ const visible = showAll ? runs : runs.slice(0, INITIAL_VISIBLE);
+ const hasMore = runs.length > INITIAL_VISIBLE;
+
+ return (
+ <section className="flex flex-col gap-2 lg:mt-[1rem]">
+ <Text variant="body-medium" className="text-neutral-800 lg:mb-[.5rem]">
+ Most expensive runs
+ </Text>
+ <ul className="flex flex-col divide-y divide-zinc-100 rounded-medium border border-zinc-100 bg-white">
+ {visible.map((run) => {
+ const agent = agentLookup.get(run.graph_id);
+ const label = agent?.name ?? `Agent ${run.graph_id.slice(0, 8)}`;
+ const href = agent
+ ? `/library/agents/${agent.libraryAgentId}?activeItem=${run.execution_id}`
+ : null;
+
+ const row = (
+ <div className="flex items-center justify-between gap-3 px-3 py-2">
+ <div className="min-w-0 flex-1">
+ <Text variant="body" className="truncate text-neutral-800">
+ {label}
+ </Text>
+ <Text variant="small" className="text-neutral-400">
+ {formatRelativeDate(run.started_at)}
+ {run.node_error_count > 0
+ ? ` · ${run.node_error_count} error${run.node_error_count === 1 ? "" : "s"}`
+ : ""}
+ </Text>
+ </div>
+ <Text
+ variant="body-medium"
+ className="tabular-nums text-neutral-800"
+ >
+ {formatCents(run.cost_cents)}
+ </Text>
+ </div>
+ );
+
+ return (
+ <li key={run.execution_id}>
+ {href ? (
+ <Link href={href} className="block hover:bg-zinc-50">
+ {row}
+ </Link>
+ ) : (
+ row
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {hasMore && (
+ <div className="flex justify-center">
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setShowAll(!showAll)}
+ >
+ {showAll ? "Collapse" : `Show all (${runs.length})`}
+ </Button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/helpers.ts
new file mode 100644
index 0000000000..f92c0767bd
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/helpers.ts
@@ -0,0 +1,34 @@
+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+
+export interface AgentLookupEntry {
+ libraryAgentId: string;
+ name: string;
+ imageUrl?: string | null;
+}
+
+export function buildAgentLookup(
+ agents: LibraryAgent[],
+): Map<string, AgentLookupEntry> {
+ const map = new Map<string, AgentLookupEntry>();
+ for (const agent of agents) {
+ map.set(agent.graph_id, {
+ libraryAgentId: agent.id,
+ name: agent.name,
+ imageUrl: agent.image_url,
+ });
+ }
+ return map;
+}
+
+export function formatRelativeDate(input: string | Date): string {
+ const date = input instanceof Date ? input : new Date(input);
+ const diffMs = Date.now() - date.getTime();
+ const minutes = Math.round(diffMs / 60_000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.round(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/useCostsBreakdown.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/useCostsBreakdown.ts
new file mode 100644
index 0000000000..e4166e19dc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/CostsBreakdown/useCostsBreakdown.ts
@@ -0,0 +1,34 @@
+import { useGetV1UserCostSummary } from "@/app/api/__generated__/endpoints/graphs/graphs";
+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import type { UserExecutionCostSummary } from "@/app/api/__generated__/models/userExecutionCostSummary";
+import { useMemo } from "react";
+import { buildAgentLookup } from "./helpers";
+
+export function useCostsBreakdown(
+ agents: LibraryAgent[],
+ { enabled }: { enabled: boolean },
+) {
+ const {
+ data: summary,
+ isLoading,
+ isError,
+ } = useGetV1UserCostSummary(undefined, {
+ query: {
+ select: (res) => res.data as UserExecutionCostSummary,
+ staleTime: 60_000,
+ enabled,
+ },
+ });
+
+ const agentLookup = useMemo(() => buildAgentLookup(agents), [agents]);
+
+ const hasAnySpend = (summary?.total_cents ?? 0) > 0;
+
+ return {
+ summary,
+ agentLookup,
+ isLoading,
+ isError,
+ hasAnySpend,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx
index c293395f25..5107125c36 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/__tests__/BriefingTabContent.test.tsx
@@ -1,8 +1,10 @@
-import { render, screen } from "@/tests/integrations/test-utils";
+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BriefingTabContent } from "../BriefingTabContent";
const mockUseGetV2GetCopilotUsage = vi.fn();
+const mockUseGetV1UserCostSummary = vi.fn();
vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({
useGetV2GetCopilotUsage: (opts: {
query?: { select?: (r: { data: unknown }) => unknown };
@@ -14,6 +16,31 @@ vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({
return ret;
},
}));
+vi.mock(
+ "@/app/api/__generated__/endpoints/graphs/graphs",
+ async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/app/api/__generated__/endpoints/graphs/graphs")
+ >();
+ return {
+ ...actual,
+ useGetV1UserCostSummary: (
+ _params: unknown,
+ opts: { query?: { select?: (r: { data: unknown }) => unknown } },
+ ) => {
+ const ret = mockUseGetV1UserCostSummary() as { data?: unknown };
+ if (
+ ret?.data !== undefined &&
+ typeof opts?.query?.select === "function"
+ ) {
+ return { ...ret, data: opts.query.select({ data: ret.data }) };
+ }
+ return ret;
+ },
+ };
+ },
+);
const mockUseGetFlag = vi.fn();
vi.mock("@/services/feature-flags/use-get-flag", async () => {
@@ -28,6 +55,7 @@ vi.mock("@/services/feature-flags/use-get-flag", async () => {
afterEach(() => {
mockUseGetV2GetCopilotUsage.mockReset();
+ mockUseGetV1UserCostSummary.mockReset();
mockUseGetFlag.mockReset();
});
@@ -54,29 +82,65 @@ function makeUsage({
};
}
+function emptyCostSummary() {
+ return {
+ data: {
+ total_cents: 0,
+ run_count: 0,
+ billable_run_count: 0,
+ failed_cost_cents: 0,
+ by_agent: [],
+ top_runs: [],
+ daily: [],
+ },
+ isLoading: false,
+ isError: false,
+ };
+}
+
+function makeAgent(overrides: Partial<LibraryAgent> = {}): LibraryAgent {
+ return {
+ id: overrides.id ?? "lib-1",
+ graph_id: overrides.graph_id ?? "g-1",
+ name: overrides.name ?? "Agent One",
+ image_url: overrides.image_url ?? null,
+ description: "",
+ creator_image_url: "",
+ creator_name: "",
+ has_external_trigger: false,
+ is_scheduled: false,
+ next_scheduled_run: null,
+ recommended_schedule_cron: null,
+ status: "COMPLETED",
+ updated_at: new Date().toISOString(),
+ new_output: false,
+ can_access_graph: true,
+ is_latest_version: true,
+ graph_version: 1,
+ } as unknown as LibraryAgent;
+}
+
describe("BriefingTabContent — UsageSection", () => {
- it("renders nothing when usage fetch has not succeeded", () => {
+ it("renders no usage block when usage fetch has not succeeded", () => {
mockUseGetV2GetCopilotUsage.mockReturnValue({
data: undefined,
isSuccess: false,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
- const { container } = render(
- <BriefingTabContent activeTab="all" agents={[]} />,
- );
- expect(container.innerHTML).toBe("");
+ render(<BriefingTabContent activeTab="all" agents={[]} />);
+ expect(screen.queryByText("Usage limits")).toBeNull();
});
- it("renders nothing when both windows are null (no limits configured)", () => {
+ it("renders no usage block when both windows are null", () => {
mockUseGetV2GetCopilotUsage.mockReturnValue({
data: makeUsage({ dailyPercent: null, weeklyPercent: null }),
isSuccess: true,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
- const { container } = render(
- <BriefingTabContent activeTab="all" agents={[]} />,
- );
- expect(container.innerHTML).toBe("");
+ render(<BriefingTabContent activeTab="all" agents={[]} />);
+ expect(screen.queryByText("Usage limits")).toBeNull();
});
it("renders tier badge + daily+weekly meters at normal usage", () => {
@@ -84,6 +148,7 @@ describe("BriefingTabContent — UsageSection", () => {
data: makeUsage({ dailyPercent: 12, weeklyPercent: 4, tier: "PRO" }),
isSuccess: true,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(true);
render(<BriefingTabContent activeTab="all" agents={[]} />);
@@ -96,25 +161,15 @@ describe("BriefingTabContent — UsageSection", () => {
expect(screen.getByText("Manage billing")).toBeDefined();
});
- it("never renders the legacy 'Reset daily limit' button when daily is exhausted", () => {
- mockUseGetV2GetCopilotUsage.mockReturnValue({
- data: makeUsage({ dailyPercent: 100, weeklyPercent: 40 }),
- isSuccess: true,
- });
- mockUseGetFlag.mockReturnValue(true);
- render(<BriefingTabContent activeTab="all" agents={[]} />);
- expect(screen.queryByText(/Reset daily limit/)).toBeNull();
- });
-
- it("shows 'Manage billing' when billing flag is on, regardless of usage", () => {
+ it("shows 'Manage billing' when billing flag is on", () => {
mockUseGetV2GetCopilotUsage.mockReturnValue({
data: makeUsage({ dailyPercent: 100, weeklyPercent: 40 }),
isSuccess: true,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(true);
render(<BriefingTabContent activeTab="all" agents={[]} />);
expect(screen.getByText("Manage billing")).toBeDefined();
- expect(screen.queryByText("Go to billing")).toBeNull();
});
it("hides 'Manage billing' when billing flag is off", () => {
@@ -122,21 +177,10 @@ describe("BriefingTabContent — UsageSection", () => {
data: makeUsage({ dailyPercent: 100, weeklyPercent: 40 }),
isSuccess: true,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
render(<BriefingTabContent activeTab="all" agents={[]} />);
expect(screen.queryByText("Manage billing")).toBeNull();
- expect(screen.queryByText("Go to billing")).toBeNull();
- });
-
- it("still shows 'Manage billing' when both daily and weekly are exhausted", () => {
- mockUseGetV2GetCopilotUsage.mockReturnValue({
- data: makeUsage({ dailyPercent: 100, weeklyPercent: 100 }),
- isSuccess: true,
- });
- mockUseGetFlag.mockReturnValue(true);
- render(<BriefingTabContent activeTab="all" agents={[]} />);
- expect(screen.getByText("Manage billing")).toBeDefined();
- expect(screen.queryByText(/Reset daily limit/)).toBeNull();
});
it("renders <1% used when percent is >0 but rounds to 0", () => {
@@ -144,6 +188,7 @@ describe("BriefingTabContent — UsageSection", () => {
data: makeUsage({ dailyPercent: 0.4, weeklyPercent: 0 }),
isSuccess: true,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
render(<BriefingTabContent activeTab="all" agents={[]} />);
expect(screen.getByText("<1% used")).toBeDefined();
@@ -154,6 +199,7 @@ describe("BriefingTabContent — UsageSection", () => {
data: undefined,
isSuccess: false,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
for (const tab of ["running", "attention", "completed"] as const) {
@@ -172,6 +218,7 @@ describe("BriefingTabContent — UsageSection", () => {
data: undefined,
isSuccess: false,
});
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
mockUseGetFlag.mockReturnValue(false);
for (const tab of ["listening", "scheduled", "idle"] as const) {
@@ -183,3 +230,177 @@ describe("BriefingTabContent — UsageSection", () => {
}
});
});
+
+describe("BriefingTabContent — CostsBreakdown", () => {
+ it("shows 'No spend this month yet' when total is zero", () => {
+ mockUseGetV2GetCopilotUsage.mockReturnValue({
+ data: undefined,
+ isSuccess: false,
+ });
+ mockUseGetV1UserCostSummary.mockReturnValue(emptyCostSummary());
+ mockUseGetFlag.mockReturnValue(false);
+ render(<BriefingTabContent activeTab="all" agents={[]} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /see costs breakdown/i }),
+ );
+ expect(screen.getByText("No spend this month yet.")).toBeDefined();
+ });
+
+ it("renders headline stats, top runs, and by-agent sections when spend > 0", () => {
+ mockUseGetV2GetCopilotUsage.mockReturnValue({
+ data: undefined,
+ isSuccess: false,
+ });
+ mockUseGetV1UserCostSummary.mockReturnValue({
+ data: {
+ total_cents: 4250,
+ run_count: 10,
+ billable_run_count: 10,
+ failed_cost_cents: 50,
+ by_agent: [
+ { graph_id: "g-1", cost_cents: 3000, run_count: 6 },
+ { graph_id: "g-2", cost_cents: 1250, run_count: 4 },
+ ],
+ top_runs: [
+ {
+ execution_id: "exec-big",
+ graph_id: "g-1",
+ cost_cents: 2500,
+ started_at: new Date().toISOString(),
+ status: "COMPLETED",
+ duration_seconds: 30,
+ node_error_count: 0,
+ },
+ {
+ execution_id: "exec-small",
+ graph_id: "g-2",
+ cost_cents: 250,
+ started_at: new Date().toISOString(),
+ status: "FAILED",
+ duration_seconds: 5,
+ node_error_count: 2,
+ },
+ ],
+ daily: [
+ { date: "2026-05-10", cost_cents: 3000, run_count: 6 },
+ { date: "2026-05-11", cost_cents: 1250, run_count: 4 },
+ ],
+ },
+ isLoading: false,
+ isError: false,
+ });
+ mockUseGetFlag.mockReturnValue(false);
+
+ render(
+ <BriefingTabContent
+ activeTab="all"
+ agents={[
+ makeAgent({ id: "lib-1", graph_id: "g-1", name: "Alpha" }),
+ makeAgent({ id: "lib-2", graph_id: "g-2", name: "Beta" }),
+ ]}
+ />,
+ );
+
+ // Sections are hidden behind the toggle by default
+ expect(screen.queryByText("$42.50")).toBeNull();
+ fireEvent.click(
+ screen.getByRole("button", { name: /see costs breakdown/i }),
+ );
+
+ // Headline stats
+ expect(screen.getByText("$42.50")).toBeDefined();
+ expect(screen.getByText("Most expensive runs")).toBeDefined();
+ expect(screen.getByText("Spend by agent")).toBeDefined();
+
+ // Agent names resolved via graph_id lookup
+ expect(screen.getAllByText("Alpha").length).toBeGreaterThanOrEqual(1);
+ expect(screen.getAllByText("Beta").length).toBeGreaterThanOrEqual(1);
+
+ // Failure indicator on the FAILED run
+ expect(screen.getByText(/2 errors/)).toBeDefined();
+ });
+
+ it("surfaces an inline error when the cost-summary endpoint fails", () => {
+ mockUseGetV2GetCopilotUsage.mockReturnValue({
+ data: undefined,
+ isSuccess: false,
+ });
+ mockUseGetV1UserCostSummary.mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ isError: true,
+ });
+ mockUseGetFlag.mockReturnValue(false);
+
+ render(<BriefingTabContent activeTab="all" agents={[]} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /see costs breakdown/i }),
+ );
+ expect(screen.getByText(/Couldn't load cost breakdown/i)).toBeDefined();
+ });
+
+ it("falls back to short graph_id label when agent isn't in the library", () => {
+ mockUseGetV2GetCopilotUsage.mockReturnValue({
+ data: undefined,
+ isSuccess: false,
+ });
+ mockUseGetV1UserCostSummary.mockReturnValue({
+ data: {
+ total_cents: 500,
+ run_count: 1,
+ billable_run_count: 1,
+ failed_cost_cents: 0,
+ by_agent: [
+ { graph_id: "deadbeef-1234-5678", cost_cents: 500, run_count: 1 },
+ ],
+ top_runs: [],
+ daily: [],
+ },
+ isLoading: false,
+ isError: false,
+ });
+ mockUseGetFlag.mockReturnValue(false);
+
+ render(<BriefingTabContent activeTab="all" agents={[]} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /see costs breakdown/i }),
+ );
+ expect(screen.getByText(/Agent deadbeef/)).toBeDefined();
+ });
+
+ it("computes Avg / run from billable_run_count, not run_count", () => {
+ mockUseGetV2GetCopilotUsage.mockReturnValue({
+ data: undefined,
+ isSuccess: false,
+ });
+ // 6 total runs but only 2 with cost > 0 — avg must be $5.00 (1000/2),
+ // not $1.67 (1000/6) which is what dividing by run_count would yield.
+ mockUseGetV1UserCostSummary.mockReturnValue({
+ data: {
+ total_cents: 1000,
+ run_count: 6,
+ billable_run_count: 2,
+ failed_cost_cents: 0,
+ by_agent: [{ graph_id: "g-1", cost_cents: 1000, run_count: 6 }],
+ top_runs: [],
+ daily: [],
+ },
+ isLoading: false,
+ isError: false,
+ });
+ mockUseGetFlag.mockReturnValue(false);
+
+ render(
+ <BriefingTabContent
+ activeTab="all"
+ agents={[makeAgent({ id: "lib-1", graph_id: "g-1", name: "Alpha" })]}
+ />,
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: /see costs breakdown/i }),
+ );
+
+ expect(screen.getByText("$5.00")).toBeDefined();
+ expect(screen.queryByText("$1.67")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts
index 2b11ec08e7..ad87d76aca 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts
@@ -3,9 +3,11 @@
import {
getGetV1ListAllExecutionsQueryKey,
useGetV1ListAllExecutions,
+ useGetV1UserCostSummary,
} from "@/app/api/__generated__/endpoints/graphs/graphs";
import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";
import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import type { UserExecutionCostSummary } from "@/app/api/__generated__/models/userExecutionCostSummary";
import { okData } from "@/app/api/helpers";
import { useExecutionEvents } from "@/hooks/useExecutionEvents";
import { useQueryClient } from "@tanstack/react-query";
@@ -35,21 +37,6 @@ function isRecentCompletion(
return Date.now() - ts < SEVENTY_TWO_HOURS_MS;
}
-function toTimestamp(value?: string | Date | null): number | null {
- if (!value) return null;
- const ts =
- value instanceof Date ? value.getTime() : new Date(value).getTime();
- return Number.isFinite(ts) ? ts : null;
-}
-
-function startOfCurrentMonth(now: Date = new Date()): number {
- return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1);
-}
-
-function currentDayKey(now: Date = new Date()): number {
- return Math.floor(now.getTime() / 86_400_000);
-}
-
export function useLibraryFleetSummary(
agents: LibraryAgent[],
): FleetSummary | undefined {
@@ -59,12 +46,16 @@ export function useLibraryFleetSummary(
query: { select: okData },
});
- const graphIDs = useMemo(() => agents.map((a) => a.graph_id), [agents]);
+ // Authoritative monthly total comes from the server-side aggregator so it
+ // stays correct above the 250-row /executions cap.
+ const { data: costSummary } = useGetV1UserCostSummary(undefined, {
+ query: {
+ select: (res) => res.data as UserExecutionCostSummary,
+ staleTime: 60_000,
+ },
+ });
- // Recompute when the UTC day rolls over so `monthStart` stays fresh on a
- // long-open tab — read on every render; cheap. React Query refetches keep
- // the memo re-evaluating in practice.
- const dayKey = currentDayKey();
+ const graphIDs = useMemo(() => agents.map((a) => a.graph_id), [agents]);
const handleExecutionUpdate = useCallback(() => {
queryClient.invalidateQueries({
@@ -84,8 +75,6 @@ export function useLibraryFleetSummary(
const agentsWithActiveExecution = new Set<string>();
const agentsWithRecentFailure = new Set<string>();
const agentsWithRecentCompletion = new Set<string>();
- const monthStart = startOfCurrentMonth();
- let monthlySpendCents = 0;
for (const exec of executions) {
if (isActive(exec.status)) {
@@ -97,16 +86,14 @@ export function useLibraryFleetSummary(
if (isRecentCompletion(exec.status, exec.ended_at)) {
agentsWithRecentCompletion.add(exec.graph_id);
}
-
- const startedTs = toTimestamp(exec.started_at);
- if (startedTs !== null && startedTs >= monthStart) {
- const cost = exec.stats?.cost;
- if (typeof cost === "number" && Number.isFinite(cost)) {
- monthlySpendCents += cost;
- }
- }
}
+ // Authoritative server total; renders $0.00 briefly during initial load,
+ // then updates to the real value. A local fallback would mis-bucket
+ // cross-month executions (server buckets by createdAt, the local list
+ // exposes only started_at) and produce a misleading flash.
+ const monthlySpend = costSummary?.total_cents ?? 0;
+
const summary: FleetSummary = {
running: 0,
error: 0,
@@ -114,7 +101,7 @@ export function useLibraryFleetSummary(
listening: 0,
scheduled: 0,
idle: 0,
- monthlySpend: monthlySpendCents,
+ monthlySpend,
};
for (const agent of agents) {
@@ -142,5 +129,5 @@ export function useLibraryFleetSummary(
}
return summary;
- }, [agents, executions, isSuccess, dayKey]);
+ }, [agents, executions, isSuccess, costSummary]);
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 265d5e3921..ed5481db53 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3984,6 +3984,82 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/executions/cost-summary": {
+ "get": {
+ "tags": ["v1", "graphs"],
+ "summary": "User cost summary",
+ "description": "Aggregated cost breakdown for the calling user's graph executions.",
+ "operationId": "getV1User cost summary",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "since",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "description": "Window start (UTC). Defaults to start of current calendar month.",
+ "title": "Since"
+ },
+ "description": "Window start (UTC). Defaults to start of current calendar month."
+ },
+ {
+ "name": "until",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "description": "Window end (UTC). Defaults to now.",
+ "title": "Until"
+ },
+ "description": "Window end (UTC). Defaults to now."
+ },
+ {
+ "name": "top_runs_limit",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 50,
+ "minimum": 1,
+ "description": "Maximum number of top-cost runs to return.",
+ "default": 10,
+ "title": "Top Runs Limit"
+ },
+ "description": "Maximum number of top-cost runs to return."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UserExecutionCostSummary"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/executions/{graph_exec_id}": {
"delete": {
"tags": ["v1", "graphs"],
@@ -18731,6 +18807,16 @@
"title": "UsageWindowPublic",
"description": "Public view of a usage window — only the percentage and reset time.\n\nHides the raw spend and the cap so clients cannot derive per-turn cost\nor reverse-engineer platform margins. ``percent_used`` is capped at 100."
},
+ "UserAgentCostRollup": {
+ "properties": {
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "cost_cents": { "type": "integer", "title": "Cost Cents" },
+ "run_count": { "type": "integer", "title": "Run Count" }
+ },
+ "type": "object",
+ "required": ["graph_id", "cost_cents", "run_count"],
+ "title": "UserAgentCostRollup"
+ },
"UserCostSummary": {
"properties": {
"user_id": {
@@ -18779,6 +18865,56 @@
],
"title": "UserCostSummary"
},
+ "UserDailyCost": {
+ "properties": {
+ "date": { "type": "string", "format": "date", "title": "Date" },
+ "cost_cents": { "type": "integer", "title": "Cost Cents" },
+ "run_count": { "type": "integer", "title": "Run Count" }
+ },
+ "type": "object",
+ "required": ["date", "cost_cents", "run_count"],
+ "title": "UserDailyCost"
+ },
+ "UserExecutionCostSummary": {
+ "properties": {
+ "total_cents": { "type": "integer", "title": "Total Cents" },
+ "run_count": { "type": "integer", "title": "Run Count" },
+ "billable_run_count": {
+ "type": "integer",
+ "title": "Billable Run Count"
+ },
+ "failed_cost_cents": {
+ "type": "integer",
+ "title": "Failed Cost Cents"
+ },
+ "by_agent": {
+ "items": { "$ref": "#/components/schemas/UserAgentCostRollup" },
+ "type": "array",
+ "title": "By Agent"
+ },
+ "top_runs": {
+ "items": { "$ref": "#/components/schemas/UserTopRun" },
+ "type": "array",
+ "title": "Top Runs"
+ },
+ "daily": {
+ "items": { "$ref": "#/components/schemas/UserDailyCost" },
+ "type": "array",
+ "title": "Daily"
+ }
+ },
+ "type": "object",
+ "required": [
+ "total_cents",
+ "run_count",
+ "billable_run_count",
+ "failed_cost_cents",
+ "by_agent",
+ "top_runs",
+ "daily"
+ ],
+ "title": "UserExecutionCostSummary"
+ },
"UserHistoryResponse": {
"properties": {
"history": {
@@ -19043,6 +19179,32 @@
"required": ["user_id", "tier"],
"title": "UserTierResponse"
},
+ "UserTopRun": {
+ "properties": {
+ "execution_id": { "type": "string", "title": "Execution Id" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "cost_cents": { "type": "integer", "title": "Cost Cents" },
+ "started_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Started At"
+ },
+ "status": { "$ref": "#/components/schemas/AgentExecutionStatus" },
+ "duration_seconds": { "type": "number", "title": "Duration Seconds" },
+ "node_error_count": { "type": "integer", "title": "Node Error Count" }
+ },
+ "type": "object",
+ "required": [
+ "execution_id",
+ "graph_id",
+ "cost_cents",
+ "started_at",
+ "status",
+ "duration_seconds",
+ "node_error_count"
+ ],
+ "title": "UserTopRun"
+ },
"UserTransaction": {
"properties": {
"transaction_key": {