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): per-expert spend on home team cards (#14022)

Abhimanyu Yadav070357f82a43
diff --git a/autogpt_platform/backend/backend/api/features/home/agents.py b/autogpt_platform/backend/backend/api/features/home/agents.py
index 4b20245df0..e9eb5e00a4 100644
--- a/autogpt_platform/backend/backend/api/features/home/agents.py
+++ b/autogpt_platform/backend/backend/api/features/home/agents.py
@@ -13,9 +13,10 @@ def compose_agent_statuses(
experts: list[Expert],
running_expert_ids: set[str],
next_run_by_expert: dict[str, datetime],
+ spend_by_expert: dict[str, int],
) -> list[HomeAgentStatus]:
statuses = [
- _agent_status(expert, running_expert_ids, next_run_by_expert)
+ _agent_status(expert, running_expert_ids, next_run_by_expert, spend_by_expert)
for expert in experts
]
return sorted(statuses, key=lambda item: _STATUS_RANK[item.status])
@@ -29,6 +30,7 @@ def compose_team_summary(agents: list[HomeAgentStatus]) -> HomeTeamSummary:
needs_attention=sum(
agent.status in {"paused", "needs_setup", "failed"} for agent in agents
),
+ spend_cents=sum(agent.spend_cents for agent in agents),
)
@@ -36,6 +38,7 @@ def _agent_status(
expert: Expert,
running_expert_ids: set[str],
next_run_by_expert: dict[str, datetime],
+ spend_by_expert: dict[str, int],
) -> HomeAgentStatus:
if expert.id in running_expert_ids:
status, detail = "working", "Working on a task now"
@@ -52,4 +55,5 @@ def _agent_status(
status=status,
detail=detail,
next_run_time=next_run_by_expert.get(expert.id),
+ spend_cents=spend_by_expert.get(expert.id, 0),
)
diff --git a/autogpt_platform/backend/backend/api/features/home/agents_test.py b/autogpt_platform/backend/backend/api/features/home/agents_test.py
index 1ae60cb127..5fd84d6b75 100644
--- a/autogpt_platform/backend/backend/api/features/home/agents_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/agents_test.py
@@ -54,6 +54,7 @@ def test_working_outranks_paused_and_setup() -> None:
],
running_expert_ids={"busy"},
next_run_by_expert={},
+ spend_by_expert={},
)
assert [status.status for status in statuses] == ["working", "ready"]
@@ -69,6 +70,7 @@ def test_status_precedence_walks_down_to_failed() -> None:
],
running_expert_ids=set(),
next_run_by_expert={},
+ spend_by_expert={},
)
assert [status.status for status in statuses] == [
@@ -89,6 +91,7 @@ def test_team_summary_groups_non_ready_states_as_attention() -> None:
],
running_expert_ids={"working"},
next_run_by_expert={},
+ spend_by_expert={},
)
summary = compose_team_summary(statuses)
@@ -99,6 +102,21 @@ def test_team_summary_groups_non_ready_states_as_attention() -> None:
assert summary.needs_attention == 2
+def test_spend_lands_on_the_matching_expert_and_totals_on_the_team() -> None:
+ statuses = compose_agent_statuses(
+ experts=[_expert(expert_id="spender"), _expert(expert_id="idle")],
+ running_expert_ids=set(),
+ next_run_by_expert={},
+ # "stranger" models an archived expert's rollup: it must not leak into
+ # the team total, which has to reconcile with the listed rows.
+ spend_by_expert={"spender": 425, "stranger": 999},
+ )
+
+ spend = {status.expert.id: status.spend_cents for status in statuses}
+ assert spend == {"spender": 425, "idle": 0}
+ assert compose_team_summary(statuses).spend_cents == 425
+
+
def test_next_run_time_comes_from_the_expert_index() -> None:
earliest = datetime(2026, 8, 10, 10, 0, tzinfo=timezone.utc)
@@ -106,6 +124,7 @@ def test_next_run_time_comes_from_the_expert_index() -> None:
experts=[_expert(expert_id="scheduled"), _expert(expert_id="idle")],
running_expert_ids=set(),
next_run_by_expert={"scheduled": earliest},
+ spend_by_expert={},
)
next_runs = {status.expert.id: status.next_run_time for status in statuses}
diff --git a/autogpt_platform/backend/backend/api/features/home/compose.py b/autogpt_platform/backend/backend/api/features/home/compose.py
index f502fc6b08..409a33a8f5 100644
--- a/autogpt_platform/backend/backend/api/features/home/compose.py
+++ b/autogpt_platform/backend/backend/api/features/home/compose.py
@@ -52,6 +52,9 @@ def compose_home_dashboard(
experts=hired,
running_expert_ids=running_expert_ids,
next_run_by_expert=next_runs_by_expert(graph_schedules, expert_by_schedule),
+ spend_by_expert={
+ rollup.expert_id: rollup.cost_cents for rollup in cost_summary.by_expert
+ },
)
return HomeDashboardResponse(
diff --git a/autogpt_platform/backend/backend/api/features/home/compose_test.py b/autogpt_platform/backend/backend/api/features/home/compose_test.py
index d24227d1c2..b87d7b909f 100644
--- a/autogpt_platform/backend/backend/api/features/home/compose_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/compose_test.py
@@ -1,7 +1,10 @@
from datetime import datetime, timezone
from backend.api.features.experts.models import Expert, ExpertWorkflowRef
-from backend.data.execution_cost_summary import UserExecutionCostSummary
+from backend.data.execution_cost_summary import (
+ UserExecutionCostSummary,
+ UserExpertCostRollup,
+)
from .compose import compose_home_dashboard
@@ -41,13 +44,16 @@ def _expert(
)
-def _cost_summary() -> UserExecutionCostSummary:
+def _cost_summary(
+ by_expert: list[UserExpertCostRollup] | None = None,
+) -> UserExecutionCostSummary:
return UserExecutionCostSummary(
total_cents=0,
run_count=0,
billable_run_count=0,
failed_cost_cents=0,
by_agent=[],
+ by_expert=by_expert or [],
top_runs=[],
daily=[],
)
@@ -73,3 +79,28 @@ def test_templates_and_archived_experts_are_left_off_the_dashboard() -> None:
assert [agent.expert.id for agent in dashboard.agents] == ["hired"]
assert dashboard.team.total == 1
assert [item.id for item in dashboard.attention] == ["setup-hired"]
+
+
+def test_expert_spend_reaches_the_agent_rows_and_the_team_total() -> None:
+ dashboard = compose_home_dashboard(
+ now=NOW,
+ experts=[_expert("hired"), _expert("quiet"), _expert("gone", is_archived=True)],
+ executions=[],
+ reviews=[],
+ schedules=[],
+ library_refs=[],
+ cost_summary=_cost_summary(
+ [
+ UserExpertCostRollup(expert_id="hired", cost_cents=730, run_count=4),
+ # Attributed to an expert the dashboard doesn't list, so it is
+ # dropped rather than silently inflating the team total.
+ UserExpertCostRollup(expert_id="gone", cost_cents=500, run_count=2),
+ ]
+ ),
+ credits_balance=100,
+ timezone_name="UTC",
+ )
+
+ spend = {agent.expert.id: agent.spend_cents for agent in dashboard.agents}
+ assert spend == {"hired": 730, "quiet": 0}
+ assert dashboard.team.spend_cents == 730
diff --git a/autogpt_platform/backend/backend/api/features/home/models.py b/autogpt_platform/backend/backend/api/features/home/models.py
index cfe49c76e4..0ec0cc66c8 100644
--- a/autogpt_platform/backend/backend/api/features/home/models.py
+++ b/autogpt_platform/backend/backend/api/features/home/models.py
@@ -82,6 +82,8 @@ class HomeAgentStatus(BaseModel):
status: Literal["ready", "working", "needs_setup", "paused", "failed"]
detail: str
next_run_time: datetime | None = None
+ # Expert-attributed spend over the same 7-day window as `HomeWeekSummary`.
+ spend_cents: int = 0
class HomeTeamSummary(BaseModel):
@@ -89,6 +91,10 @@ class HomeTeamSummary(BaseModel):
ready: int
working: int
needs_attention: int
+ # Sum of `spend_cents` across the listed agents, so the header total and
+ # the rows under it always reconcile. Spend stamped to an archived expert
+ # is therefore excluded, as is unattributed spend.
+ spend_cents: int = 0
class HomeDailyActivity(BaseModel):
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index bf5766a0f9..c6f3343365 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -156,7 +156,12 @@ async def _load_home_source_data(
review_db.get_pending_reviews_for_user(user_id, page=1, page_size=_REVIEW_LIMIT)
)
cost_summary_task = asyncio.create_task(
- get_user_cost_summary(user_id=user_id, since=week_start, until=now)
+ get_user_cost_summary(
+ user_id=user_id,
+ since=week_start,
+ until=now,
+ include_by_expert=True,
+ )
)
schedules_task = asyncio.create_task(_get_schedules(user_id=user_id))
credits_task = asyncio.create_task(
diff --git a/autogpt_platform/backend/backend/data/execution_cost_summary.py b/autogpt_platform/backend/backend/data/execution_cost_summary.py
index 948140c98e..a9d3d0b40a 100644
--- a/autogpt_platform/backend/backend/data/execution_cost_summary.py
+++ b/autogpt_platform/backend/backend/data/execution_cost_summary.py
@@ -15,6 +15,12 @@ class UserAgentCostRollup(BaseModel):
run_count: int
+class UserExpertCostRollup(BaseModel):
+ expert_id: str
+ cost_cents: int
+ run_count: int
+
+
class UserTopRun(BaseModel):
execution_id: str
graph_id: str
@@ -48,6 +54,10 @@ class UserExecutionCostSummary(BaseModel):
# silently skips — dividing by it biases the average downward.
duration_run_count: int = 0
by_agent: list[UserAgentCostRollup]
+ # Only runs carrying an expert stamp; unattributed runs (plain library
+ # runs, Autopilot sessions) have no row here, so this does not sum to
+ # `total_cents`.
+ by_expert: list[UserExpertCostRollup] = []
top_runs: list[UserTopRun]
daily: list[UserDailyCost]
@@ -70,6 +80,7 @@ async def get_user_cost_summary(
since: datetime | None = None,
until: datetime | None = None,
top_runs_limit: int = 10,
+ include_by_expert: bool = False,
) -> UserExecutionCostSummary:
"""Aggregate per-user execution costs from AgentGraphExecution.stats JSON.
@@ -80,6 +91,10 @@ async def get_user_cost_summary(
`@@index([userId, isDeleted, createdAt])` is hit on `AgentGraphExecution`
— bucketing by `startedAt` instead would force a full per-user scan for
heavy users.
+
+ `include_by_expert` is opt-in because the expert rollup is its own query
+ over the same rows: callers that never render per-expert spend would
+ otherwise pay for a scan they throw away.
"""
# 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
@@ -93,9 +108,10 @@ async def get_user_cost_summary(
until = now
params = (user_id, since, until)
- totals, by_agent, top_runs, daily = await asyncio.gather(
+ totals, by_agent, by_expert, top_runs, daily = await asyncio.gather(
_fetch_totals(params),
_fetch_by_agent(params),
+ _fetch_by_expert(params) if include_by_expert else _no_expert_rollup(),
_fetch_top_runs(params, top_runs_limit),
_fetch_daily(params),
)
@@ -110,6 +126,7 @@ async def get_user_cost_summary(
total_duration_seconds=float(totals.get("total_duration_seconds") or 0),
duration_run_count=int(totals.get("duration_run_count") or 0),
by_agent=by_agent,
+ by_expert=by_expert,
top_runs=top_runs,
daily=daily,
)
@@ -167,6 +184,46 @@ async def _fetch_by_agent(
]
+async def _no_expert_rollup() -> list[UserExpertCostRollup]:
+ return []
+
+
+async def _fetch_by_expert(
+ params: tuple[str, datetime, datetime],
+) -> list[UserExpertCostRollup]:
+ """Every expert with spend in the window — deliberately uncapped.
+
+ `by_agent` can afford a top-N cut because it only ever feeds a ranked
+ list, but callers sum this rollup into a headline total. A LIMIT here
+ would silently under-report that total for anyone whose hired roster
+ outgrew the cap; the row count is bounded by the user's own experts.
+
+ This is a separate scan of the same window, not a free rider on the
+ other aggregates — `asyncio.gather` only overlaps its latency. Hence
+ the `include_by_expert` opt-in on `get_user_cost_summary`.
+ """
+ rows = await query_raw_with_schema(
+ "SELECT"
+ ' "expertId" AS expert_id,'
+ " COALESCE(SUM((stats->>'cost')::numeric), 0)::bigint AS cost_cents,"
+ " COUNT(*)::bigint AS run_count"
+ ' FROM {schema_prefix}"AgentGraphExecution"'
+ f" WHERE {_BASE_WHERE}"
+ ' AND "expertId" IS NOT NULL'
+ ' GROUP BY "expertId"'
+ " ORDER BY cost_cents DESC",
+ *params,
+ )
+ return [
+ UserExpertCostRollup(
+ expert_id=r["expert_id"],
+ cost_cents=int(r.get("cost_cents") or 0),
+ run_count=int(r.get("run_count") or 0),
+ )
+ for r in rows
+ ]
+
+
async def _fetch_top_runs(
params: tuple[str, datetime, datetime], limit: int
) -> list[UserTopRun]:
diff --git a/autogpt_platform/backend/backend/data/execution_cost_summary_test.py b/autogpt_platform/backend/backend/data/execution_cost_summary_test.py
index 6e0670ec4f..a755059c19 100644
--- a/autogpt_platform/backend/backend/data/execution_cost_summary_test.py
+++ b/autogpt_platform/backend/backend/data/execution_cost_summary_test.py
@@ -7,7 +7,7 @@ from uuid import uuid4
import pytest
from prisma.enums import AgentExecutionStatus
from prisma.errors import UniqueViolationError
-from prisma.models import AgentGraph, AgentGraphExecution, User
+from prisma.models import AgentGraph, AgentGraphExecution, Expert, User
from backend.data.execution_cost_summary import get_user_cost_summary
from backend.util.json import SafeJson
@@ -45,6 +45,21 @@ async def _create_graph(graph_id: str, user_id: str, name: str = "Test") -> None
pass
+async def _create_expert(expert_id: str, user_id: str) -> None:
+ try:
+ await Expert.prisma().create(
+ data={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "name": f"Expert {expert_id}",
+ "role": "Assistant",
+ "identity": "test",
+ }
+ )
+ except UniqueViolationError:
+ pass
+
+
async def _create_run(
*,
run_id: str,
@@ -57,6 +72,7 @@ async def _create_run(
node_error_count: int = 0,
is_dry_run: bool = False,
created_at: datetime | None = None,
+ expert_id: str | None = None,
) -> None:
# `walltime` is the key the executor actually persists — it comes from
# GraphExecutionStats.model_dump() in update_graph_execution_stats().
@@ -81,13 +97,18 @@ async def _create_run(
"startedAt": started_at,
"endedAt": started_at + timedelta(seconds=duration or 0),
"stats": SafeJson(stats),
+ **({"expertId": expert_id} if expert_id else {}),
}
)
-async def _cleanup(user_id: str, graph_ids: list[str]) -> None:
+async def _cleanup(
+ user_id: str, graph_ids: list[str], expert_ids: list[str] | None = None
+) -> None:
try:
await AgentGraphExecution.prisma().delete_many(where={"userId": user_id})
+ for eid in expert_ids or []:
+ await Expert.prisma().delete_many(where={"id": eid})
for gid in graph_ids:
await AgentGraph.prisma().delete_many(where={"id": gid})
await User.prisma().delete_many(where={"id": user_id})
@@ -105,6 +126,7 @@ async def test_empty_window_returns_zeroed_summary(server: SpinTestServer):
user_id=user_id,
since=now - timedelta(days=1),
until=now,
+ include_by_expert=True,
)
assert summary.total_cents == 0
assert summary.run_count == 0
@@ -116,12 +138,106 @@ async def test_empty_window_returns_zeroed_summary(server: SpinTestServer):
assert summary.total_duration_seconds == 0
assert summary.duration_run_count == 0
assert summary.by_agent == []
+ assert summary.by_expert == []
assert summary.top_runs == []
assert summary.daily == []
finally:
await _cleanup(user_id, [])
[email protected](loop_scope="session")
+async def test_by_expert_rolls_up_stamped_runs_and_drops_unattributed(
+ server: SpinTestServer,
+):
+ user_id = f"cs-expert-{uuid4()}"
+ graph_id = f"cs-g-e-{uuid4()}"
+ expert_a = f"cs-x-a-{uuid4()}"
+ expert_b = f"cs-x-b-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_id, user_id)
+ await _create_expert(expert_a, user_id)
+ await _create_expert(expert_b, user_id)
+ try:
+ now = datetime.now(timezone.utc)
+
+ await _create_run(
+ run_id=f"xa1-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=120,
+ started_at=now - timedelta(hours=3),
+ expert_id=expert_a,
+ )
+ # Zero-cost run on the same expert: it lifts run_count without spend.
+ await _create_run(
+ run_id=f"xa2-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=0,
+ started_at=now - timedelta(hours=2),
+ expert_id=expert_a,
+ )
+ await _create_run(
+ run_id=f"xb1-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=900,
+ started_at=now - timedelta(hours=1),
+ expert_id=expert_b,
+ )
+ # Unstamped run: spend counts toward the user total but gets no bucket.
+ await _create_run(
+ run_id=f"xnone-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=300,
+ started_at=now - timedelta(minutes=30),
+ )
+ # Dry runs stay excluded here too, not just from the headline totals.
+ await _create_run(
+ run_id=f"xdry-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=700,
+ started_at=now - timedelta(minutes=20),
+ is_dry_run=True,
+ expert_id=expert_a,
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=now - timedelta(days=1),
+ until=now + timedelta(minutes=1),
+ include_by_expert=True,
+ )
+
+ assert summary.total_cents == 1320
+ # Highest spend first, and the null bucket is absent entirely.
+ assert [row.expert_id for row in summary.by_expert] == [expert_b, expert_a]
+ by_expert = {row.expert_id: row for row in summary.by_expert}
+ assert by_expert[expert_a].cost_cents == 120
+ assert by_expert[expert_a].run_count == 2
+ assert by_expert[expert_b].cost_cents == 900
+ assert by_expert[expert_b].run_count == 1
+
+ # The rollup is its own scan, so callers that never render per-expert
+ # spend must not pay for it.
+ without_experts = await get_user_cost_summary(
+ user_id=user_id,
+ since=now - timedelta(days=1),
+ until=now + timedelta(minutes=1),
+ )
+ assert without_experts.by_expert == []
+ assert without_experts.total_cents == 1320
+ finally:
+ await _cleanup(user_id, [graph_id], [expert_a, expert_b])
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_aggregates_by_agent_and_top_runs(server: SpinTestServer):
user_id = f"cs-agg-{uuid4()}"
@@ -251,6 +367,46 @@ async def test_aggregates_by_agent_and_top_runs(server: SpinTestServer):
await _cleanup(user_id, [graph_a, graph_b])
[email protected](loop_scope="session")
+async def test_by_expert_covers_a_roster_larger_than_the_by_agent_cap(
+ server: SpinTestServer,
+):
+ # Callers sum `by_expert` into a headline total, so a top-N cut like the
+ # one `by_agent` carries would under-report it. 51 experts clears the
+ # 50-row cap that used to apply here.
+ roster_size = 51
+ user_id = f"cs-roster-{uuid4()}"
+ graph_id = f"cs-g-r-{uuid4()}"
+ await _create_user(user_id)
+ await _create_graph(graph_id, user_id)
+ expert_ids = [f"cs-x-r{index}-{uuid4()}" for index in range(roster_size)]
+ try:
+ now = datetime.now(timezone.utc)
+ for index, expert_id in enumerate(expert_ids):
+ await _create_expert(expert_id, user_id)
+ await _create_run(
+ run_id=f"xr{index}-{uuid4()}",
+ user_id=user_id,
+ graph_id=graph_id,
+ status=AgentExecutionStatus.COMPLETED,
+ cost_cents=index + 1,
+ started_at=now - timedelta(minutes=index + 1),
+ expert_id=expert_id,
+ )
+
+ summary = await get_user_cost_summary(
+ user_id=user_id,
+ since=now - timedelta(days=1),
+ until=now + timedelta(minutes=1),
+ include_by_expert=True,
+ )
+
+ assert len(summary.by_expert) == roster_size
+ assert sum(row.cost_cents for row in summary.by_expert) == summary.total_cents
+ finally:
+ await _cleanup(user_id, [graph_id], expert_ids)
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_excludes_dry_runs_and_outside_window(server: SpinTestServer):
user_id = f"cs-filter-{uuid4()}"
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/main.test.tsx
index bcd25b91f2..0cd2ebf3cf 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/main.test.tsx
@@ -207,6 +207,35 @@ test("renders every Home tile from the aggregate API", async () => {
expect(screen.getByText("Spanish practice plan")).toBeDefined();
});
+test("shows weekly spend per agent and on the team line", async () => {
+ mockDashboard({
+ ...dashboard,
+ team: { ...dashboard.team, spend_cents: 1_250 },
+ agents: [
+ { ...dashboard.agents[0], spend_cents: 900 },
+ {
+ expert: { id: "nova", name: "Nova", role: "Ops", avatar_url: null },
+ status: "ready",
+ detail: "Ready for the next task",
+ spend_cents: 0,
+ },
+ ],
+ });
+
+ render(<HomePage />);
+
+ // Spend sits in its own non-truncating element, so a long detail line can
+ // never clip the figure this tile exists to show.
+ const spend = await screen.findByText("· $9.00 this week");
+ expect(spend.className).toContain("shrink-0");
+ expect(
+ screen.getByText("1 working now · 7 ready · $12.50 this week"),
+ ).toBeDefined();
+ // An expert with no attributed spend keeps its detail line unadorned.
+ expect(screen.getByText("Ready for the next task")).toBeDefined();
+ expect(screen.queryByText("· $0.00 this week")).toBeNull();
+});
+
test("falls back to an Unknown badge for an unrecognised agent status", async () => {
mockDashboard({
...dashboard,
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/AgentTeam.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/AgentTeam.tsx
index 19141d4b7c..3fa054c437 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/AgentTeam.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/AgentTeam.tsx
@@ -7,6 +7,7 @@ import Link from "next/link";
import type { HomeDashboardResponse } from "@/app/api/__generated__/models/homeDashboardResponse";
import { Icon } from "@/components/atoms/Icon/Icon";
import { Text } from "@/components/atoms/Text/Text";
+import { formatWeeklySpend } from "../../helpers";
import { HomeTileEmpty } from "../HomeTileEmpty/HomeTileEmpty";
import { HomeTile } from "../HomeTile/HomeTile";
import { AgentRow } from "./components/AgentRow";
@@ -19,6 +20,11 @@ interface Props {
export function AgentTeam({ dashboard, className }: Props) {
const { team, agents } = dashboard;
const readyCount = team.ready + team.working;
+ const teamSpend = formatWeeklySpend(team.spend_cents);
+ const statusLine =
+ team.working > 0
+ ? `${team.working} working now · ${team.ready} ready`
+ : `${team.ready} ready for work`;
return (
<HomeTile
className={className}
@@ -46,10 +52,8 @@ export function AgentTeam({ dashboard, className }: Props) {
</div>
}
header={
- <Text variant="large" className="text-zinc-600">
- {team.working > 0
- ? `${team.working} working now · ${team.ready} ready`
- : `${team.ready} ready for work`}
+ <Text variant="large" className="text-zinc-600" unmask={!teamSpend}>
+ {teamSpend ? `${statusLine} · ${teamSpend}` : statusLine}
</Text>
}
>
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/components/AgentRow.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/components/AgentRow.tsx
index 25673ce3eb..575ad0fbc5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/components/AgentRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/AgentTeam/components/AgentRow.tsx
@@ -4,6 +4,7 @@ import type { HomeAgentStatus } from "@/app/api/__generated__/models/homeAgentSt
import { Icon } from "@/components/atoms/Icon/Icon";
import { Text } from "@/components/atoms/Text/Text";
import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { formatWeeklySpend } from "../../../helpers";
import { formatUntil } from "../../NowNext/helpers";
import { StatusBadge } from "./StatusBadge";
@@ -12,6 +13,7 @@ interface Props {
}
export function AgentRow({ agent }: Props) {
+ const spend = formatWeeklySpend(agent.spend_cents);
return (
<Link
href={`/team/${agent.expert.id}`}
@@ -28,9 +30,20 @@ export function AgentRow({ agent }: Props) {
</Text>
<StatusBadge status={agent.status} />
</div>
- <Text variant="small" className="truncate text-zinc-500">
- {agent.detail}
- </Text>
+ <div className="flex min-w-0 items-center gap-1 text-zinc-500">
+ <Text variant="small" className="min-w-0 truncate">
+ {agent.detail}
+ </Text>
+ {spend ? (
+ <Text
+ variant="small"
+ className="shrink-0 tabular-nums"
+ unmask={false}
+ >
+ {`· ${spend}`}
+ </Text>
+ ) : null}
+ </div>
</div>
{agent.next_run_time ? (
<Text
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
index cacbc66a5d..a63156616f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
@@ -5,6 +5,7 @@ import {
formatCurrency,
formatDuration,
formatHeaderDate,
+ formatWeeklySpend,
getHomeStatusLine,
getTimeOfDayGreeting,
} from "./helpers";
@@ -66,4 +67,10 @@ describe("formatters", () => {
expect(formatDuration(120)).toBe("2m");
expect(formatCurrency(367)).toBe("$3.67");
});
+
+ it("drops the weekly spend line when nothing was attributed", () => {
+ expect(formatWeeklySpend(1_250)).toBe("$12.50 this week");
+ expect(formatWeeklySpend(0)).toBeNull();
+ expect(formatWeeklySpend(undefined)).toBeNull();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
index 80cc999d30..bf8f1f31fc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
@@ -67,6 +67,13 @@ export function formatDuration(totalSeconds: number): string {
return `${hours}h ${minutes}m`;
}
+// Null rather than "$0.00 this week" so a brand-new or idle expert reads as
+// having no spend line at all instead of an explicit zero.
+export function formatWeeklySpend(cents: number | undefined): string | null {
+ if (!cents || cents <= 0) return null;
+ return `${formatCurrency(cents)} this week`;
+}
+
export function formatCurrency(cents: number): string {
return new Intl.NumberFormat(undefined, {
style: "currency",
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 1cb21ee328..594b7ee794 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -19069,6 +19069,11 @@
{ "type": "null" }
],
"title": "Next Run Time"
+ },
+ "spend_cents": {
+ "type": "integer",
+ "title": "Spend Cents",
+ "default": 0
}
},
"type": "object",
@@ -19295,7 +19300,12 @@
"total": { "type": "integer", "title": "Total" },
"ready": { "type": "integer", "title": "Ready" },
"working": { "type": "integer", "title": "Working" },
- "needs_attention": { "type": "integer", "title": "Needs Attention" }
+ "needs_attention": { "type": "integer", "title": "Needs Attention" },
+ "spend_cents": {
+ "type": "integer",
+ "title": "Spend Cents",
+ "default": 0
+ }
},
"type": "object",
"required": ["total", "ready", "working", "needs_attention"],
@@ -26749,6 +26759,12 @@
"type": "array",
"title": "By Agent"
},
+ "by_expert": {
+ "items": { "$ref": "#/components/schemas/UserExpertCostRollup" },
+ "type": "array",
+ "title": "By Expert",
+ "default": []
+ },
"top_runs": {
"items": { "$ref": "#/components/schemas/UserTopRun" },
"type": "array",
@@ -26772,6 +26788,16 @@
],
"title": "UserExecutionCostSummary"
},
+ "UserExpertCostRollup": {
+ "properties": {
+ "expert_id": { "type": "string", "title": "Expert Id" },
+ "cost_cents": { "type": "integer", "title": "Cost Cents" },
+ "run_count": { "type": "integer", "title": "Run Count" }
+ },
+ "type": "object",
+ "required": ["expert_id", "cost_cents", "run_count"],
+ "title": "UserExpertCostRollup"
+ },
"UserHistoryResponse": {
"properties": {
"history": {