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): add actionable automation credit history (#14361)

Toran Bruce Richardse7d97ea56c01
diff --git a/autogpt_platform/backend/backend/api/features/credit_history_routes_test.py b/autogpt_platform/backend/backend/api/features/credit_history_routes_test.py
new file mode 100644
index 0000000000..22f7fc92fa
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/credit_history_routes_test.py
@@ -0,0 +1,82 @@
+from unittest.mock import AsyncMock
+
+import pytest
+from autogpt_libs.auth import get_request_context, get_user_id, requires_user
+from autogpt_libs.auth.models import RequestContext
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from backend.api.features.v1 import get_credit_history, v1_router
+from backend.api.rest_api import handle_internal_http_error
+from backend.data.credit import UserCreditBase
+from backend.data.model import TransactionHistory
+
+CONTEXT = RequestContext(
+ user_id="user",
+ org_id="org",
+ team_id=None,
+ is_org_owner=True,
+ is_org_admin=False,
+ is_org_billing_manager=False,
+ is_team_admin=False,
+ is_team_billing_manager=False,
+ seat_status="ACTIVE",
+)
+
+
+def client():
+ app = FastAPI()
+ app.include_router(v1_router)
+ app.add_exception_handler(ValueError, handle_internal_http_error(400))
+ app.dependency_overrides[requires_user] = lambda: None
+ app.dependency_overrides[get_user_id] = lambda: "user"
+ app.dependency_overrides[get_request_context] = lambda: CONTEXT
+ return TestClient(app)
+
+
[email protected]("limit", [0, -1, 1001])
+def test_invalid_history_limit_returns_400(client, limit):
+ response = client.get(
+ "/credits/transactions", params={"transaction_count_limit": limit}
+ )
+ assert response.status_code == 400
+ assert "Transaction count limit" in response.json()["detail"]
+ assert response.json()["message"] == "Failed to process GET /credits/transactions"
+
+
+def test_invalid_cursor_returns_400(client, monkeypatch):
+ model = AsyncMock(spec=UserCreditBase)
+ model.get_transaction_history.side_effect = ValueError(
+ "Invalid credit history cursor"
+ )
+ monkeypatch.setattr(
+ "backend.api.features.v1.get_credit_model", AsyncMock(return_value=model)
+ )
+ response = client.get("/credits/transactions", params={"cursor": "invalid"})
+ assert response.status_code == 400
+ assert response.json()["detail"] == "Invalid credit history cursor"
+ assert response.json()["message"] == "Failed to process GET /credits/transactions"
+
+
+async def test_history_route_forwards_cursor_and_org_context(monkeypatch):
+ model = AsyncMock(spec=UserCreditBase)
+ model.get_transaction_history.return_value = TransactionHistory(
+ transactions=[], next_transaction_time=None
+ )
+ get_model = AsyncMock(return_value=model)
+ monkeypatch.setattr("backend.api.features.v1.get_credit_model", get_model)
+ result = await get_credit_history(
+ user_id="user", ctx=CONTEXT, cursor="cursor", transaction_count_limit=50
+ )
+ get_model.assert_awaited_once_with("user", "org")
+ model.get_transaction_history.assert_awaited_once_with(
+ user_id="user",
+ transaction_time_ceiling=None,
+ transaction_count_limit=50,
+ transaction_type=None,
+ cursor="cursor",
+ viewer_organization_id="org",
+ )
+ assert result.transactions == []
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 65edd7bb32..1a0ee98bd6 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -1698,6 +1698,7 @@ async def get_credit_history(
transaction_time: datetime | None = None,
transaction_type: str | None = None,
transaction_count_limit: int = 100,
+ cursor: str | None = None,
) -> TransactionHistory:
if transaction_count_limit < 1 or transaction_count_limit > 1000:
raise ValueError("Transaction count limit must be between 1 and 1000")
@@ -1708,6 +1709,8 @@ async def get_credit_history(
transaction_time_ceiling=transaction_time,
transaction_count_limit=transaction_count_limit,
transaction_type=transaction_type,
+ cursor=cursor,
+ viewer_organization_id=ctx.org_id,
)
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 687ed69c9e..0dc8ae6936 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -2,7 +2,6 @@ import asyncio
import logging
import time
from abc import ABC, abstractmethod
-from collections import defaultdict
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Literal, cast
@@ -25,11 +24,11 @@ from pydantic import BaseModel
from backend.api.features.admin.model import UserHistoryResponse
from backend.data.block_cost_config import BLOCK_COSTS
+from backend.data.credit_history import get_credit_history
from backend.data.db import query_raw_with_schema
from backend.data.includes import MAX_CREDIT_REFUND_REQUESTS_FETCH
from backend.data.model import (
AutoTopUpConfig,
- CreditTransactionItem,
RefundRequest,
TopUpType,
TransactionHistory,
@@ -165,6 +164,8 @@ class UserCreditBase(ABC):
transaction_count_limit: int,
transaction_time_ceiling: datetime | None = None,
transaction_type: str | None = None,
+ cursor: str | None = None,
+ viewer_organization_id: str | None = None,
) -> TransactionHistory:
"""
Get the credit transactions for the user.
@@ -1316,61 +1317,16 @@ class UserCredit(UserCreditBase):
transaction_count_limit: int | None = 100,
transaction_time_ceiling: datetime | None = None,
transaction_type: str | None = None,
+ cursor: str | None = None,
+ viewer_organization_id: str | None = None,
) -> TransactionHistory:
- transactions_filter: CreditTransactionWhereInput = {
- "userId": user_id,
- "isActive": True,
- }
- if transaction_time_ceiling:
- transaction_time_ceiling = transaction_time_ceiling.replace(
- tzinfo=timezone.utc
- )
- transactions_filter["createdAt"] = {"lt": transaction_time_ceiling}
- if transaction_type:
- transactions_filter["type"] = CreditTransactionType[transaction_type]
- transactions = await CreditTransaction.prisma().find_many(
- where=transactions_filter,
- order={"createdAt": "desc"},
- take=transaction_count_limit,
- )
-
- grouped_transactions: dict[str, CreditTransactionItem] = defaultdict(
- lambda: CreditTransactionItem(user_id=user_id)
- )
- tx_time = None
- for t in transactions:
- metadata = (
- UsageTransactionMetadata.model_validate(t.metadata)
- if t.metadata
- else UsageTransactionMetadata()
- )
- tx_time = t.createdAt.replace(tzinfo=timezone.utc)
-
- if t.type == CreditTransactionType.USAGE and metadata.graph_exec_id:
- gt = grouped_transactions[metadata.graph_exec_id]
- gid = metadata.graph_id[:8] if metadata.graph_id else "UNKNOWN"
- gt.description = f"Graph #{gid} Execution"
-
- gt.usage_node_count += 1
- gt.usage_start_time = min(gt.usage_start_time, tx_time)
- gt.usage_execution_id = metadata.graph_exec_id
- gt.usage_graph_id = metadata.graph_id
- else:
- gt = grouped_transactions[t.transactionKey]
- gt.description = f"{t.type} Transaction"
- gt.transaction_key = t.transactionKey
-
- gt.amount += t.amount
- gt.transaction_type = t.type
-
- if tx_time > gt.transaction_time:
- gt.transaction_time = tx_time
-
- return TransactionHistory(
- transactions=list(grouped_transactions.values()),
- next_transaction_time=(
- tx_time if len(transactions) == transaction_count_limit else None
- ),
+ return await get_credit_history(
+ user_id=user_id,
+ transaction_count_limit=transaction_count_limit,
+ transaction_time_ceiling=transaction_time_ceiling,
+ transaction_type=transaction_type,
+ cursor=cursor,
+ viewer_organization_id=viewer_organization_id,
)
async def get_refund_requests(
diff --git a/autogpt_platform/backend/backend/data/credit_history/__init__.py b/autogpt_platform/backend/backend/data/credit_history/__init__.py
new file mode 100644
index 0000000000..2807db1207
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/__init__.py
@@ -0,0 +1,3 @@
+from backend.data.credit_history.service import get_credit_history
+
+__all__ = ["get_credit_history"]
diff --git a/autogpt_platform/backend/backend/data/credit_history/cursor.py b/autogpt_platform/backend/backend/data/credit_history/cursor.py
new file mode 100644
index 0000000000..6eb6d99aec
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/cursor.py
@@ -0,0 +1,63 @@
+import base64
+import hashlib
+from datetime import datetime, timezone
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict
+
+
+class CreditHistoryCursor(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ version: Literal[1] = 1
+ snapshot_at: datetime
+ transaction_time: datetime
+ group_id: str
+ scope: str
+
+
+def cursor_scope(user_id: str, organization_id: str | None, kind: str | None) -> str:
+ ledger = (
+ f"org:{organization_id}" if organization_id is not None else f"user:{user_id}"
+ )
+ return hashlib.sha256(f"{ledger}|{kind or ''}".encode()).hexdigest()
+
+
+def as_utc(value: datetime) -> datetime:
+ return (
+ value.replace(tzinfo=timezone.utc)
+ if value.tzinfo is None
+ else value.astimezone(timezone.utc)
+ )
+
+
+def decode_cursor(cursor: str, scope: str) -> CreditHistoryCursor:
+ try:
+ if len(cursor) > 4096:
+ raise ValueError("Cursor too long")
+ decoded = base64.b64decode(
+ cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
+ )
+ position = CreditHistoryCursor.model_validate_json(decoded)
+ if (
+ position.scope != scope
+ or position.snapshot_at.tzinfo is None
+ or position.transaction_time.tzinfo is None
+ or position.transaction_time > position.snapshot_at
+ or not position.group_id
+ ):
+ raise ValueError("Invalid cursor fields")
+ return position
+ except ValueError as exc:
+ raise ValueError("Invalid credit history cursor") from exc
+
+
+def encode_cursor(position: CreditHistoryCursor) -> str:
+ # Cursors are unsigned, untrusted pagination state. The server derives the
+ # expected scope and query's ledger owner separately from the authorized
+ # request; the scope hash is only a reuse check, not authorization.
+ return (
+ base64.urlsafe_b64encode(position.model_dump_json().encode())
+ .decode()
+ .rstrip("=")
+ )
diff --git a/autogpt_platform/backend/backend/data/credit_history/cursor_test.py b/autogpt_platform/backend/backend/data/credit_history/cursor_test.py
new file mode 100644
index 0000000000..bb3e7e4c13
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/cursor_test.py
@@ -0,0 +1,74 @@
+import base64
+import json
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from backend.data.credit_history.cursor import (
+ CreditHistoryCursor,
+ as_utc,
+ cursor_scope,
+ decode_cursor,
+ encode_cursor,
+)
+
+
+def test_cursor_preserves_snapshot_and_tie_breaker():
+ position = CreditHistoryCursor(
+ snapshot_at=datetime(2026, 9, 5, 12, 0, tzinfo=timezone.utc),
+ transaction_time=datetime(2026, 9, 4, 9, 0, 0, 123000, tzinfo=timezone.utc),
+ group_id="execution:run-2",
+ scope=cursor_scope("user", None, "USAGE"),
+ )
+ assert decode_cursor(encode_cursor(position), position.scope) == position
+
+
+ "user_id,org_id,kind",
+ [("other", None, None), ("user", "org", None), ("user", None, "USAGE")],
+)
+def test_cursor_is_bound_to_wallet_and_filter(user_id, org_id, kind):
+ time = datetime(2026, 9, 5, tzinfo=timezone.utc)
+ position = CreditHistoryCursor(
+ snapshot_at=time,
+ transaction_time=time,
+ group_id="transaction:key",
+ scope=cursor_scope("user", None, None),
+ )
+ with pytest.raises(ValueError, match="Invalid credit history cursor"):
+ decode_cursor(encode_cursor(position), cursor_scope(user_id, org_id, kind))
+
+
[email protected]("cursor", ["", "!!!", "a" * 5000, "e30", "bm90LWpzb24"])
+def test_malformed_cursor(cursor):
+ with pytest.raises(ValueError, match="Invalid credit history cursor"):
+ decode_cursor(cursor, "scope")
+
+
+ "overrides",
+ [
+ {"version": 2},
+ {"snapshot_at": "2026-09-01T00:00:00"},
+ {"transaction_time": "2026-09-10T00:00:00Z"},
+ {"group_id": ""},
+ {"extra": "unexpected"},
+ ],
+)
+def test_cursor_rejects_invalid_fields(overrides):
+ fields = {
+ "version": 1,
+ "snapshot_at": "2026-09-05T00:00:00Z",
+ "transaction_time": "2026-09-04T00:00:00Z",
+ "group_id": "execution:run",
+ "scope": "scope",
+ **overrides,
+ }
+ encoded = base64.urlsafe_b64encode(json.dumps(fields).encode()).decode()
+ with pytest.raises(ValueError, match="Invalid credit history cursor"):
+ decode_cursor(encoded, "scope")
+
+
+def test_timezone_conversion_preserves_instant():
+ paris = datetime(2026, 9, 5, 12, 0, tzinfo=timezone(timedelta(hours=2)))
+ assert as_utc(paris) == datetime(2026, 9, 5, 10, 0, tzinfo=timezone.utc)
diff --git a/autogpt_platform/backend/backend/data/credit_history/enrichment.py b/autogpt_platform/backend/backend/data/credit_history/enrichment.py
new file mode 100644
index 0000000000..4442d42ebd
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/enrichment.py
@@ -0,0 +1,337 @@
+import asyncio
+from typing import cast
+
+from prisma.enums import SubmissionStatus
+from prisma.models import (
+ AgentGraph,
+ AgentGraphExecution,
+ ChatSession,
+ LibraryAgent,
+ StoreListingVersion,
+)
+from prisma.types import (
+ AgentGraphExecutionWhereInput,
+ AgentGraphWhereInput,
+ ChatSessionWhereInput,
+)
+from pydantic import BaseModel
+
+from backend.copilot.constants import COPILOT_SESSION_PREFIX
+from backend.data.model import CreditHistoryRelatedExecution, CreditTransactionItem
+from backend.data.tenancy import get_user_team_ids, visibility_filter
+
+
+class _AgentRef(BaseModel):
+ name: str | None = None
+ library_agent_id: str | None = None
+ execution_available: bool = False
+
+
+async def enrich_credit_history(
+ items: list[CreditTransactionItem],
+ user_id: str,
+ organization_id: str | None = None,
+) -> list[CreditTransactionItem]:
+ if not any(item.usage_execution_id or item.usage_graph_id for item in items):
+ return items
+ team_ids = (
+ await get_user_team_ids(user_id, organization_id) if organization_id else []
+ )
+ scope = visibility_filter(user_id, organization_id, team_ids)
+ execution_data, sessions = await asyncio.gather(
+ _load_executions(items, user_id, cast(AgentGraphExecutionWhereInput, scope)),
+ _load_sessions(items, user_id, organization_id),
+ )
+ executions, child_counts = execution_data
+ refs, fallback = await _load_agent_refs(
+ items, executions, user_id, cast(AgentGraphWhereInput, scope)
+ )
+ execution_map = {execution.id: execution for execution in executions}
+ return [
+ _enrich_item(item, execution_map, refs, fallback, sessions, child_counts)
+ for item in items
+ ]
+
+
+async def _load_executions(
+ items: list[CreditTransactionItem],
+ user_id: str,
+ scope: AgentGraphExecutionWhereInput,
+) -> tuple[list[AgentGraphExecution], dict[str, int]]:
+ ids = sorted(
+ {
+ item.usage_execution_id
+ for item in items
+ if item.usage_execution_id
+ and not item.usage_execution_id.startswith(COPILOT_SESSION_PREFIX)
+ }
+ )
+ if not ids:
+ return [], {}
+ # Match execution detail's expert guard as well as its org/team predicate.
+ access: AgentGraphExecutionWhereInput = {
+ "isDeleted": False,
+ "AND": [scope, {"OR": [{"expertId": None}, {"userId": user_id}]}],
+ }
+ executions = await AgentGraphExecution.prisma().find_many(
+ where={**access, "id": {"in": ids}},
+ )
+ if not executions:
+ return [], {}
+ return await _load_related_executions(executions, access)
+
+
+async def _load_related_executions(
+ executions: list[AgentGraphExecution], access: AgentGraphExecutionWhereInput
+) -> tuple[list[AgentGraphExecution], dict[str, int]]:
+ parents = sorted(
+ {e.parentGraphExecutionId for e in executions if e.parentGraphExecutionId}
+ )
+ parent_rows = (
+ await AgentGraphExecution.prisma().find_many(
+ where={**access, "id": {"in": parents}}
+ )
+ if parents
+ else []
+ )
+ child_where: AgentGraphExecutionWhereInput = {
+ **access,
+ "parentGraphExecutionId": {"in": [e.id for e in executions]},
+ }
+ children, counts = await asyncio.gather(
+ AgentGraphExecution.prisma().find_many(
+ where=child_where,
+ take=100,
+ order=[{"createdAt": "asc"}, {"id": "asc"}],
+ ),
+ AgentGraphExecution.prisma().group_by(
+ by=["parentGraphExecutionId"],
+ where=child_where,
+ count=True,
+ ),
+ )
+ records = {e.id: e for e in [*executions, *parent_rows, *children]}
+ child_counts = {
+ parent_id: int((row.get("_count") or {}).get("_all") or 0)
+ for row in counts
+ if (parent_id := row.get("parentGraphExecutionId"))
+ }
+ return list(records.values()), child_counts
+
+
+async def _load_sessions(
+ items: list[CreditTransactionItem], user_id: str, organization_id: str | None
+) -> dict[str, ChatSession]:
+ ids = sorted(
+ {
+ item.usage_execution_id.removeprefix(COPILOT_SESSION_PREFIX)
+ for item in items
+ if item.usage_execution_id
+ and item.usage_execution_id.startswith(COPILOT_SESSION_PREFIX)
+ }
+ )
+ if not ids:
+ return {}
+ where: ChatSessionWhereInput = {"id": {"in": ids}, "userId": user_id}
+ if organization_id:
+ # Match the chat detail endpoint: expert sessions remain owner-accessible.
+ where["AND"] = [
+ {
+ "OR": [
+ {"organizationId": organization_id},
+ {"organizationId": None},
+ {"expertId": {"not": None}},
+ ]
+ }
+ ]
+ sessions = await ChatSession.prisma().find_many(where=where)
+ return {session.id: session for session in sessions}
+
+
+async def _load_agent_refs(
+ items: list[CreditTransactionItem],
+ executions: list[AgentGraphExecution],
+ user_id: str,
+ scope: AgentGraphWhereInput,
+) -> tuple[dict[tuple[str, int], _AgentRef], dict[str, _AgentRef]]:
+ graph_ids = sorted(
+ {e.agentGraphId for e in executions}
+ | {
+ item.usage_graph_id
+ for item in items
+ if item.usage_graph_id
+ and not (item.usage_execution_id or "").startswith(COPILOT_SESSION_PREFIX)
+ }
+ )
+ if not graph_ids:
+ return {}, {}
+ libraries = await LibraryAgent.prisma().find_many(
+ where={
+ "userId": user_id,
+ "agentGraphId": {"in": graph_ids},
+ "isDeleted": False,
+ },
+ include={"AgentGraph": True},
+ order=[{"agentGraphVersion": "asc"}, {"id": "asc"}],
+ )
+ libraries = [library for library in libraries if library.AgentGraph]
+ graphs = await _load_accessible_graphs(executions, libraries, scope)
+ current = {library.agentGraphId: library for library in libraries}
+ exact = {
+ (library.agentGraphId, library.agentGraphVersion): library
+ for library in libraries
+ }
+ fallback = {
+ graph_id: _library_ref(library) for graph_id, library in current.items()
+ }
+ return {
+ (execution.agentGraphId, execution.agentGraphVersion): _execution_ref(
+ execution, graphs, exact, current
+ )
+ for execution in executions
+ }, fallback
+
+
+async def _load_accessible_graphs(
+ executions: list[AgentGraphExecution],
+ libraries: list[LibraryAgent],
+ scope: AgentGraphWhereInput,
+) -> dict[tuple[str, int], AgentGraph]:
+ if not executions:
+ return {}
+ versions = sorted({(e.agentGraphId, e.agentGraphVersion) for e in executions})
+ graphs, published = await asyncio.gather(
+ AgentGraph.prisma().find_many(
+ where={
+ "AND": [
+ scope,
+ {
+ "OR": [
+ {"id": graph_id, "version": version}
+ for graph_id, version in versions
+ ]
+ },
+ ]
+ }
+ ),
+ StoreListingVersion.prisma().find_many(
+ where={
+ "submissionStatus": SubmissionStatus.APPROVED,
+ "isDeleted": False,
+ "OR": [
+ {"agentGraphId": graph_id, "agentGraphVersion": version}
+ for graph_id, version in versions
+ ],
+ },
+ include={"AgentGraph": True},
+ ),
+ )
+ accessible = [
+ *graphs,
+ *[listing.AgentGraph for listing in published if listing.AgentGraph],
+ *[
+ library.AgentGraph
+ for library in libraries
+ if not library.isArchived and library.AgentGraph
+ ],
+ ]
+ return {(graph.id, graph.version): graph for graph in accessible}
+
+
+def _library_ref(library: LibraryAgent) -> _AgentRef:
+ name = library.name
+ if name is None and library.AgentGraph:
+ name = library.AgentGraph.name
+ return _AgentRef(name=name or None, library_agent_id=library.id)
+
+
+def _execution_ref(
+ execution: AgentGraphExecution,
+ graphs: dict[tuple[str, int], AgentGraph],
+ exact: dict[tuple[str, int], LibraryAgent],
+ current: dict[str, LibraryAgent],
+) -> _AgentRef:
+ key = (execution.agentGraphId, execution.agentGraphVersion)
+ library = exact.get(key)
+ graph = graphs.get(key)
+ destination = library or current.get(execution.agentGraphId)
+ name = (
+ _library_ref(destination).name
+ if destination
+ else (graph.name if graph else None)
+ )
+ return _AgentRef(
+ name=name or None,
+ library_agent_id=destination.id if destination else None,
+ execution_available=graph is not None,
+ )
+
+
+def _enrich_item(
+ original: CreditTransactionItem,
+ executions: dict[str, AgentGraphExecution],
+ refs: dict[tuple[str, int], _AgentRef],
+ fallback: dict[str, _AgentRef],
+ sessions: dict[str, ChatSession],
+ child_counts: dict[str, int],
+) -> CreditTransactionItem:
+ item = original.model_copy(deep=True)
+ execution_id = item.usage_execution_id or ""
+ if execution_id.startswith(COPILOT_SESSION_PREFIX):
+ session = sessions.get(execution_id.removeprefix(COPILOT_SESSION_PREFIX))
+ item.conversation_id = session.id if session else None
+ item.conversation_title = session.title if session else None
+ return item
+ execution = executions.get(execution_id)
+ ref = (
+ refs.get((execution.agentGraphId, execution.agentGraphVersion))
+ if execution
+ else fallback.get(item.usage_graph_id or "")
+ )
+ if ref:
+ item.agent_name = ref.name
+ item.library_agent_id = ref.library_agent_id
+ if not execution or not ref:
+ return item
+ item.execution_available = ref.execution_available
+ item.execution_graph_version = execution.agentGraphVersion
+ item.execution_status = execution.executionStatus
+ item.execution_started_at = execution.startedAt
+ _add_related(item, execution, executions, refs)
+ item.related_executions_has_more = len(item.related_executions) < child_counts.get(
+ execution.id, 0
+ )
+ return item
+
+
+def _related_ref(
+ execution: AgentGraphExecution, refs: dict[tuple[str, int], _AgentRef]
+) -> CreditHistoryRelatedExecution:
+ ref = refs.get((execution.agentGraphId, execution.agentGraphVersion), _AgentRef())
+ return CreditHistoryRelatedExecution(
+ execution_id=execution.id,
+ agent_name=ref.name,
+ library_agent_id=ref.library_agent_id,
+ execution_available=ref.execution_available,
+ )
+
+
+def _add_related(
+ item: CreditTransactionItem,
+ execution: AgentGraphExecution,
+ executions: dict[str, AgentGraphExecution],
+ refs: dict[tuple[str, int], _AgentRef],
+) -> None:
+ parent = executions.get(execution.parentGraphExecutionId or "")
+ if parent:
+ related = _related_ref(parent, refs)
+ item.parent_execution_id = related.execution_id
+ item.parent_agent_name = related.agent_name
+ item.parent_library_agent_id = (
+ related.library_agent_id if related.execution_available else None
+ )
+ item.related_executions = [
+ _related_ref(child, refs)
+ for child in executions.values()
+ if child.parentGraphExecutionId == execution.id
+ ]
diff --git a/autogpt_platform/backend/backend/data/credit_history/enrichment_test.py b/autogpt_platform/backend/backend/data/credit_history/enrichment_test.py
new file mode 100644
index 0000000000..8be2837709
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/enrichment_test.py
@@ -0,0 +1,308 @@
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from prisma.enums import AgentExecutionStatus, ResourceVisibility
+from prisma.models import (
+ AgentGraph,
+ AgentGraphExecution,
+ ChatSession,
+ LibraryAgent,
+ StoreListingVersion,
+)
+
+from backend.data.credit_history import enrichment as history
+from backend.data.model import CreditTransactionItem
+
+
+def _graph(graph_id="graph", version=2, name="Original agent"):
+ graph = MagicMock(spec=AgentGraph, id=graph_id, version=version)
+ graph.name = name
+ return graph
+
+
+def _execution(execution_id="run", graph_id="graph", parent=None):
+ return AgentGraphExecution(
+ id=execution_id,
+ createdAt=datetime(2026, 9, 5, 9, tzinfo=timezone.utc),
+ userId="user",
+ isDeleted=False,
+ isShared=False,
+ visibility=ResourceVisibility.PRIVATE,
+ agentGraphId=graph_id,
+ agentGraphVersion=2,
+ parentGraphExecutionId=parent,
+ executionStatus=AgentExecutionStatus.COMPLETED,
+ startedAt=datetime(2026, 9, 5, 9, tzinfo=timezone.utc),
+ )
+
+
+def _library(graph=None, *, title=None, archived=False, library_id="library"):
+ graph = graph or _graph()
+ library = MagicMock(
+ spec=LibraryAgent,
+ id=library_id,
+ userId="user",
+ agentGraphId=graph.id,
+ agentGraphVersion=graph.version,
+ AgentGraph=graph,
+ isArchived=archived,
+ isDeleted=False,
+ )
+ library.name = title
+ return library
+
+
+def _item(execution_id="run", graph_id="graph"):
+ return CreditTransactionItem(
+ user_id="user",
+ usage_graph_id=graph_id,
+ usage_execution_id=execution_id,
+ amount=-12,
+ )
+
+
+def _database(
+ mocker, *, executions=(), related=(), libraries=(), graphs=(), sessions=()
+):
+ actions = {}
+ for name, rows in {
+ "AgentGraphExecution": executions,
+ "LibraryAgent": libraries,
+ "AgentGraph": graphs,
+ "StoreListingVersion": (),
+ "ChatSession": sessions,
+ }.items():
+ action = MagicMock()
+ action.find_many = AsyncMock(return_value=list(rows))
+ actions[name] = action
+ mocker.patch(f"{history.__name__}.{name}.prisma", return_value=action)
+ actions["AgentGraphExecution"].find_many.side_effect = [
+ list(executions),
+ list(related),
+ list(related),
+ ]
+ parent_ids = {
+ run.parentGraphExecutionId for run in related if run.parentGraphExecutionId
+ }
+ actions["AgentGraphExecution"].group_by = AsyncMock(
+ return_value=[
+ {
+ "parentGraphExecutionId": parent_id,
+ "_count": {
+ "_all": sum(
+ run.parentGraphExecutionId == parent_id for run in related
+ )
+ },
+ }
+ for parent_id in parent_ids
+ ]
+ )
+ mocker.patch.object(history, "get_user_team_ids", AsyncMock(return_value=["team"]))
+ return actions
+
+
+async def test_exact_run_version_and_familiar_name_survive_library_update(mocker):
+ old_graph = _graph()
+ current = _library(_graph(version=3, name="New name"))
+ _database(
+ mocker, executions=[_execution()], libraries=[current], graphs=[old_graph]
+ )
+ original = _item()
+
+ item = (await history.enrich_credit_history([original], "user"))[0]
+
+ assert item.agent_name == "New name"
+ assert item.library_agent_id == "library"
+ assert item.execution_graph_version == 2
+ assert item.execution_available is True
+ assert item.execution_status == "COMPLETED"
+ assert item.execution_started_at == _execution().startedAt
+ assert item.amount == original.amount
+ assert original.agent_name is None
+
+
+async def test_marketplace_snapshot_takes_precedence_over_graph_name(mocker):
+ _database(
+ mocker,
+ executions=[_execution()],
+ libraries=[_library(title="Installed title")],
+ )
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Installed title"
+ assert item.execution_available is True
+
+
+async def test_exact_library_snapshot_preferred_when_multiple_versions_exist(mocker):
+ _database(
+ mocker,
+ executions=[_execution()],
+ libraries=[
+ _library(title="Installed title", library_id="old-library"),
+ _library(_graph(version=3), title="Current title"),
+ ],
+ )
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Installed title"
+ assert item.library_agent_id == "old-library"
+ assert item.execution_graph_version == 2
+
+
+async def test_archived_library_is_linkable_but_does_not_grant_run_access(mocker):
+ _database(mocker, executions=[_execution()], libraries=[_library(archived=True)])
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Original agent"
+ assert item.library_agent_id == "library"
+ assert item.execution_available is False
+
+
+async def test_deleted_execution_keeps_safe_current_library_name(mocker):
+ _database(mocker, libraries=[_library(title="Known agent")])
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Known agent"
+ assert item.library_agent_id == "library"
+ assert item.execution_available is False
+ assert item.execution_status is None
+ assert item.execution_graph_version is None
+
+
+async def test_deleted_library_never_gets_replacement_graph_uuid_link(mocker):
+ _database(mocker, executions=[_execution()], graphs=[_graph()])
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Original agent"
+ assert item.library_agent_id is None
+ assert item.execution_available is True
+
+
+async def test_public_nested_agent_can_be_named_without_library_entry(mocker):
+ actions = _database(mocker, executions=[_execution()])
+ actions["StoreListingVersion"].find_many.return_value = [
+ MagicMock(spec=StoreListingVersion, AgentGraph=_graph())
+ ]
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert item.agent_name == "Original agent"
+ assert item.execution_available is True
+ assert item.library_agent_id is None
+ where = actions["StoreListingVersion"].find_many.call_args.kwargs["where"]
+ assert where["submissionStatus"] == "APPROVED"
+ assert where["isDeleted"] is False
+ assert where["OR"] == [{"agentGraphId": "graph", "agentGraphVersion": 2}]
+
+
+async def test_org_billing_does_not_grant_private_names_or_links(mocker):
+ actions = _database(mocker)
+ item = (await history.enrich_credit_history([_item()], "user", "org"))[0]
+ assert item.agent_name is None
+ assert item.library_agent_id is None
+ assert item.execution_available is False
+ where = actions["AgentGraphExecution"].find_many.call_args_list[0].kwargs["where"]
+ assert where["isDeleted"] is False
+ assert {"OR": [{"expertId": None}, {"userId": "user"}]} in where["AND"]
+ assert (
+ actions["LibraryAgent"].find_many.call_args.kwargs["where"]["userId"] == "user"
+ )
+ assert (
+ actions["LibraryAgent"].find_many.call_args.kwargs["where"]["isDeleted"]
+ is False
+ )
+
+
+async def test_nested_runs_have_relationships_without_rolling_up_costs(mocker):
+ parent = _execution()
+ child = _execution("child", "child-graph", "run")
+ _database(
+ mocker,
+ executions=[parent, child],
+ related=[parent, child],
+ graphs=[_graph(), _graph("child-graph", name="Research helper")],
+ libraries=[_library()],
+ )
+ parent_item, child_item = await history.enrich_credit_history(
+ [_item(), _item("child", "child-graph")], "user"
+ )
+ assert parent_item.amount == child_item.amount == -12
+ assert child_item.parent_execution_id == "run"
+ assert child_item.parent_agent_name == "Original agent"
+ assert child_item.parent_library_agent_id == "library"
+ assert len(parent_item.related_executions) == 1
+ related = parent_item.related_executions[0]
+ assert related.execution_id == "child"
+ assert related.agent_name == "Research helper"
+ assert related.library_agent_id is None
+ assert related.amount is None
+
+
+async def test_copilot_links_only_existing_owned_conversations(mocker):
+ session = MagicMock(spec=ChatSession, id="chat", title="Research leads")
+ actions = _database(mocker, sessions=[session])
+ existing, unavailable = await history.enrich_credit_history(
+ [_item("copilot-session-chat"), _item("copilot-session-missing")], "user", "org"
+ )
+ assert existing.conversation_id == "chat"
+ assert existing.conversation_title == "Research leads"
+ assert existing.execution_available is False
+ assert unavailable.conversation_id is None
+ assert unavailable.conversation_title is None
+ where = actions["ChatSession"].find_many.call_args.kwargs["where"]
+ assert where["userId"] == "user"
+ assert where["id"]["in"] == ["chat", "missing"]
+ assert where["AND"] == [
+ {
+ "OR": [
+ {"organizationId": "org"},
+ {"organizationId": None},
+ {"expertId": {"not": None}},
+ ]
+ }
+ ]
+
+
+async def test_nonusage_entries_do_not_trigger_metadata_queries(mocker):
+ actions = _database(mocker)
+ items = [
+ CreditTransactionItem(user_id="user", description="Credits added", amount=500)
+ ]
+ assert await history.enrich_credit_history(items, "user") == items
+ for action in actions.values():
+ action.find_many.assert_not_called()
+
+
+async def test_metadata_queries_are_batched_for_repeated_agent_runs(mocker):
+ runs = [_execution(f"run-{number}") for number in range(20)]
+ actions = _database(mocker, executions=runs, libraries=[_library()])
+ items = await history.enrich_credit_history([_item(run.id) for run in runs], "user")
+ assert len(items) == 20
+ assert all(item.agent_name == "Original agent" for item in items)
+ assert actions["AgentGraphExecution"].find_many.await_count == 2
+ assert actions["LibraryAgent"].find_many.await_count == 1
+ assert actions["AgentGraph"].find_many.await_count == 1
+ assert actions["StoreListingVersion"].find_many.await_count == 1
+ actions["ChatSession"].find_many.assert_not_awaited()
+
+
+async def test_many_children_are_bounded_and_reported_as_incomplete(mocker):
+ children = [_execution(f"child-{index}", "graph", "run") for index in range(100)]
+ actions = _database(
+ mocker, executions=[_execution()], related=children, graphs=[_graph()]
+ )
+ actions["AgentGraphExecution"].group_by.return_value = [
+ {"parentGraphExecutionId": "run", "_count": {"_all": 101}}
+ ]
+ item = (await history.enrich_credit_history([_item()], "user"))[0]
+ assert len(item.related_executions) == 100
+ assert item.related_executions_has_more is True
+ assert item.amount == -12
+ assert actions["AgentGraphExecution"].find_many.call_args.kwargs["take"] == 100
diff --git a/autogpt_platform/backend/backend/data/credit_history/history_test.py b/autogpt_platform/backend/backend/data/credit_history/history_test.py
new file mode 100644
index 0000000000..e9cda4a877
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/history_test.py
@@ -0,0 +1,232 @@
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock
+from uuid import uuid4
+
+import pytest
+import pytest_asyncio
+from prisma.enums import CreditTransactionType
+from prisma.models import CreditTransaction, Organization, OrgCreditTransaction, User
+
+from backend.data.credit_history import get_credit_history
+from backend.data.credit_history.queries import credit_history_query
+from backend.data.db import get_database_schema, prisma
+from backend.util.json import SafeJson
+
+
+@pytest_asyncio.fixture(loop_scope="session")
+async def history_wallet(server, monkeypatch):
+ user_id = str(uuid4())
+ await User.prisma().create(
+ data={"id": user_id, "email": f"history-{user_id}@example.com"}
+ )
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.enrich_credit_history",
+ AsyncMock(side_effect=lambda items, **kwargs: items),
+ )
+ yield user_id
+ await CreditTransaction.prisma().delete_many(where={"userId": user_id})
+ await User.prisma().delete(where={"id": user_id})
+
+
+async def add_charge(
+ user_id: str,
+ key: str,
+ amount: int,
+ time: datetime,
+ execution_id: str | None = "run-1",
+ adjustment: bool = False,
+ fee: bool = False,
+):
+ metadata = {
+ "graph_exec_id": execution_id,
+ "graph_id": "graph-1",
+ "node_exec_id": None if fee else "node-1",
+ "block": "AITextGeneratorBlock",
+ "input": {"secret": "never-return-this"},
+ }
+ if adjustment:
+ metadata["input"]["reconciled_delta"] = -amount
+ if fee:
+ metadata["input"]["charge"] = "Execution Cost"
+ return await CreditTransaction.prisma().create(
+ data={
+ "userId": user_id,
+ "transactionKey": key,
+ "createdAt": time,
+ "amount": amount,
+ "type": CreditTransactionType.USAGE,
+ "metadata": SafeJson(metadata),
+ }
+ )
+
+
[email protected](loop_scope="session")
+async def test_complete_execution_before_pagination(history_wallet):
+ now = datetime.now(timezone.utc) - timedelta(minutes=5)
+ await add_charge(history_wallet, "estimate", -100, now)
+ await add_charge(
+ history_wallet, "other-run", -20, now + timedelta(seconds=1), "run-2"
+ )
+ await add_charge(
+ history_wallet, "refund", 40, now + timedelta(seconds=2), adjustment=True
+ )
+ await add_charge(history_wallet, "fee", -1, now + timedelta(seconds=3), fee=True)
+
+ page = await get_credit_history(history_wallet, transaction_count_limit=1)
+
+ assert len(page.transactions) == 1
+ row = page.transactions[0]
+ assert row.amount == -61
+ assert row.usage_charge_amount == -100
+ assert row.usage_fee_amount == -1
+ assert row.usage_adjustment_amount == 40
+ assert row.usage_node_count == 1
+ assert row.charges_total_count == 3
+ assert "never-return-this" not in row.model_dump_json()
+ assert page.next_cursor
+ next_page = await get_credit_history(
+ history_wallet, transaction_count_limit=1, cursor=page.next_cursor
+ )
+ assert [row.usage_execution_id for row in next_page.transactions] == ["run-2"]
+ assert next_page.next_cursor is None
+
+
[email protected](loop_scope="session")
+async def test_cursor_ties_and_snapshot_ignore_later_adjustments(history_wallet):
+ time = datetime.now(timezone.utc) - timedelta(minutes=5)
+ for execution_id in ["run-a", "run-b", "run-c"]:
+ await add_charge(history_wallet, execution_id, -10, time, execution_id)
+ first = await get_credit_history(history_wallet, transaction_count_limit=1)
+ assert first.next_cursor
+ await add_charge(
+ history_wallet, "later", 5, datetime.now(timezone.utc), "run-a", adjustment=True
+ )
+ second = await get_credit_history(
+ history_wallet, transaction_count_limit=1, cursor=first.next_cursor
+ )
+ assert second.next_cursor
+ third = await get_credit_history(
+ history_wallet, transaction_count_limit=1, cursor=second.next_cursor
+ )
+ all_rows = first.transactions + second.transactions + third.transactions
+ assert {row.usage_execution_id for row in all_rows} == {"run-a", "run-b", "run-c"}
+ assert all(row.amount == -10 for row in all_rows)
+ assert len({row.id for row in all_rows}) == 3
+
+
[email protected](loop_scope="session")
+async def test_bounded_details_keep_complete_total(history_wallet):
+ time = datetime.now(timezone.utc) - timedelta(minutes=5)
+ for index in range(105):
+ await add_charge(history_wallet, f"charge-{index}", -1, time)
+ row = (await get_credit_history(history_wallet)).transactions[0]
+ assert row.amount == -105
+ assert row.charges_total_count == 105
+ assert row.charges_truncated
+ assert len(row.charges) == 100
+
+
[email protected](loop_scope="session")
+async def test_copilot_and_orphan_usage_are_distinct(history_wallet):
+ time = datetime.now(timezone.utc) - timedelta(minutes=5)
+ await add_charge(history_wallet, "tool", -10, time, "copilot-session-chat-1")
+ await add_charge(history_wallet, "orphan-1", -4, time, None)
+ await add_charge(history_wallet, "orphan-2", -5, time, None)
+ page = await get_credit_history(history_wallet)
+ assert len(page.transactions) == 3
+ assert sorted(row.activity_type for row in page.transactions) == [
+ "block_usage",
+ "block_usage",
+ "copilot_tools",
+ ]
+
+
[email protected](loop_scope="session")
+async def test_invalid_or_cross_wallet_cursor_is_rejected(history_wallet):
+ time = datetime.now(timezone.utc) - timedelta(minutes=5)
+ for execution_id in ["run-a", "run-b"]:
+ await add_charge(history_wallet, execution_id, -1, time, execution_id)
+ page = await get_credit_history(history_wallet, transaction_count_limit=1)
+ with pytest.raises(ValueError, match="cursor"):
+ await get_credit_history("another-wallet", cursor=page.next_cursor)
+ with pytest.raises(ValueError, match="cursor"):
+ await get_credit_history(history_wallet, cursor="not-a-cursor")
+
+
[email protected](loop_scope="session")
+async def test_timestamp_comparisons_ignore_database_session_timezone(history_wallet):
+ time = datetime(2026, 9, 5, 10, tzinfo=timezone.utc)
+ await add_charge(history_wallet, "timezone-charge", -10, time)
+ schema = get_database_schema()
+ query = credit_history_query(organization=False).format(
+ schema_prefix=f'"{schema}".' if schema != "public" else "",
+ schema=schema,
+ )
+ before = time - timedelta(hours=1)
+ after = time + timedelta(hours=1)
+ async with prisma.tx() as tx:
+ await tx.execute_raw("SET LOCAL TIME ZONE 'Europe/Paris'")
+ assert (
+ await tx.query_raw(query, history_wallet, before, None, None, None, None, 2)
+ == []
+ )
+ rows = await tx.query_raw(
+ query, history_wallet, after, None, None, None, None, 2
+ )
+ assert len(rows) == 1
+ assert (
+ await tx.query_raw(
+ query, history_wallet, after, None, before, "execution:run-1", None, 2
+ )
+ == []
+ )
+ assert (
+ await tx.query_raw(
+ query, history_wallet, after, None, None, None, before, 2
+ )
+ == []
+ )
+
+
[email protected](loop_scope="session")
+async def test_org_aggregation_preserves_amounts_and_wallet_boundary(history_wallet):
+ org = await Organization.prisma().create(
+ data={"name": "History test", "slug": f"history-{uuid4()}"}
+ )
+ time = (datetime.now(timezone.utc) - timedelta(minutes=5)).replace(microsecond=0)
+ try:
+ await add_charge(history_wallet, "personal", -999, time)
+ for key, amount, is_adjustment in [
+ ("estimate", -100, False),
+ ("extra", -15, True),
+ ("refund", 40, True),
+ ]:
+ await OrgCreditTransaction.prisma().create(
+ data={
+ "orgId": org.id,
+ "transactionKey": key,
+ "createdAt": time,
+ "amount": amount,
+ "type": CreditTransactionType.USAGE,
+ "metadata": SafeJson(
+ {
+ "graph_exec_id": "run-1",
+ "graph_id": "graph-1",
+ "input": (
+ {"reconciled_delta": -amount} if is_adjustment else {}
+ ),
+ }
+ ),
+ }
+ )
+ result = await get_credit_history(history_wallet, organization_id=org.id)
+ assert len(result.transactions) == 1
+ row = result.transactions[0]
+ assert row.amount == -75
+ assert row.usage_charge_amount == -100
+ assert row.usage_adjustment_amount == 25
+ assert row.charges_total_count == 3
+ assert row.transaction_time == time
+ finally:
+ await OrgCreditTransaction.prisma().delete_many(where={"orgId": org.id})
+ await Organization.prisma().delete(where={"id": org.id})
diff --git a/autogpt_platform/backend/backend/data/credit_history/queries.py b/autogpt_platform/backend/backend/data/credit_history/queries.py
new file mode 100644
index 0000000000..37cf284fc7
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/queries.py
@@ -0,0 +1,92 @@
+_HISTORY_QUERY = """
+WITH wallet AS (
+ SELECT "transactionKey", "createdAt", amount, type::text AS transaction_type,
+ metadata
+ FROM {schema_prefix}__LEDGER__
+ WHERE __OWNER__ = $1 AND "isActive" = TRUE
+ AND "createdAt" <= ($2::timestamptz AT TIME ZONE 'UTC')
+ AND ($3::text IS NULL OR type::text = $3::text)
+), classified AS MATERIALIZED (
+ SELECT *,
+ CASE WHEN transaction_type = 'USAGE'
+ AND NULLIF(metadata->>'graph_exec_id', '') IS NOT NULL
+ THEN 'execution:' || (metadata->>'graph_exec_id')
+ ELSE 'transaction:' || "transactionKey" END AS group_id,
+ CASE WHEN transaction_type != 'USAGE' THEN 'transaction'
+ WHEN metadata->'input' ? 'reconciled_delta' THEN 'adjustment'
+ WHEN metadata->'input'->>'charge' = 'Execution Cost' THEN 'execution_fee'
+ ELSE 'usage' END AS charge_type
+ FROM wallet
+), heads AS (
+ SELECT group_id AS id, MAX("createdAt") AS transaction_time
+ FROM classified
+ GROUP BY group_id
+), page AS (
+ SELECT * FROM heads
+ WHERE ($4::timestamptz IS NULL
+ OR (transaction_time, id) < (($4::timestamptz AT TIME ZONE 'UTC'), $5::text))
+ AND ($6::timestamptz IS NULL
+ OR transaction_time < ($6::timestamptz AT TIME ZONE 'UTC'))
+ ORDER BY transaction_time DESC, id DESC
+ LIMIT $7::int
+), selected AS MATERIALIZED (
+ SELECT classified.*
+ FROM classified INNER JOIN page ON page.id = classified.group_id
+), grouped AS (
+ SELECT group_id AS id,
+ CASE WHEN group_id LIKE 'execution:%' THEN group_id
+ ELSE MAX("transactionKey") END AS transaction_key,
+ MAX("createdAt") AS transaction_time,
+ MIN("createdAt") AS usage_start_time,
+ MAX(transaction_type) AS transaction_type,
+ SUM(amount)::bigint AS amount,
+ MAX(CASE WHEN transaction_type = 'USAGE'
+ THEN NULLIF(metadata->>'graph_id', '') END) AS usage_graph_id,
+ MAX(CASE WHEN transaction_type = 'USAGE'
+ THEN NULLIF(metadata->>'graph_exec_id', '') END) AS usage_execution_id,
+ COUNT(DISTINCT CASE WHEN transaction_type = 'USAGE'
+ THEN NULLIF(metadata->>'node_exec_id', '') END)::int
+ AS usage_node_count,
+ BOOL_OR(NULLIF(metadata->>'block_id', '') IS NOT NULL
+ OR NULLIF(metadata->>'block', '') IS NOT NULL) AS usage_has_block,
+ BOOL_OR(COALESCE(metadata->>'reason', '') = 'CoPilot daily rate limit reset')
+ AS usage_is_daily_reset,
+ COALESCE(SUM(amount) FILTER (WHERE charge_type = 'usage'), 0)::bigint
+ AS usage_charge_amount,
+ COALESCE(SUM(amount) FILTER (WHERE charge_type = 'execution_fee'), 0)::bigint
+ AS usage_fee_amount,
+ COALESCE(SUM(amount) FILTER (WHERE charge_type = 'adjustment'), 0)::bigint
+ AS usage_adjustment_amount,
+ COUNT(*)::int AS charges_total_count
+ FROM selected
+ GROUP BY group_id
+), selected_entries AS (
+ SELECT selected.*, ROW_NUMBER() OVER (
+ PARTITION BY group_id ORDER BY "createdAt", "transactionKey"
+ ) AS entry_number
+ FROM selected
+), details AS (
+ SELECT group_id, jsonb_agg(jsonb_build_object(
+ 'id', "transactionKey",
+ 'posted_at', "createdAt",
+ 'amount', amount,
+ 'charge_type', charge_type,
+ 'block_name', LEFT(metadata->>'block', 200),
+ 'node_execution_id', metadata->>'node_exec_id'
+ ) ORDER BY "createdAt", "transactionKey") AS charges
+ FROM selected_entries WHERE entry_number <= 100
+ GROUP BY group_id
+)
+SELECT page.*, COALESCE(details.charges, '[]'::jsonb) AS charges
+FROM grouped AS page LEFT JOIN details ON details.group_id = page.id
+ORDER BY page.transaction_time DESC, page.id DESC
+"""
+
+
+def credit_history_query(*, organization: bool) -> str:
+ ledger, owner = (
+ ('"OrgCreditTransaction"', '"orgId"')
+ if organization
+ else ('"CreditTransaction"', '"userId"')
+ )
+ return _HISTORY_QUERY.replace("__LEDGER__", ledger).replace("__OWNER__", owner)
diff --git a/autogpt_platform/backend/backend/data/credit_history/service.py b/autogpt_platform/backend/backend/data/credit_history/service.py
new file mode 100644
index 0000000000..8b43d23ec7
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/service.py
@@ -0,0 +1,166 @@
+from datetime import datetime, timezone
+from typing import Literal
+
+from prisma.enums import CreditTransactionType
+from pydantic import Json, TypeAdapter, field_validator
+
+from backend.data.credit_history.cursor import (
+ CreditHistoryCursor,
+ as_utc,
+ cursor_scope,
+ decode_cursor,
+ encode_cursor,
+)
+from backend.data.credit_history.enrichment import enrich_credit_history
+from backend.data.credit_history.queries import credit_history_query
+from backend.data.db import query_raw_with_schema
+from backend.data.model import (
+ CreditHistoryCharge,
+ CreditTransactionItem,
+ TransactionHistory,
+)
+
+
+async def get_credit_history(
+ user_id: str,
+ transaction_count_limit: int | None = 100,
+ transaction_time_ceiling: datetime | None = None,
+ transaction_type: str | None = None,
+ cursor: str | None = None,
+ organization_id: str | None = None,
+ viewer_organization_id: str | None = None,
+) -> TransactionHistory:
+ """Read wallet history with separately scoped viewer enrichment.
+
+ organization_id selects the authorized org wallet; None selects user_id's
+ personal wallet. viewer_organization_id scopes execution/chat visibility,
+ falling back to organization_id; it never changes the wallet being read.
+
+ Org history is organization-wide, with no initiator or team filtering:
+ active members can read ledger run/graph/node IDs and charge block names.
+ Viewer-scoped enrichment restricts agent names and navigation links, not
+ those ledger fields.
+ """
+ limit = transaction_count_limit if transaction_count_limit is not None else 100
+ if not 1 <= limit <= 1000:
+ raise ValueError("Transaction count limit must be between 1 and 1000")
+ if transaction_type is not None:
+ CreditTransactionType(transaction_type)
+ scope = cursor_scope(user_id, organization_id, transaction_type)
+ position = decode_cursor(cursor, scope) if cursor is not None else None
+ snapshot = position.snapshot_at if position else datetime.now(timezone.utc)
+ ceiling = as_utc(transaction_time_ceiling) if transaction_time_ceiling else None
+ rows = await query_raw_with_schema(
+ credit_history_query(organization=organization_id is not None),
+ organization_id if organization_id is not None else user_id,
+ snapshot,
+ transaction_type,
+ position.transaction_time if position else None,
+ position.group_id if position else None,
+ ceiling,
+ limit + 1,
+ model=_HistoryRow,
+ )
+ selected = [_to_item(row, user_id) for row in rows[:limit]]
+ transactions = await enrich_credit_history(
+ selected,
+ user_id=user_id,
+ organization_id=(
+ viewer_organization_id
+ if viewer_organization_id is not None
+ else organization_id
+ ),
+ )
+ for item in transactions:
+ if item.activity_type == "agent_run":
+ item.description = item.agent_name or "Agent unavailable"
+ has_more = len(rows) > limit
+ last = rows[limit - 1] if has_more else None
+ return TransactionHistory(
+ transactions=transactions,
+ snapshot_at=as_utc(snapshot),
+ next_transaction_time=as_utc(last.transaction_time) if last else None,
+ next_cursor=(
+ encode_cursor(
+ CreditHistoryCursor(
+ snapshot_at=snapshot,
+ transaction_time=as_utc(last.transaction_time),
+ group_id=last.id,
+ scope=scope,
+ )
+ )
+ if last is not None
+ else None
+ ),
+ )
+
+
+class _HistoryRow(CreditTransactionItem):
+ user_id: str = ""
+ usage_has_block: bool = False
+ usage_is_daily_reset: bool = False
+
+ @field_validator("charges", mode="before")
+ @classmethod
+ def parse_charges(cls, value: object) -> list[CreditHistoryCharge]:
+ # Prisma's typed raw-query decoder serializes JSON columns to strings.
+ return _HISTORY_CHARGES.validate_python(value)
+
+
+def _to_item(row: _HistoryRow, user_id: str) -> CreditTransactionItem:
+ activity_type: Literal["agent_run", "copilot_tools", "block_usage", "other"] = (
+ "other"
+ )
+ description = _TRANSACTION_DESCRIPTIONS[row.transaction_type]
+ if row.transaction_type == CreditTransactionType.USAGE:
+ if row.usage_execution_id and row.usage_execution_id.startswith(
+ "copilot-session-"
+ ):
+ activity_type, description = "copilot_tools", "Autopilot tool use"
+ elif row.usage_execution_id:
+ activity_type, description = "agent_run", "Agent run"
+ elif row.usage_has_block:
+ activity_type, description = "block_usage", "Block usage"
+ else:
+ description = (
+ "Daily limit reset" if row.usage_is_daily_reset else "Credit usage"
+ )
+ return CreditTransactionItem(
+ **row.model_dump(
+ exclude={
+ "user_id",
+ "activity_type",
+ "description",
+ "charges_truncated",
+ "transaction_time",
+ "usage_start_time",
+ "charges",
+ "usage_has_block",
+ "usage_is_daily_reset",
+ }
+ ),
+ user_id=user_id,
+ activity_type=activity_type,
+ description=description,
+ transaction_time=as_utc(row.transaction_time),
+ usage_start_time=as_utc(row.usage_start_time),
+ charges=[
+ charge.model_copy(update={"posted_at": as_utc(charge.posted_at)})
+ for charge in row.charges
+ ],
+ charges_truncated=row.charges_total_count > len(row.charges),
+ )
+
+
+_TRANSACTION_DESCRIPTIONS = {
+ CreditTransactionType.TOP_UP: "Credits added",
+ CreditTransactionType.USAGE: "Usage",
+ CreditTransactionType.GRANT: "Credits granted",
+ CreditTransactionType.REFUND: "Top-up refunded",
+ CreditTransactionType.CARD_CHECK: "Card verification",
+ CreditTransactionType.SUBSCRIPTION: "Subscription payment",
+}
+
+_HISTORY_CHARGES = TypeAdapter(
+ list[CreditHistoryCharge] | Json[list[CreditHistoryCharge]]
+)
diff --git a/autogpt_platform/backend/backend/data/credit_history/service_test.py b/autogpt_platform/backend/backend/data/credit_history/service_test.py
new file mode 100644
index 0000000000..af3a13574a
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_history/service_test.py
@@ -0,0 +1,265 @@
+import json
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock
+
+import pytest
+from prisma._raw_query import deserialize_raw_results
+from prisma.enums import CreditTransactionType
+from pydantic import ValidationError
+
+from backend.data.credit_history.cursor import cursor_scope, decode_cursor
+from backend.data.credit_history.service import (
+ _HistoryRow,
+ _to_item,
+ get_credit_history,
+)
+from backend.data.model import CreditHistoryCharge, CreditTransactionItem
+
+
+def history_row(key: str, execution_id: str | None = "run-1") -> _HistoryRow:
+ return _HistoryRow(
+ id=key,
+ transaction_key=key,
+ amount=-50,
+ transaction_time=datetime(2026, 9, 4, tzinfo=timezone.utc),
+ usage_start_time=datetime(2026, 9, 3, tzinfo=timezone.utc),
+ usage_execution_id=execution_id,
+ usage_graph_id="graph-1",
+ usage_has_block=True,
+ usage_charge_amount=-100,
+ usage_adjustment_amount=50,
+ charges_total_count=2,
+ charges=[
+ CreditHistoryCharge(
+ id="charge",
+ amount=-100,
+ charge_type="usage",
+ posted_at=datetime(2026, 9, 3, tzinfo=timezone.utc),
+ ),
+ CreditHistoryCharge(
+ id="adjustment",
+ amount=50,
+ charge_type="adjustment",
+ posted_at=datetime(2026, 9, 4, tzinfo=timezone.utc),
+ ),
+ ],
+ )
+
+
+async def test_page_cursor_preserves_snapshot_and_exact_position(monkeypatch):
+ query = AsyncMock(
+ return_value=[history_row("execution:run-2"), history_row("execution:run-1")]
+ )
+ enrichment = AsyncMock(side_effect=lambda items, **kwargs: items)
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.query_raw_with_schema", query
+ )
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.enrich_credit_history", enrichment
+ )
+ first = await get_credit_history("user", transaction_count_limit=1)
+ assert len(first.transactions) == 1
+ assert first.next_cursor
+ position = decode_cursor(first.next_cursor, cursor_scope("user", None, None))
+ assert position.group_id == "execution:run-2"
+ assert first.snapshot_at == position.snapshot_at
+ query.return_value = [history_row("execution:run-1")]
+ second = await get_credit_history(
+ "user", transaction_count_limit=1, cursor=first.next_cursor
+ )
+ args = query.call_args.args
+ assert args[1] == "user"
+ assert args[2] == position.snapshot_at
+ assert args[4] == position.transaction_time
+ assert args[5] == position.group_id
+ assert args[7] == 2
+ assert second.next_cursor is None
+ assert second.snapshot_at == first.snapshot_at
+ assert enrichment.call_args.kwargs == {"user_id": "user", "organization_id": None}
+
+
+async def test_org_uses_same_query_contract_and_scope(monkeypatch):
+ query = AsyncMock(return_value=[history_row("execution:run-1")])
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.query_raw_with_schema", query
+ )
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.enrich_credit_history",
+ AsyncMock(side_effect=lambda items, **kwargs: items),
+ )
+ ceiling = datetime(2026, 9, 5, 12, tzinfo=timezone(timedelta(hours=2)))
+ result = await get_credit_history(
+ "viewer",
+ organization_id="org-1",
+ transaction_type="USAGE",
+ transaction_time_ceiling=ceiling,
+ )
+ args = query.call_args.args
+ assert '"OrgCreditTransaction"' in args[0]
+ assert '"orgId" = $1' in args[0]
+ assert args[1] == "org-1"
+ assert args[3] == "USAGE"
+ assert args[6] == datetime(2026, 9, 5, 10, tzinfo=timezone.utc)
+ assert result.transactions[0].user_id == "viewer"
+
+
+async def test_viewer_context_does_not_switch_the_wallet(monkeypatch):
+ query = AsyncMock(
+ return_value=[history_row("execution:run-2"), history_row("execution:run-1")]
+ )
+ enrichment = AsyncMock(side_effect=lambda items, **kwargs: items)
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.query_raw_with_schema", query
+ )
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.enrich_credit_history", enrichment
+ )
+ page = await get_credit_history(
+ "user", transaction_count_limit=1, viewer_organization_id="current-context"
+ )
+ args = query.call_args.args
+ assert '"CreditTransaction"' in args[0]
+ assert '"userId" = $1' in args[0]
+ assert args[1] == "user"
+ enrichment.assert_awaited_once_with(
+ page.transactions, user_id="user", organization_id="current-context"
+ )
+ assert page.next_cursor
+ decode_cursor(page.next_cursor, cursor_scope("user", None, None))
+
+
[email protected]("limit", [0, -1, 1001])
+async def test_invalid_page_limit_is_rejected_before_query(limit):
+ with pytest.raises(ValueError, match="Transaction count limit"):
+ await get_credit_history("user", transaction_count_limit=limit)
+
+
+ "execution_id,activity,description",
+ [
+ ("run-1", "agent_run", "Agent run"),
+ ("copilot-session-chat", "copilot_tools", "Autopilot tool use"),
+ (None, "block_usage", "Block usage"),
+ ],
+)
+def test_usage_types_are_not_mislabelled(execution_id, activity, description):
+ item = _to_item(history_row("id", execution_id), "user")
+ assert item.activity_type == activity
+ assert item.description == description
+ assert (
+ item.amount
+ == item.usage_charge_amount
+ + item.usage_fee_amount
+ + item.usage_adjustment_amount
+ )
+ assert not item.charges_truncated
+
+
+def test_top_up_refund_is_negative_wallet_movement():
+ row = history_row("payment-id", None).model_copy(
+ update={"transaction_type": CreditTransactionType.REFUND}
+ )
+ item = _to_item(row, "user")
+ assert item.activity_type == "other"
+ assert item.description == "Top-up refunded"
+ assert item.transaction_key == "payment-id"
+ assert item.amount == -50
+
+
+def test_added_model_fields_preserve_legacy_construction():
+ item = CreditTransactionItem(
+ user_id="user", transaction_key="payment-id", amount=100
+ )
+ assert item.charges == []
+ assert item.related_executions == []
+ assert item.library_agent_id is None
+ assert not item.execution_available
+
+
+ "is_reset,expected",
+ [(True, "Daily limit reset"), (False, "Credit usage")],
+)
+def test_reason_only_usage_does_not_invent_a_block(is_reset, expected):
+ row = history_row("transaction:key", None).model_copy(
+ update={"usage_has_block": False, "usage_is_daily_reset": is_reset}
+ )
+ item = _to_item(row, "user")
+ assert item.activity_type == "other"
+ assert item.description == expected
+ assert "usage_has_block" not in item.model_dump()
+ assert "usage_is_daily_reset" not in item.model_dump()
+
+
+ "name,expected",
+ [("Research digest", "Research digest"), (None, "Agent unavailable")],
+)
+async def test_legacy_description_uses_safe_enriched_name(monkeypatch, name, expected):
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.query_raw_with_schema",
+ AsyncMock(return_value=[history_row("execution:run")]),
+ )
+
+ async def enrich(items, **kwargs):
+ return [item.model_copy(update={"agent_name": name}) for item in items]
+
+ monkeypatch.setattr(
+ "backend.data.credit_history.service.enrich_credit_history", enrich
+ )
+ result = await get_credit_history("user")
+ assert result.transactions[0].description == expected
+
+
+def test_raw_query_dates_are_unambiguously_utc():
+ row = history_row("execution:run").model_copy(
+ update={"transaction_time": datetime(2026, 9, 5, 10)}
+ )
+ row.charges[0].posted_at = datetime(2026, 9, 5, 9)
+ item = _to_item(row, "user")
+ assert item.transaction_time == datetime(2026, 9, 5, 10, tzinfo=timezone.utc)
+ assert item.charges[0].posted_at == datetime(2026, 9, 5, 9, tzinfo=timezone.utc)
+
+
[email protected]("serialized", [False, True])
[email protected]("populated", [False, True])
+def test_prisma_raw_json_charges_are_parsed_at_the_history_boundary(
+ serialized, populated
+):
+ charges = (
+ [charge.model_dump(mode="json") for charge in history_row("run").charges]
+ if populated
+ else []
+ )
+ rows = deserialize_raw_results(
+ {
+ "columns": ["id", "amount", "charges_total_count", "charges"],
+ "types": ["string", "bigint", "int", "json"],
+ "rows": [
+ [
+ "execution:run",
+ "-50" if populated else "0",
+ len(charges),
+ json.dumps(charges) if serialized else charges,
+ ]
+ ],
+ },
+ model=_HistoryRow,
+ )
+ item = _to_item(rows[0], "user")
+ assert item.charges == (history_row("run").charges if populated else [])
+ assert item.amount == sum(charge.amount for charge in item.charges)
+ assert item.charges_total_count == len(item.charges)
+ assert not item.charges_truncated
+ assert json.loads(item.model_dump_json())["charges"] == charges
+
+
[email protected]("charges", ["invalid-json", "{}", '[{"id":"missing-fields"}]'])
+def test_malformed_database_charges_are_not_silently_discarded(charges):
+ with pytest.raises(ValidationError):
+ _HistoryRow.model_validate({"charges": charges})
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index ecf96dcb87..3474eb7a44 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -862,7 +862,25 @@ class UserTransaction(BaseModel):
extra_data: str | None = None
+class CreditHistoryCharge(BaseModel):
+ id: str
+ posted_at: datetime
+ amount: int
+ charge_type: Literal["usage", "execution_fee", "adjustment", "transaction"]
+ block_name: str | None = None
+ node_execution_id: str | None = None
+
+
+class CreditHistoryRelatedExecution(BaseModel):
+ execution_id: str
+ agent_name: str | None = None
+ library_agent_id: str | None = None
+ execution_available: bool = False
+ amount: int | None = None
+
+
class CreditTransactionItem(BaseModel):
+ id: str = ""
transaction_key: str = ""
transaction_time: datetime = datetime.min.replace(tzinfo=timezone.utc)
transaction_type: CreditTransactionType = CreditTransactionType.USAGE
@@ -873,11 +891,37 @@ class CreditTransactionItem(BaseModel):
usage_node_count: int = 0
usage_start_time: datetime = datetime.max.replace(tzinfo=timezone.utc)
user_id: str
+ activity_type: Literal["agent_run", "copilot_tools", "block_usage", "other"] = (
+ "other"
+ )
+ library_agent_id: str | None = None
+ agent_name: str | None = None
+ execution_started_at: datetime | None = None
+ execution_status: str | None = None
+ execution_graph_version: int | None = None
+ execution_available: bool = False
+ conversation_id: str | None = None
+ conversation_title: str | None = None
+ parent_execution_id: str | None = None
+ parent_agent_name: str | None = None
+ parent_library_agent_id: str | None = None
+ related_executions: list[CreditHistoryRelatedExecution] = Field(
+ default_factory=list
+ )
+ related_executions_has_more: bool = False
+ usage_charge_amount: int = 0
+ usage_fee_amount: int = 0
+ usage_adjustment_amount: int = 0
+ charges: list[CreditHistoryCharge] = Field(default_factory=list)
+ charges_total_count: int = 0
+ charges_truncated: bool = False
class TransactionHistory(BaseModel):
transactions: list[CreditTransactionItem]
next_transaction_time: datetime | None
+ next_cursor: str | None = None
+ snapshot_at: datetime | None = None
class RefundRequest(BaseModel):
diff --git a/autogpt_platform/backend/backend/data/org_credit.py b/autogpt_platform/backend/backend/data/org_credit.py
index 156f2d99bc..2adf959178 100644
--- a/autogpt_platform/backend/backend/data/org_credit.py
+++ b/autogpt_platform/backend/backend/data/org_credit.py
@@ -19,6 +19,7 @@ from backend.data.credit import (
UserCreditBase,
get_user_credit_model,
)
+from backend.data.credit_history import get_credit_history
from backend.data.db import prisma
from backend.data.model import RefundRequest, TransactionHistory
from backend.data.onboarding_steps import OnboardingStep
@@ -355,29 +356,17 @@ class OrgCreditModel(UserCreditBase):
transaction_count_limit: int,
transaction_time_ceiling: datetime | None = None,
transaction_type: str | None = None,
+ cursor: str | None = None,
+ viewer_organization_id: str | None = None,
) -> TransactionHistory:
- raw = await get_org_transaction_history(
- self._org_id,
- limit=transaction_count_limit,
- offset=0,
- )
- from backend.data.model import CreditTransactionItem
-
- # TransactionHistory expects CreditTransactionItem; running_balance
- # lives on UserTransaction but isn't part of this DTO and is dropped.
- transactions = [
- CreditTransactionItem(
- user_id=user_id,
- amount=t["amount"],
- transaction_type=t.get("type", CreditTransactionType.USAGE),
- transaction_key=t.get("transactionKey", ""),
- description=f"{t.get('type', 'UNKNOWN')} Transaction",
- )
- for t in raw
- ]
- return TransactionHistory(
- transactions=transactions,
- next_transaction_time=None,
+ return await get_credit_history(
+ user_id=user_id,
+ organization_id=self._org_id,
+ transaction_count_limit=transaction_count_limit,
+ transaction_time_ceiling=transaction_time_ceiling,
+ transaction_type=transaction_type,
+ cursor=cursor,
+ viewer_organization_id=viewer_organization_id,
)
async def get_refund_requests(self, user_id: str) -> list[RefundRequest]:
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
index f8352f41ea..d9e0cb3f06 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
@@ -1058,12 +1058,13 @@ describe("TransactionHistoryCard", () => {
expect(await screen.findByText(/No transactions yet/i)).toBeDefined();
});
- it("renders a row per transaction with credit/debit colour-coded amounts", async () => {
+ it("renders signed balance changes with neutral debits and highlighted credits", async () => {
server.use(
jsonHandler("get", "/api/credits/transactions", {
transactions: [
{
transaction_key: "TXN-A",
+ id: "transaction:TXN-A",
transaction_time: "2026-04-10T00:00:00Z",
transaction_type: "TOP_UP",
amount: 5000,
@@ -1071,6 +1072,9 @@ describe("TransactionHistoryCard", () => {
},
{
transaction_key: "TXN-B",
+ id: "execution:TXN-B",
+ activity_type: "agent_run",
+ agent_name: "Morning briefing",
transaction_time: "2026-04-11T00:00:00Z",
transaction_type: "USAGE",
amount: -250,
@@ -1083,10 +1087,11 @@ describe("TransactionHistoryCard", () => {
render(<TransactionHistoryCard />);
- expect(await screen.findByText("Top up")).toBeDefined();
+ expect(await screen.findByText("Credits added")).toBeDefined();
+ expect(screen.getByText("Morning briefing")).toBeDefined();
expect(screen.getByText("Agent run")).toBeDefined();
expect(screen.getByText("+$50.00")).toBeDefined();
- expect(screen.getByText("-$2.50")).toBeDefined();
+ expect(screen.getByText("−$2.50")).toBeDefined();
expect(screen.queryByText(/^Balance$/)).toBeNull();
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
index 3f0530d5cb..ca542e683f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
@@ -1,146 +1,121 @@
"use client";
import { motion, useReducedMotion } from "framer-motion";
-
+import { useId } from "react";
+import { Button } from "@/components/atoms/Button/Button";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { Text } from "@/components/atoms/Text/Text";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
-
-import {
- getSectionMotionProps,
- rowVariants,
- rowsContainerVariants,
-} from "../../../helpers";
+import { getSectionMotionProps } from "../../../helpers";
+import { TransactionHistoryTable } from "./components/TransactionHistoryTable";
import { useTransactionHistoryCard } from "./useTransactionHistoryCard";
-interface Props {
- index?: number;
-}
+type Props = { index?: number };
export function TransactionHistoryCard({ index = 0 }: Props) {
const reduceMotion = useReducedMotion();
- const { transactions, isLoading, isError, refetch } =
- useTransactionHistoryCard();
- const sectionMotion = getSectionMotionProps(index, Boolean(reduceMotion));
-
- if (isLoading) {
- return (
- <motion.div {...sectionMotion}>
- <Skeleton className="h-[200px] rounded-[18px]" />
- </motion.div>
- );
- }
+ const history = useTransactionHistoryCard();
+ const headingID = useId();
- if (isError) {
- return (
- <ErrorCard
- context="transaction history"
- hint="We couldn't load your recent transactions."
- onRetry={() => void refetch()}
- />
- );
+ async function retryHistory() {
+ await history.refetch();
+ document.getElementById(headingID)?.focus({ preventScroll: true });
}
-
return (
- <motion.section {...sectionMotion} className="flex w-full flex-col gap-2">
- <div className="px-4">
- <Text variant="body-medium" as="span" className="text-textBlack">
- Transaction history
+ <motion.section
+ {...getSectionMotionProps(index, Boolean(reduceMotion))}
+ className="flex w-full flex-col gap-3"
+ aria-label="Transaction history"
+ >
+ <div className="flex flex-wrap items-end justify-between gap-2 px-4">
+ <div>
+ <Text
+ variant="body-medium"
+ as="h2"
+ id={headingID}
+ tabIndex={-1}
+ className="focus:outline-none"
+ >
+ Transaction history
+ </Text>
+ <Text variant="small" className="mt-1 text-zinc-600">
+ Changes to your automation credit balance.
+ </Text>
+ </div>
+ <Text variant="small" className="text-zinc-600">
+ USD · Your local time
</Text>
</div>
-
- <div className="overflow-hidden rounded-[18px] border border-zinc-200 bg-white shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
- {transactions.length === 0 ? (
- <div className="px-4 py-6">
- <Text variant="small" as="span" className="text-zinc-500">
- No transactions yet.
- </Text>
- </div>
- ) : (
- <div className="overflow-x-auto">
- <table className="w-full border-collapse text-left">
- <thead className="bg-zinc-50">
- <tr className="border-b border-zinc-200">
- <Th className="hidden sm:table-cell">Date</Th>
- <Th>Description</Th>
- <Th align="right">Amount</Th>
- </tr>
- </thead>
- <motion.tbody
- initial={reduceMotion ? false : "hidden"}
- animate="show"
- variants={reduceMotion ? undefined : rowsContainerVariants}
- >
- {transactions.map((transaction, rowIndex) => (
- <motion.tr
- key={transaction.id}
- variants={reduceMotion ? undefined : rowVariants}
- className={
- rowIndex !== transactions.length - 1
- ? "border-b border-zinc-100 transition-colors hover:bg-zinc-50/60"
- : "transition-colors hover:bg-zinc-50/60"
- }
- >
- <td className="hidden px-2 py-4 sm:table-cell sm:px-4">
- <Text variant="body" as="span" className="text-zinc-600">
- {transaction.date}
- </Text>
- </td>
- <td className="px-2 py-4 sm:px-4">
- <Text variant="body" as="span" className="text-textBlack">
- {transaction.description}
- </Text>
- <Text
- variant="small"
- as="span"
- className="block text-zinc-500 sm:hidden"
- >
- {transaction.date}
- </Text>
- </td>
- <td className="px-2 py-4 text-right sm:px-4">
- <Text
- variant="body-medium"
- as="span"
- className={
- transaction.kind === "credit"
- ? "tabular-nums text-emerald-700"
- : "tabular-nums text-red-600"
- }
- >
- {transaction.amount}
- </Text>
- </td>
- </motion.tr>
- ))}
- </motion.tbody>
- </table>
- </div>
- )}
- </div>
+ {history.isLoading ? (
+ <HistorySkeleton />
+ ) : history.isError ? (
+ <ErrorCard
+ context="transaction history"
+ hint="We couldn’t load your transactions. Please try again."
+ onRetry={() => void retryHistory()}
+ />
+ ) : history.transactions.length === 0 ? (
+ <EmptyHistory />
+ ) : (
+ <TransactionHistoryTable
+ transactions={history.transactions}
+ hasMore={history.hasMore}
+ isLoadingMore={history.isLoadingMore}
+ isLoadMoreError={history.isLoadMoreError}
+ onLoadMore={() => history.loadMore()}
+ />
+ )}
+ {history.isRefreshError && (
+ <div
+ className="flex flex-wrap items-center justify-between gap-2 px-4"
+ role="alert"
+ >
+ <Text variant="small" className="text-zinc-600">
+ History couldn’t be refreshed. Showing previously loaded activity.
+ </Text>
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={() => void retryHistory()}
+ >
+ Try again
+ </Button>
+ </div>
+ )}
+ <Text variant="small" className="px-4 text-zinc-600">
+ Each agent run combines its recorded charges and adjustments. Only runs
+ with credit activity appear here.
+ </Text>
</motion.section>
);
}
-interface ThProps {
- children: React.ReactNode;
- align?: "left" | "right";
- className?: string;
+function HistorySkeleton() {
+ return (
+ <div
+ role="status"
+ aria-label="Loading transaction history"
+ className="rounded-large border border-zinc-200 bg-white p-5"
+ >
+ <div className="space-y-6">
+ {Array.from({ length: 5 }, (_, index) => (
+ <div key={index} className="flex items-center justify-between gap-6">
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-5 w-16" />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
}
-function Th({ children, align = "left", className = "" }: ThProps) {
+function EmptyHistory() {
return (
- <th
- scope="col"
- className={`px-2 py-3 sm:px-4 ${align === "right" ? "text-right" : "text-left"} ${className}`}
- >
- <Text
- variant="small-medium"
- as="span"
- className="uppercase tracking-[0.04em] text-zinc-500"
- >
- {children}
+ <div className="rounded-large border border-zinc-200 bg-white px-5 py-10 text-center">
+ <Text variant="body-medium">No transactions yet.</Text>
+ <Text variant="small" className="mt-2 text-zinc-600">
+ Credit purchases and paid activity will appear here.
</Text>
- </th>
+ </div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/activity-types.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/activity-types.test.tsx
new file mode 100644
index 0000000000..b6a654a71d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/activity-types.test.tsx
@@ -0,0 +1,199 @@
+import { delay, http, HttpResponse } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@/tests/integrations/test-utils";
+import { TransactionHistoryCard } from "../TransactionHistoryCard";
+import { executionID, run, topUp } from "./fixtures";
+
+describe("Transaction history activity and states", () => {
+ it.each([
+ ["REFUND", -500, "Top-up refunded", "−$5.00"],
+ ["SUBSCRIPTION", -2000, "Subscription payment", "−$20.00"],
+ ["GRANT", 500, "Credits granted", "+$5.00"],
+ ["CARD_CHECK", 0, "Card verification", "$0.00"],
+ ["USAGE", -500, "Daily limit reset", "−$5.00"],
+ ] as const)(
+ "renders %s as a signed credit-balance change",
+ async (type, amount, name, formatted) => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ { ...topUp, transaction_type: type, description: name, amount },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText(name);
+ const money = screen.getByText(formatted);
+ expect(money.classList.contains("text-red-600")).toBe(false);
+ expect(money.classList.contains("text-green-700")).toBe(
+ Number(amount) > 0,
+ );
+ },
+ );
+
+ it("renders direct block usage outside an agent run", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ {
+ ...topUp,
+ transaction_type: "USAGE",
+ activity_type: "block_usage",
+ description: "Block usage",
+ amount: -12,
+ },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ expect(await screen.findByText("Direct block usage")).toBeDefined();
+ expect(screen.getByText("Outside an agent run")).toBeDefined();
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Direct block usage/i }),
+ );
+ expect(
+ screen.getByText("A paid block call without an associated agent run."),
+ ).toBeDefined();
+ });
+
+ it("uses the conversation destination for Autopilot tool use, never a library route", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ {
+ ...run,
+ activity_type: "copilot_tools",
+ conversation_id: "chat-123",
+ conversation_title: "Market landscape",
+ library_agent_id: null,
+ execution_available: false,
+ execution_status: null,
+ },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText("Autopilot tool use");
+ expect(screen.getByText("Market landscape")).toBeDefined();
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Autopilot tool use/i }),
+ );
+ expect(
+ screen
+ .getByRole("link", { name: /View conversation/ })
+ .getAttribute("href"),
+ ).toBe("/copilot?sessionId=chat-123");
+ expect(screen.queryByRole("link", { name: /View task/ })).toBeNull();
+ expect(
+ screen.getByText(/Subscription usage is tracked separately/),
+ ).toBeDefined();
+ });
+
+ it("opens related receipts without adding child charges to the parent amount", async () => {
+ const childID = "child-run";
+ const child = {
+ ...run,
+ id: "execution:child-run",
+ usage_execution_id: childID,
+ agent_name: "Website summary",
+ amount: -6,
+ usage_charge_amount: -6,
+ usage_fee_amount: 0,
+ usage_adjustment_amount: 0,
+ library_agent_id: null,
+ parent_execution_id: executionID,
+ parent_agent_name: "Morning briefing",
+ };
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ {
+ ...run,
+ related_executions: [
+ {
+ execution_id: childID,
+ agent_name: "Website summary",
+ amount: null,
+ },
+ ],
+ },
+ child,
+ ],
+ next_cursor: null,
+ snapshot_at: "2026-09-05T08:14:10Z",
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText("Morning briefing");
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Morning briefing/i }),
+ );
+ const parentReceipt = screen.getByRole("region", {
+ name: "Morning briefing credit receipt",
+ });
+ expect(within(parentReceipt).getByText("−$0.12")).toBeDefined();
+ expect(within(parentReceipt).getByText("−$0.06")).toBeDefined();
+ expect(within(parentReceipt).queryByText("−$0.18")).toBeNull();
+ fireEvent.click(
+ within(parentReceipt).getByRole("button", { name: "Website summary" }),
+ );
+ expect(
+ screen.getByRole("region", { name: "Website summary credit receipt" }),
+ ).toBeDefined();
+ expect(
+ screen.queryByRole("region", { name: "Morning briefing credit receipt" }),
+ ).toBeNull();
+ expect(document.activeElement?.id).toBe(
+ "transaction-details-execution:child-run",
+ );
+ });
+
+ it("shows loading, then the genuine empty state", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", async () => {
+ await delay(100);
+ return HttpResponse.json({ transactions: [], next_cursor: null });
+ }),
+ );
+ render(<TransactionHistoryCard />);
+ expect(
+ screen.getByRole("status", { name: "Loading transaction history" }),
+ ).toBeDefined();
+ expect(await screen.findByText("No transactions yet.")).toBeDefined();
+ });
+
+ it("retries an initial error without claiming that ongoing credit activity stopped", async () => {
+ let attempts = 0;
+ server.use(
+ http.get("*/api/credits/transactions", () => {
+ attempts += 1;
+ return attempts === 1
+ ? HttpResponse.json({ detail: "Unavailable" }, { status: 500 })
+ : HttpResponse.json({ transactions: [topUp], next_cursor: null });
+ }),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText(/We couldn.t load your transactions/);
+ expect(screen.queryByText(/Your credit balance is unchanged/)).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Try Again" }));
+ expect(await screen.findByText("Credits added")).toBeDefined();
+ expect(document.activeElement?.textContent).toBe("Transaction history");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/fixtures.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/fixtures.ts
new file mode 100644
index 0000000000..490354c9e2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/fixtures.ts
@@ -0,0 +1,57 @@
+export const executionID = "e4288112-28f2-432e-b5f0-937d22a7bc21";
+export const libraryID = "3b8c1a22-5c27-48aa-ae42-184cff161bb2";
+
+export const run = {
+ id: `execution:${executionID}`,
+ transaction_key: `execution:${executionID}`,
+ transaction_type: "USAGE",
+ transaction_time: "2026-09-05T08:14:09Z",
+ amount: -12,
+ description: "Agent run",
+ activity_type: "agent_run",
+ agent_name: "Morning briefing",
+ library_agent_id: libraryID,
+ usage_execution_id: executionID,
+ execution_available: true,
+ execution_started_at: "2026-09-05T08:13:52Z",
+ execution_status: "RUNNING",
+ execution_graph_version: 3,
+ usage_charge_amount: -14,
+ usage_fee_amount: -1,
+ usage_adjustment_amount: 3,
+ related_executions: [],
+ charges_total_count: 3,
+ charges_truncated: false,
+ charges: [
+ {
+ id: "charge-1",
+ amount: -14,
+ posted_at: "2026-09-05T08:13:54Z",
+ charge_type: "usage",
+ },
+ {
+ id: "charge-2",
+ amount: -1,
+ posted_at: "2026-09-05T08:13:58Z",
+ charge_type: "execution_fee",
+ },
+ {
+ id: "charge-3",
+ amount: 3,
+ posted_at: "2026-09-05T08:14:09Z",
+ charge_type: "adjustment",
+ },
+ ],
+};
+
+export const topUp = {
+ id: "transaction:topup-1",
+ transaction_key: "topup-1",
+ transaction_type: "TOP_UP",
+ transaction_time: "2026-09-04T08:30:12Z",
+ description: "Credits added",
+ activity_type: "other",
+ amount: 2000,
+ charges: [],
+ related_executions: [],
+};
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/receipt-snapshot.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/receipt-snapshot.test.tsx
new file mode 100644
index 0000000000..6223c351a1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/receipt-snapshot.test.tsx
@@ -0,0 +1,55 @@
+import { http, HttpResponse } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@/tests/integrations/test-utils";
+import { TransactionHistoryCard } from "../TransactionHistoryCard";
+import { run, topUp } from "./fixtures";
+
+describe("Transaction history snapshot", () => {
+ it("labels the credit cutoff even when a later page reports a currently completed run", async () => {
+ const snapshot = "2026-09-05T08:14:10Z";
+ server.use(
+ http.get("*/api/credits/transactions", ({ request }) => {
+ const laterPage = new URL(request.url).searchParams.has("cursor");
+ return HttpResponse.json({
+ transactions: laterPage
+ ? [{ ...run, execution_status: "COMPLETED" }]
+ : [topUp],
+ next_cursor: laterPage ? null : "older-page",
+ snapshot_at: snapshot,
+ });
+ }),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText("Credits added");
+ fireEvent.click(screen.getByRole("button", { name: /Load more/ }));
+ await screen.findByText("Morning briefing");
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Morning briefing/i }),
+ );
+ const receipt = screen.getByRole("region", {
+ name: "Morning briefing credit receipt",
+ });
+ expect(
+ within(receipt).getByText("Run status").closest("div")?.textContent,
+ ).toContain("Completed");
+ const cutoff = within(receipt).getByText("Credits as of").closest("div");
+ expect(cutoff?.querySelector("[title]")?.getAttribute("title")).toBe(
+ new Date(snapshot).toLocaleString(undefined, {
+ dateStyle: "long",
+ timeStyle: "long",
+ }),
+ );
+ expect(
+ within(receipt).getByText(
+ "Recorded charges and adjustments for this run.",
+ ),
+ ).toBeDefined();
+ expect(within(receipt).queryByText(/All recorded/)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/time-zone.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/time-zone.test.tsx
new file mode 100644
index 0000000000..730bea3f69
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/time-zone.test.tsx
@@ -0,0 +1,31 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderToString } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import { TransactionHistoryCard } from "../TransactionHistoryCard";
+
+describe("Transaction history time zone", () => {
+ it("keeps initial markup stable across server and browser time zones", () => {
+ const options = Intl.DateTimeFormat().resolvedOptions();
+ const resolvedOptions = vi.spyOn(
+ Intl.DateTimeFormat.prototype,
+ "resolvedOptions",
+ );
+ const card = (
+ <QueryClientProvider client={new QueryClient()}>
+ <TransactionHistoryCard />
+ </QueryClientProvider>
+ );
+
+ try {
+ resolvedOptions.mockReturnValue({ ...options, timeZone: "UTC" });
+ const serverMarkup = renderToString(card);
+ resolvedOptions.mockReturnValue({ ...options, timeZone: "Europe/Paris" });
+ const browserMarkup = renderToString(card);
+
+ expect(browserMarkup).toBe(serverMarkup);
+ expect(serverMarkup).toContain("USD · Your local time");
+ } finally {
+ resolvedOptions.mockRestore();
+ }
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/transaction-history.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/transaction-history.test.tsx
new file mode 100644
index 0000000000..af291818db
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/__tests__/transaction-history.test.tsx
@@ -0,0 +1,179 @@
+import { http, HttpResponse } from "msw";
+import { describe, expect, it } from "vitest";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@/tests/integrations/test-utils";
+import { TransactionHistoryCard } from "../TransactionHistoryCard";
+import { executionID, libraryID, run, topUp } from "./fixtures";
+
+describe("Transaction history receipts", () => {
+ it("links the agent separately from its task and labels run status in the receipt", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({ transactions: [run], next_cursor: null }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+
+ expect(
+ (
+ await screen.findByRole("link", { name: "Morning briefing" })
+ ).getAttribute("href"),
+ ).toBe(`/library/agents/${libraryID}`);
+ expect(screen.queryByRole("link", { name: "View task" })).toBeNull();
+ const details = screen.getByRole("button", {
+ name: /details for Morning briefing/i,
+ });
+ expect(details.getAttribute("aria-expanded")).toBe("false");
+ fireEvent.click(details);
+
+ const receipt = screen.getByRole("region", {
+ name: "Morning briefing credit receipt",
+ });
+ expect(
+ within(receipt).getByRole("heading", { name: "Charges for this run" })
+ .textContent,
+ ).toMatch(/^Charges for this run$/);
+ const statusLabel = within(receipt).getByText("Run status");
+ expect(statusLabel.closest("div")?.textContent).toContain("Running");
+ expect(within(receipt).getByText("Net change so far")).toBeDefined();
+ expect(
+ within(receipt).getByText("+$0.03").classList.contains("text-green-700"),
+ ).toBe(true);
+ expect(
+ within(receipt)
+ .getByRole("link", { name: /View task/ })
+ .getAttribute("href"),
+ ).toBe(
+ `/library/agents/${libraryID}?activeTab=runs&activeItem=${executionID}`,
+ );
+
+ fireEvent.click(
+ within(receipt).getByRole("button", { name: /Show charge entries/ }),
+ );
+ expect(
+ within(receipt).getByRole("table", { name: "Recorded charge entries" }),
+ ).toBeDefined();
+ fireEvent.click(within(receipt).getByRole("button", { name: "Reference" }));
+ expect(within(receipt).getByText(executionID)).toBeDefined();
+ });
+
+ it("preserves loaded receipts when loading more fails and retries the same cursor", async () => {
+ let attempts = 0;
+ server.use(
+ http.get("*/api/credits/transactions", ({ request }) => {
+ if (!new URL(request.url).searchParams.has("cursor"))
+ return HttpResponse.json({
+ transactions: [run],
+ next_cursor: "older-page",
+ });
+ attempts += 1;
+ if (attempts === 1)
+ return HttpResponse.json({ detail: "Unavailable" }, { status: 500 });
+ expect(new URL(request.url).searchParams.get("cursor")).toBe(
+ "older-page",
+ );
+ return HttpResponse.json({ transactions: [topUp], next_cursor: null });
+ }),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByRole("link", { name: "Morning briefing" });
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Morning briefing/i }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Load more/ }));
+ await screen.findByText(/couldn.t load older transactions/i);
+ expect(
+ screen.getByRole("region", { name: "Morning briefing credit receipt" }),
+ ).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: /Retry loading more/ }));
+ expect(await screen.findByText("Credits added")).toBeDefined();
+ expect(
+ screen.getByText("+$20.00").classList.contains("text-green-700"),
+ ).toBe(true);
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: /Load more/ })).toBeNull(),
+ );
+ });
+
+ it("keeps unavailable history without creating a dead library or task link", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ {
+ ...run,
+ agent_name: null,
+ library_agent_id: null,
+ execution_available: false,
+ execution_status: null,
+ execution_started_at: null,
+ execution_graph_version: null,
+ },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText("Agent unavailable");
+ expect(screen.queryByRole("link")).toBeNull();
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Agent unavailable/i }),
+ );
+ expect(screen.getByText("Agent and run unavailable")).toBeDefined();
+ expect(screen.queryByRole("link", { name: /View task/ })).toBeNull();
+ });
+
+ it("keeps the agent link when its run is unavailable without creating a dead task link", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [{ ...run, execution_available: false }],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ expect(
+ (
+ await screen.findByRole("link", { name: "Morning briefing" })
+ ).getAttribute("href"),
+ ).toBe(`/library/agents/${libraryID}`);
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Morning briefing/i }),
+ );
+ expect(screen.queryByRole("link", { name: /View task/ })).toBeNull();
+ expect(screen.getByText("Run unavailable")).toBeDefined();
+ });
+
+ it("keeps complete totals when the charge-entry list is limited", async () => {
+ server.use(
+ http.get("*/api/credits/transactions", () =>
+ HttpResponse.json({
+ transactions: [
+ { ...run, charges_total_count: 130, charges_truncated: true },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ );
+ render(<TransactionHistoryCard />);
+ await screen.findByText("Morning briefing");
+ fireEvent.click(
+ screen.getByRole("button", { name: /details for Morning briefing/i }),
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: /Show charge entries/ }),
+ );
+ expect(screen.getByText(/Showing 3 of 130 charge entries/)).toBeDefined();
+ expect(
+ screen.getByText(/The total includes every charge and adjustment/),
+ ).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptBreakdown.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptBreakdown.tsx
new file mode 100644
index 0000000000..b478969f77
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptBreakdown.tsx
@@ -0,0 +1,63 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { activityName, isRunActive, type Transaction } from "../helpers";
+import { TransactionAmount } from "./TransactionAmount";
+
+type Props = { transaction: Transaction };
+
+export function ReceiptBreakdown({ transaction }: Props) {
+ const usage =
+ transaction.activity_type !== "other" &&
+ transaction.transaction_type === "USAGE";
+ return (
+ <dl className="mt-4 grid grid-cols-[minmax(0,1fr)_auto] gap-x-5 gap-y-2">
+ {usage ? (
+ <>
+ <BreakdownLine
+ label="Block usage"
+ amount={transaction.usage_charge_amount ?? 0}
+ />
+ {!!transaction.usage_fee_amount && (
+ <BreakdownLine
+ label="Execution fees"
+ amount={transaction.usage_fee_amount}
+ />
+ )}
+ {!!transaction.usage_adjustment_amount && (
+ <BreakdownLine
+ label="Usage adjustment"
+ amount={transaction.usage_adjustment_amount}
+ />
+ )}
+ </>
+ ) : (
+ <BreakdownLine
+ label={activityName(transaction)}
+ amount={transaction.amount}
+ />
+ )}
+ <dt className="mt-1 border-t border-zinc-200 pt-3">
+ <Text variant="body-medium" as="span">
+ {isRunActive(transaction) ? "Net change so far" : "Net change"}
+ </Text>
+ </dt>
+ <dd className="mt-1 border-t border-zinc-200 pt-3 text-right">
+ <TransactionAmount amount={transaction.amount} />
+ </dd>
+ </dl>
+ );
+}
+
+function BreakdownLine({ label, amount }: { label: string; amount: number }) {
+ return (
+ <>
+ <dt>
+ <Text variant="small" as="span" className="text-zinc-600">
+ {label}
+ </Text>
+ </dt>
+ <dd className="text-right">
+ <TransactionAmount amount={amount} className="text-xs font-normal" />
+ </dd>
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptEntries.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptEntries.tsx
new file mode 100644
index 0000000000..15b675262b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptEntries.tsx
@@ -0,0 +1,127 @@
+import { useId, useState } from "react";
+import { ArrowDown01Icon, ArrowUp01Icon } from "@hugeicons/core-free-icons";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { chargeLabel, formatActivityDate, type Transaction } from "../helpers";
+import { TransactionAmount } from "./TransactionAmount";
+
+type Props = { transaction: Transaction };
+
+export function ReceiptEntries({ transaction }: Props) {
+ const [entriesOpen, setEntriesOpen] = useState(false);
+ const [referenceOpen, setReferenceOpen] = useState(false);
+ const entriesID = useId();
+ const referenceID = useId();
+ const reference =
+ transaction.usage_execution_id || transaction.transaction_key;
+ return (
+ <div className="mt-3">
+ <div className="flex flex-wrap items-center justify-between gap-x-4">
+ {!!transaction.charges?.length && (
+ <Button
+ variant="ghost"
+ size="small"
+ className="min-h-11 min-w-0 px-0 text-zinc-600"
+ onClick={() => setEntriesOpen(!entriesOpen)}
+ aria-expanded={entriesOpen}
+ aria-controls={entriesOpen ? entriesID : undefined}
+ rightIcon={
+ <Icon
+ icon={entriesOpen ? ArrowUp01Icon : ArrowDown01Icon}
+ size={16}
+ />
+ }
+ >
+ {entriesOpen ? "Hide" : "Show"} charge entries
+ </Button>
+ )}
+ {reference && (
+ <Button
+ variant="ghost"
+ size="small"
+ className="min-h-11 min-w-0 px-0 text-zinc-600"
+ onClick={() => setReferenceOpen(!referenceOpen)}
+ aria-expanded={referenceOpen}
+ aria-controls={referenceOpen ? referenceID : undefined}
+ >
+ {referenceOpen ? "Hide reference" : "Reference"}
+ </Button>
+ )}
+ </div>
+ {entriesOpen && (
+ <div id={entriesID}>
+ <ChargeEntries transaction={transaction} />
+ </div>
+ )}
+ {referenceOpen && (
+ <div id={referenceID} className="mt-2">
+ <Text variant="small" className="text-zinc-600">
+ {transaction.activity_type === "agent_run" ? "Run ID" : "Reference"}
+ </Text>
+ <Text
+ variant="small"
+ as="code"
+ unmask={false}
+ className="break-all font-mono"
+ >
+ {reference}
+ </Text>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ChargeEntries({ transaction }: Props) {
+ const charges = transaction.charges ?? [];
+ return (
+ <div className="mt-2 border-t border-zinc-200 pt-3">
+ <table className="w-full text-left" aria-label="Recorded charge entries">
+ <thead className="sr-only">
+ <tr>
+ <th scope="col">Date and time</th>
+ <th scope="col">Charge</th>
+ <th scope="col">Amount</th>
+ </tr>
+ </thead>
+ <tbody>
+ {charges.map((charge) => {
+ const posted = formatActivityDate(charge.posted_at);
+ return (
+ <tr key={charge.id}>
+ <td className="py-2 pr-3 align-top">
+ <Text
+ variant="small"
+ unmask={false}
+ title={posted.full}
+ className="text-zinc-600"
+ >
+ {posted.date}
+ <br />
+ {posted.time}
+ </Text>
+ </td>
+ <td className="py-2 pr-3 align-top">
+ <Text variant="small">{chargeLabel(charge.charge_type)}</Text>
+ </td>
+ <td className="py-2 text-right align-top">
+ <TransactionAmount
+ amount={charge.amount}
+ className="text-xs font-normal"
+ />
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {transaction.charges_truncated && (
+ <Text variant="small" className="mt-2 text-zinc-600">
+ Showing {charges.length} of {transaction.charges_total_count} charge
+ entries. The total includes every charge and adjustment.
+ </Text>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptMetadata.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptMetadata.tsx
new file mode 100644
index 0000000000..0deadf3040
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptMetadata.tsx
@@ -0,0 +1,131 @@
+import { ArrowUpRight01Icon } from "@hugeicons/core-free-icons";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import {
+ formatActivityDate,
+ statusLabel,
+ taskHref,
+ type Transaction,
+} from "../helpers";
+
+type Props = { transaction: Transaction };
+
+export function ReceiptMetadata({ transaction }: Props) {
+ const started = formatActivityDate(transaction.execution_started_at);
+ const posted = formatActivityDate(transaction.transaction_time);
+ const cutoff = formatActivityDate(transaction.receipt_as_of);
+ return (
+ <div className="mt-4 flex flex-wrap items-end justify-between gap-4 border-t border-zinc-200 pt-4">
+ <div className="flex flex-wrap gap-x-6 gap-y-3">
+ {transaction.execution_status && (
+ <div className="flex flex-col items-start gap-1">
+ <Text variant="small" className="text-zinc-600">
+ Run status
+ </Text>
+ <Badge
+ variant={
+ transaction.execution_status === "COMPLETED"
+ ? "success"
+ : transaction.execution_status === "FAILED"
+ ? "error"
+ : "info"
+ }
+ size="small"
+ >
+ {statusLabel(transaction.execution_status)}
+ </Badge>
+ </div>
+ )}
+ {transaction.execution_started_at && (
+ <MetadataField
+ label="Started"
+ value={`${started.date} · ${started.time}`}
+ title={started.full}
+ />
+ )}
+ {transaction.execution_graph_version != null && (
+ <MetadataField
+ label="Version"
+ value={`v${transaction.execution_graph_version}`}
+ />
+ )}
+ <MetadataField
+ label="Last activity"
+ value={`${posted.date} · ${posted.time}`}
+ title={posted.full}
+ />
+ {transaction.receipt_as_of && (
+ <MetadataField
+ label="Credits as of"
+ value={`${cutoff.date} · ${cutoff.time}`}
+ title={cutoff.full}
+ />
+ )}
+ </div>
+ <ReceiptDestination transaction={transaction} />
+ </div>
+ );
+}
+
+function MetadataField({
+ label,
+ value,
+ title,
+}: {
+ label: string;
+ value: string;
+ title?: string;
+}) {
+ return (
+ <div className="flex flex-col gap-1">
+ <Text variant="small" className="text-zinc-600">
+ {label}
+ </Text>
+ <Text variant="small" unmask={false} title={title}>
+ {value}
+ </Text>
+ </div>
+ );
+}
+
+function ReceiptDestination({ transaction }: Props) {
+ const href = taskHref(transaction);
+ const conversationHref = transaction.conversation_id
+ ? `/copilot?sessionId=${encodeURIComponent(transaction.conversation_id)}`
+ : null;
+ if (href || conversationHref) {
+ return (
+ <Button
+ as="NextLink"
+ href={href || conversationHref || ""}
+ variant="secondary"
+ size="small"
+ className="min-h-11 min-w-0"
+ rightIcon={<Icon icon={ArrowUpRight01Icon} size={16} />}
+ >
+ {href ? "View task" : "View conversation"}
+ </Button>
+ );
+ }
+ if (transaction.activity_type === "agent_run") {
+ const label = transaction.library_agent_id
+ ? "Run unavailable"
+ : transaction.execution_available
+ ? "Not in your library"
+ : "Agent and run unavailable";
+ return (
+ <Text variant="small" className="text-zinc-600">
+ {label}
+ </Text>
+ );
+ }
+ if (transaction.activity_type === "copilot_tools")
+ return (
+ <Text variant="small" className="text-zinc-600">
+ Conversation unavailable
+ </Text>
+ );
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptRelations.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptRelations.tsx
new file mode 100644
index 0000000000..baa166c16e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/ReceiptRelations.tsx
@@ -0,0 +1,130 @@
+import type { CreditHistoryRelatedExecution } from "@/app/api/__generated__/models/creditHistoryRelatedExecution";
+import { Button } from "@/components/atoms/Button/Button";
+import { Link } from "@/components/atoms/Link/Link";
+import { Text } from "@/components/atoms/Text/Text";
+import { libraryHref, type Transaction } from "../helpers";
+import { TransactionAmount } from "./TransactionAmount";
+
+type Props = {
+ transaction: Transaction;
+ loadedTransactions: Transaction[];
+ onSelectRelated: (executionID: string) => void;
+};
+
+export function ReceiptRelations({
+ transaction,
+ loadedTransactions,
+ onSelectRelated,
+}: Props) {
+ const related = transaction.related_executions ?? [];
+ if (
+ !transaction.parent_execution_id &&
+ related.length === 0 &&
+ !transaction.related_executions_has_more
+ )
+ return null;
+ return (
+ <div className="mt-4 space-y-2 border-t border-zinc-200 pt-3">
+ {transaction.parent_execution_id && (
+ <Text variant="small" className="text-zinc-600">
+ Started by
+ </Text>
+ )}
+ {transaction.parent_execution_id && (
+ <RelatedExecution
+ execution={{
+ execution_id: transaction.parent_execution_id,
+ agent_name: transaction.parent_agent_name,
+ library_agent_id: transaction.parent_library_agent_id,
+ execution_available: !!transaction.parent_library_agent_id,
+ }}
+ loadedTransactions={loadedTransactions}
+ receiptAsOf={transaction.receipt_as_of}
+ onSelectRelated={onSelectRelated}
+ />
+ )}
+ {(related.length > 0 || transaction.related_executions_has_more) && (
+ <Text variant="small" className="text-zinc-600">
+ Other agents used by this run
+ </Text>
+ )}
+ {related.map((execution) => (
+ <RelatedExecution
+ key={execution.execution_id}
+ execution={execution}
+ loadedTransactions={loadedTransactions}
+ receiptAsOf={transaction.receipt_as_of}
+ onSelectRelated={onSelectRelated}
+ />
+ ))}
+ <Text variant="small" className="text-zinc-600">
+ Any credit charges for related runs appear separately.
+ {related.length > 0
+ ? " The task page includes related runs in its total."
+ : ""}
+ </Text>
+ {transaction.related_executions_has_more && (
+ <Text variant="small" className="text-zinc-600">
+ More related runs are not shown here.
+ </Text>
+ )}
+ </div>
+ );
+}
+
+function RelatedExecution({
+ execution,
+ loadedTransactions,
+ receiptAsOf,
+ onSelectRelated,
+}: {
+ execution: CreditHistoryRelatedExecution;
+ loadedTransactions: Transaction[];
+ receiptAsOf: Transaction["receipt_as_of"];
+ onSelectRelated: (executionID: string) => void;
+}) {
+ const name = execution.agent_name || "Agent unavailable";
+ const loaded = loadedTransactions.find(
+ (item) => item.usage_execution_id === execution.execution_id,
+ );
+ const sameSnapshot =
+ receiptAsOf &&
+ loaded?.receipt_as_of &&
+ new Date(receiptAsOf).getTime() ===
+ new Date(loaded.receipt_as_of).getTime();
+ const amount = sameSnapshot ? loaded.amount : execution.amount;
+ const agentHref = libraryHref(execution.library_agent_id);
+ const href =
+ agentHref && execution.execution_available
+ ? `${agentHref}?activeTab=runs&activeItem=${encodeURIComponent(execution.execution_id)}`
+ : null;
+ return (
+ <div className="flex items-center justify-between gap-4">
+ {loaded ? (
+ <Button
+ variant="ghost"
+ size="small"
+ unmask={false}
+ className="min-h-11 min-w-0 whitespace-normal px-0 text-left text-purple-700"
+ onClick={() => onSelectRelated(execution.execution_id)}
+ >
+ {name}
+ </Button>
+ ) : href ? (
+ <Link
+ href={href}
+ className="inline-flex min-h-11 items-center text-purple-700"
+ >
+ {name}
+ </Link>
+ ) : (
+ <Text variant="small" unmask={false}>
+ {name}
+ </Text>
+ )}
+ {amount != null && (
+ <TransactionAmount amount={amount} className="text-xs" />
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionAmount.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionAmount.tsx
new file mode 100644
index 0000000000..1c7b88b25d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionAmount.tsx
@@ -0,0 +1,22 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+import { formatAmount } from "../helpers";
+
+type Props = { amount: number; className?: string };
+
+export function TransactionAmount({ amount, className }: Props) {
+ return (
+ <Text
+ variant="body-medium"
+ as="span"
+ unmask={false}
+ className={cn(
+ "whitespace-nowrap tabular-nums",
+ amount > 0 ? "text-green-700" : "text-textBlack",
+ className,
+ )}
+ >
+ {formatAmount(amount)}
+ </Text>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionHistoryTable.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionHistoryTable.tsx
new file mode 100644
index 0000000000..fa24b8c224
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionHistoryTable.tsx
@@ -0,0 +1,128 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { useId, type MouseEvent } from "react";
+import { Text } from "@/components/atoms/Text/Text";
+import type { Transaction } from "../helpers";
+import { useReceiptSelection } from "../useReceiptSelection";
+import { TransactionRow } from "./TransactionRow";
+
+type Props = {
+ transactions: Transaction[];
+ hasMore: boolean;
+ isLoadingMore: boolean;
+ isLoadMoreError: boolean;
+ onLoadMore: () => Promise<unknown>;
+};
+
+export function TransactionHistoryTable({
+ transactions,
+ hasMore,
+ isLoadingMore,
+ isLoadMoreError,
+ onLoadMore,
+}: Props) {
+ const { selectedID, toggleReceipt, selectRelated } =
+ useReceiptSelection(transactions);
+ const loadMoreID = useId();
+ const endID = useId();
+
+ async function loadOlder(event: MouseEvent<HTMLButtonElement>) {
+ const restoreFocus = document.activeElement === event.currentTarget;
+ await onLoadMore();
+ if (restoreFocus)
+ requestAnimationFrame(() => {
+ const target =
+ document.getElementById(loadMoreID) || document.getElementById(endID);
+ target?.focus({ preventScroll: true });
+ });
+ }
+ return (
+ <div className="overflow-hidden rounded-large border border-zinc-200 bg-white shadow-subtle">
+ <table
+ className="w-full table-fixed border-collapse text-left"
+ aria-label="Automation credit transactions"
+ >
+ <colgroup>
+ <col />
+ <col className="w-0 sm:w-32" />
+ <col className="w-24" />
+ <col className="w-12 sm:w-24" />
+ </colgroup>
+ <thead className="border-b border-zinc-200 bg-zinc-50">
+ <tr>
+ <th scope="col" className="py-3 pl-3 pr-2 sm:pl-5">
+ <Text variant="small-medium" as="span" className="text-zinc-600">
+ Activity
+ </Text>
+ </th>
+ <th scope="col" className="p-0 sm:px-2 sm:py-3">
+ <Text
+ variant="small-medium"
+ as="span"
+ className="sr-only text-zinc-600 sm:not-sr-only"
+ >
+ Last activity
+ </Text>
+ </th>
+ <th scope="col" className="px-2 py-3 text-right">
+ <Text variant="small-medium" as="span" className="text-zinc-600">
+ Amount
+ </Text>
+ </th>
+ <th scope="col">
+ <span className="sr-only">Details</span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {transactions.map((transaction) => (
+ <TransactionRow
+ key={transaction.id}
+ transaction={transaction}
+ open={selectedID === transaction.id}
+ onToggle={toggleReceipt}
+ loadedTransactions={transactions}
+ onSelectRelated={selectRelated}
+ />
+ ))}
+ </tbody>
+ </table>
+ <div className="flex flex-wrap items-center justify-between gap-3 px-3 py-3 sm:px-5">
+ <Text variant="small" className="text-zinc-600">
+ Latest charges and credits first
+ </Text>
+ {hasMore ? (
+ <Button
+ id={loadMoreID}
+ variant="secondary"
+ size="small"
+ className="min-h-11 min-w-0"
+ loading={isLoadingMore}
+ onClick={(event) => void loadOlder(event)}
+ >
+ {isLoadMoreError ? "Retry loading more" : "Load more"}
+ </Button>
+ ) : (
+ <Text
+ variant="small"
+ id={endID}
+ tabIndex={-1}
+ className="text-zinc-600 focus:outline-none"
+ >
+ End of history
+ </Text>
+ )}
+ {isLoadMoreError && (
+ <Text variant="small" role="alert" className="w-full text-zinc-600">
+ We couldn’t load older transactions. Your loaded history is still
+ available.
+ </Text>
+ )}
+ </div>
+ <Text variant="small" className="sr-only" role="status">
+ {isLoadingMore
+ ? "Loading older transactions"
+ : `${transactions.length} transactions loaded`}
+ </Text>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionReceipt.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionReceipt.tsx
new file mode 100644
index 0000000000..42ac2996e5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionReceipt.tsx
@@ -0,0 +1,56 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { activityName, receiptNote, type Transaction } from "../helpers";
+import { ReceiptBreakdown } from "./ReceiptBreakdown";
+import { ReceiptEntries } from "./ReceiptEntries";
+import { ReceiptMetadata } from "./ReceiptMetadata";
+import { ReceiptRelations } from "./ReceiptRelations";
+
+type Props = {
+ transaction: Transaction;
+ receiptID: string;
+ loadedTransactions: Transaction[];
+ onSelectRelated: (executionID: string) => void;
+};
+
+export function TransactionReceipt({
+ transaction,
+ receiptID,
+ loadedTransactions,
+ onSelectRelated,
+}: Props) {
+ const hasRelations =
+ !!transaction.parent_execution_id ||
+ !!transaction.related_executions?.length ||
+ !!transaction.related_executions_has_more;
+ const heading =
+ transaction.activity_type === "agent_run"
+ ? `Charges for this run${hasRelations ? " only" : ""}`
+ : transaction.activity_type === "copilot_tools"
+ ? "Tool usage in this conversation"
+ : "Credit balance change";
+ const note = receiptNote(transaction);
+ return (
+ <section
+ id={receiptID}
+ aria-label={`${activityName(transaction)} credit receipt`}
+ className="mx-2 mb-3 rounded-medium border border-zinc-100 bg-zinc-50 p-3 sm:mx-4 sm:p-5"
+ >
+ <Text variant="body-medium" as="h3">
+ {heading}
+ </Text>
+ <ReceiptBreakdown transaction={transaction} />
+ {note && (
+ <Text variant="small" className="mt-3 text-zinc-600">
+ {note}
+ </Text>
+ )}
+ <ReceiptRelations
+ transaction={transaction}
+ loadedTransactions={loadedTransactions}
+ onSelectRelated={onSelectRelated}
+ />
+ <ReceiptMetadata transaction={transaction} />
+ <ReceiptEntries transaction={transaction} />
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionRow.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionRow.tsx
new file mode 100644
index 0000000000..57787306a4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/components/TransactionRow.tsx
@@ -0,0 +1,146 @@
+import { useId } from "react";
+import {
+ ArrowDown01Icon,
+ ArrowUp01Icon,
+ CreditCardIcon,
+ Robot01Icon,
+} from "@hugeicons/core-free-icons";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Link } from "@/components/atoms/Link/Link";
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+import {
+ activityDescription,
+ activityName,
+ formatActivityDate,
+ isRunActive,
+ libraryHref,
+ statusLabel,
+ type Transaction,
+} from "../helpers";
+import { TransactionAmount } from "./TransactionAmount";
+import { TransactionReceipt } from "./TransactionReceipt";
+
+type Props = {
+ transaction: Transaction;
+ open: boolean;
+ onToggle: (id: string) => void;
+ loadedTransactions: Transaction[];
+ onSelectRelated: (executionID: string) => void;
+};
+
+export function TransactionRow({
+ transaction,
+ open,
+ onToggle,
+ loadedTransactions,
+ onSelectRelated,
+}: Props) {
+ const receiptID = useId();
+ const posted = formatActivityDate(transaction.transaction_time);
+ return (
+ <>
+ <tr className="border-b border-zinc-100">
+ <td className="py-4 pl-3 pr-2 sm:pl-5">
+ <TransactionActivity transaction={transaction} />
+ </td>
+ <td className="p-0 sm:px-2 sm:py-4">
+ <Text
+ variant="small"
+ title={posted.full}
+ unmask={false}
+ className="hidden sm:block"
+ >
+ {posted.date}
+ <span className="mt-1 block text-zinc-600">{posted.time}</span>
+ </Text>
+ </td>
+ <td className="px-2 py-4 text-right">
+ <TransactionAmount amount={transaction.amount} />
+ {isRunActive(transaction) && (
+ <Text variant="small" className="text-zinc-600">
+ so far
+ </Text>
+ )}
+ </td>
+ <td className="px-1 py-3 sm:pr-3">
+ <Button
+ id={`transaction-details-${transaction.id}`}
+ variant="ghost"
+ size="small"
+ unmask={false}
+ className="min-h-11 w-full min-w-0 px-1 text-zinc-600"
+ onClick={() => onToggle(transaction.id)}
+ aria-label={`${open ? "Close" : "Open"} details for ${activityName(transaction)}, ${posted.date} at ${posted.time}`}
+ aria-expanded={open}
+ aria-controls={open ? receiptID : undefined}
+ rightIcon={
+ <Icon icon={open ? ArrowUp01Icon : ArrowDown01Icon} size={16} />
+ }
+ >
+ <span className="hidden sm:inline">Details</span>
+ </Button>
+ </td>
+ </tr>
+ {open && (
+ <tr className="border-b border-zinc-100">
+ <td colSpan={4} className="p-0">
+ <TransactionReceipt
+ transaction={transaction}
+ receiptID={receiptID}
+ loadedTransactions={loadedTransactions}
+ onSelectRelated={onSelectRelated}
+ />
+ </td>
+ </tr>
+ )}
+ </>
+ );
+}
+
+function TransactionActivity({ transaction }: { transaction: Transaction }) {
+ const href = libraryHref(transaction.library_agent_id);
+ const name = activityName(transaction);
+ const posted = formatActivityDate(transaction.transaction_time);
+ const agent = transaction.activity_type === "agent_run";
+ return (
+ <div className="flex items-center gap-3">
+ <span
+ className={cn(
+ "hidden size-8 shrink-0 items-center justify-center rounded-small sm:flex",
+ agent ? "bg-purple-50 text-purple-700" : "bg-zinc-100 text-zinc-600",
+ )}
+ >
+ <Icon icon={agent ? Robot01Icon : CreditCardIcon} size={16} />
+ </span>
+ <div className="min-w-0">
+ {href ? (
+ <Link
+ href={href}
+ className="inline-flex min-h-6 items-center break-words text-purple-700"
+ >
+ {name}
+ </Link>
+ ) : (
+ <Text variant="body-medium" unmask={false} className="break-words">
+ {name}
+ </Text>
+ )}
+ <Text variant="small" unmask={false} className="mt-1 text-zinc-600">
+ {isRunActive(transaction)
+ ? statusLabel(transaction.execution_status || "")
+ : activityDescription(transaction)}
+ </Text>
+ <Text
+ variant="small"
+ unmask={false}
+ title={posted.full}
+ className="mt-2 text-zinc-600 sm:hidden"
+ >
+ {posted.date} · {posted.time}
+ </Text>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/helpers.ts
new file mode 100644
index 0000000000..a248cbd26a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/helpers.ts
@@ -0,0 +1,139 @@
+import type { CreditTransactionItem } from "@/app/api/__generated__/models/creditTransactionItem";
+import { formatCents } from "../../../helpers";
+
+export type Transaction = CreditTransactionItem & {
+ id: string;
+ amount: number;
+ transaction_type: NonNullable<CreditTransactionItem["transaction_type"]>;
+ receipt_as_of?: string | Date | null;
+};
+
+const transactionNames: Record<string, string> = {
+ TOP_UP: "Credits added",
+ GRANT: "Credits granted",
+ REFUND: "Top-up refunded",
+ SUBSCRIPTION: "Subscription payment",
+ CARD_CHECK: "Card verification",
+};
+
+export function activityName(transaction: Transaction): string {
+ if (transaction.activity_type === "agent_run")
+ return transaction.agent_name || "Agent unavailable";
+ if (transaction.activity_type === "copilot_tools")
+ return "Autopilot tool use";
+ if (transaction.activity_type === "block_usage") return "Direct block usage";
+ if (transaction.transaction_type === "USAGE")
+ return transaction.description || "Credit usage";
+ return (
+ transactionNames[transaction.transaction_type] || "Credit balance change"
+ );
+}
+
+export function activityDescription(transaction: Transaction): string {
+ if (transaction.parent_agent_name)
+ return `Part of ${transaction.parent_agent_name}`;
+ if (transaction.activity_type === "agent_run") return "Agent run";
+ if (transaction.activity_type === "copilot_tools")
+ return transaction.conversation_title || "Paid block tools";
+ if (transaction.activity_type === "block_usage")
+ return "Outside an agent run";
+ if (transaction.transaction_type === "TOP_UP") return "Credit purchase";
+ if (transaction.transaction_type === "REFUND")
+ return "Credit purchase refunded";
+ if (transaction.transaction_type === "SUBSCRIPTION")
+ return "Paid from credit balance";
+ return "Credit balance";
+}
+
+export function formatAmount(amount: number): string {
+ const sign = amount < 0 ? "−" : amount > 0 ? "+" : "";
+ return `${sign}${formatCents(Math.abs(amount))}`;
+}
+
+export function formatActivityDate(value: string | Date | null | undefined) {
+ if (!value)
+ return { date: "Unavailable", time: "", full: "Date unavailable" };
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime()))
+ return { date: "Unavailable", time: "", full: "Date unavailable" };
+ return {
+ date: date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }),
+ time: date.toLocaleTimeString(undefined, {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ }),
+ full: date.toLocaleString(undefined, {
+ dateStyle: "long",
+ timeStyle: "long",
+ }),
+ };
+}
+
+export function libraryHref(libraryID: string | null | undefined) {
+ return libraryID ? `/library/agents/${encodeURIComponent(libraryID)}` : null;
+}
+
+export function taskHref(transaction: Transaction) {
+ const agentHref = libraryHref(transaction.library_agent_id);
+ if (
+ !agentHref ||
+ !transaction.execution_available ||
+ !transaction.usage_execution_id
+ )
+ return null;
+ return `${agentHref}?activeTab=runs&activeItem=${encodeURIComponent(transaction.usage_execution_id)}`;
+}
+
+export function isRunActive(transaction: Transaction) {
+ return ["QUEUED", "RUNNING", "REVIEW", "INCOMPLETE"].includes(
+ transaction.execution_status || "",
+ );
+}
+
+export function statusLabel(status: string) {
+ const labels: Record<string, string> = {
+ QUEUED: "Queued",
+ RUNNING: "Running",
+ REVIEW: "Needs review",
+ INCOMPLETE: "Incomplete",
+ COMPLETED: "Completed",
+ FAILED: "Failed",
+ TERMINATED: "Stopped",
+ };
+ return labels[status] || "Unavailable";
+}
+
+export function receiptNote(transaction: Transaction) {
+ if (transaction.activity_type === "agent_run") {
+ if (isRunActive(transaction))
+ return "This run is still active. Charges and adjustments may continue.";
+ if (transaction.amount === 0)
+ return "No net change to your credit balance.";
+ return "Recorded charges and adjustments for this run.";
+ }
+ if (transaction.activity_type === "copilot_tools")
+ return "Paid block tools across this conversation. Subscription usage is tracked separately.";
+ if (transaction.activity_type === "block_usage")
+ return "A paid block call without an associated agent run.";
+ if (transaction.transaction_type === "REFUND")
+ return "Credits removed from your balance after the payment was refunded.";
+ if (transaction.transaction_type === "SUBSCRIPTION")
+ return "This payment was taken from your credit balance.";
+ if (transaction.amount === 0) return "No change to your credit balance.";
+ return "";
+}
+
+export function chargeLabel(type: string) {
+ const labels: Record<string, string> = {
+ usage: "Block usage",
+ execution_fee: "Execution fee",
+ adjustment: "Usage adjustment",
+ transaction: "Balance change",
+ };
+ return labels[type] || "Balance change";
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useReceiptSelection.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useReceiptSelection.ts
new file mode 100644
index 0000000000..4e31966ca6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useReceiptSelection.ts
@@ -0,0 +1,30 @@
+import { useEffect, useState } from "react";
+import type { Transaction } from "./helpers";
+
+export function useReceiptSelection(transactions: Transaction[]) {
+ const [selectedID, setSelectedID] = useState<string | null>(null);
+ const [relatedID, setRelatedID] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!relatedID) return;
+ const button = document.getElementById(`transaction-details-${relatedID}`);
+ button?.focus({ preventScroll: true });
+ button?.scrollIntoView({ block: "center" });
+ setRelatedID(null);
+ }, [relatedID]);
+
+ function toggleReceipt(id: string) {
+ setSelectedID((current) => (current === id ? null : id));
+ }
+
+ function selectRelated(executionID: string) {
+ const transaction = transactions.find(
+ (item) => item.usage_execution_id === executionID,
+ );
+ if (!transaction) return;
+ setSelectedID(transaction.id);
+ setRelatedID(transaction.id);
+ }
+
+ return { selectedID, toggleReceipt, selectRelated };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
index 76d5839f46..be65e2c813 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
@@ -1,50 +1,62 @@
"use client";
-import { useGetV1GetCreditHistory } from "@/app/api/__generated__/endpoints/credits/credits";
+import {
+ getGetV1GetCreditHistoryQueryKey,
+ getV1GetCreditHistory,
+} from "@/app/api/__generated__/endpoints/credits/credits";
import type { TransactionHistory } from "@/app/api/__generated__/models/transactionHistory";
-
-import { formatCents } from "../../../helpers";
-
-export interface TransactionRow {
- id: string;
- date: string;
- description: string;
- amount: string;
- kind: "credit" | "debit";
-}
+import { useOrgTeamStore } from "@/services/org-team/store";
+import { useInfiniteQuery } from "@tanstack/react-query";
+import type { Transaction } from "./helpers";
export function useTransactionHistoryCard() {
- const { data, isLoading, isError, refetch } = useGetV1GetCreditHistory(
- { transaction_count_limit: 50 },
- {
- query: {
- select: (res) => res.data as TransactionHistory | undefined,
- },
+ const activeOrgID = useOrgTeamStore((state) => state.activeOrgID);
+ const history = useInfiniteQuery({
+ queryKey: [...getGetV1GetCreditHistoryQueryKey(), "receipts", activeOrgID],
+ initialPageParam: undefined as string | undefined,
+ queryFn: async ({ pageParam, signal }) => {
+ const response = await getV1GetCreditHistory(
+ { transaction_count_limit: 25, cursor: pageParam },
+ { signal },
+ );
+ if (response.status !== 200)
+ throw new Error("Transaction history could not be loaded");
+ return response.data;
},
- );
-
- const transactions: TransactionRow[] = (data?.transactions ?? []).map(
- (tx, idx) => {
- const amountCents = tx.amount ?? 0;
- return {
- id:
- tx.transaction_key ??
- (tx.transaction_time
- ? `${tx.transaction_time.toString()}-${idx}`
- : `tx-${idx}`),
- date: tx.transaction_time
- ? new Date(tx.transaction_time).toLocaleDateString(undefined, {
- month: "short",
- day: "numeric",
- year: "numeric",
- })
- : "—",
- description: tx.description ?? tx.transaction_type ?? "Transaction",
- amount: `${amountCents > 0 ? "+" : ""}${formatCents(amountCents)}`,
- kind: amountCents >= 0 ? "credit" : "debit",
- };
- },
- );
+ getNextPageParam: (page) => page.next_cursor || undefined,
+ retry: false,
+ });
+ const transactions = mergeTransactions(history.data?.pages ?? []);
+ return {
+ transactions,
+ isLoading: history.isLoading,
+ isError: history.isError && !history.data,
+ isLoadingMore: history.isFetchingNextPage,
+ isLoadMoreError: history.isFetchNextPageError,
+ isRefreshError: history.isRefetchError && !history.isFetchNextPageError,
+ hasMore: !!history.hasNextPage,
+ refetch: history.refetch,
+ loadMore: history.fetchNextPage,
+ };
+}
- return { transactions, isLoading, isError, refetch };
+function mergeTransactions(pages: TransactionHistory[]): Transaction[] {
+ const transactions = new Map<string, Transaction>();
+ for (const page of pages) {
+ for (const item of page.transactions) {
+ const id =
+ item.id ||
+ item.transaction_key ||
+ `execution:${item.usage_execution_id}`;
+ if (!transactions.has(id))
+ transactions.set(id, {
+ ...item,
+ id,
+ amount: item.amount ?? 0,
+ transaction_type: item.transaction_type ?? "USAGE",
+ receipt_as_of: page.snapshot_at,
+ });
+ }
+ }
+ return Array.from(transactions.values());
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 570a6b6bd7..69d7f02f20 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -5690,6 +5690,15 @@
"default": 100,
"title": "Transaction Count Limit"
}
+ },
+ {
+ "name": "cursor",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Cursor"
+ }
}
],
"responses": {
@@ -18612,8 +18621,61 @@
"required": ["id", "provider", "type", "title", "scopes", "username"],
"title": "CredentialsMetaResponse"
},
+ "CreditHistoryCharge": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "posted_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Posted At"
+ },
+ "amount": { "type": "integer", "title": "Amount" },
+ "charge_type": {
+ "type": "string",
+ "enum": ["usage", "execution_fee", "adjustment", "transaction"],
+ "title": "Charge Type"
+ },
+ "block_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Block Name"
+ },
+ "node_execution_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Node Execution Id"
+ }
+ },
+ "type": "object",
+ "required": ["id", "posted_at", "amount", "charge_type"],
+ "title": "CreditHistoryCharge"
+ },
+ "CreditHistoryRelatedExecution": {
+ "properties": {
+ "execution_id": { "type": "string", "title": "Execution Id" },
+ "agent_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Agent Name"
+ },
+ "library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Id"
+ },
+ "execution_available": {
+ "type": "boolean",
+ "title": "Execution Available",
+ "default": false
+ },
+ "amount": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Amount"
+ }
+ },
+ "type": "object",
+ "required": ["execution_id"],
+ "title": "CreditHistoryRelatedExecution"
+ },
"CreditTransactionItem": {
"properties": {
+ "id": { "type": "string", "title": "Id", "default": "" },
"transaction_key": {
"type": "string",
"title": "Transaction Key",
@@ -18653,7 +18715,103 @@
"title": "Usage Start Time",
"default": "9999-12-31T23:59:59.999999Z"
},
- "user_id": { "type": "string", "title": "User Id" }
+ "user_id": { "type": "string", "title": "User Id" },
+ "activity_type": {
+ "type": "string",
+ "enum": ["agent_run", "copilot_tools", "block_usage", "other"],
+ "title": "Activity Type",
+ "default": "other"
+ },
+ "library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Id"
+ },
+ "agent_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Agent Name"
+ },
+ "execution_started_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Execution Started At"
+ },
+ "execution_status": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Execution Status"
+ },
+ "execution_graph_version": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Execution Graph Version"
+ },
+ "execution_available": {
+ "type": "boolean",
+ "title": "Execution Available",
+ "default": false
+ },
+ "conversation_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Conversation Id"
+ },
+ "conversation_title": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Conversation Title"
+ },
+ "parent_execution_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Execution Id"
+ },
+ "parent_agent_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Agent Name"
+ },
+ "parent_library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Library Agent Id"
+ },
+ "related_executions": {
+ "items": {
+ "$ref": "#/components/schemas/CreditHistoryRelatedExecution"
+ },
+ "type": "array",
+ "title": "Related Executions"
+ },
+ "related_executions_has_more": {
+ "type": "boolean",
+ "title": "Related Executions Has More",
+ "default": false
+ },
+ "usage_charge_amount": {
+ "type": "integer",
+ "title": "Usage Charge Amount",
+ "default": 0
+ },
+ "usage_fee_amount": {
+ "type": "integer",
+ "title": "Usage Fee Amount",
+ "default": 0
+ },
+ "usage_adjustment_amount": {
+ "type": "integer",
+ "title": "Usage Adjustment Amount",
+ "default": 0
+ },
+ "charges": {
+ "items": { "$ref": "#/components/schemas/CreditHistoryCharge" },
+ "type": "array",
+ "title": "Charges"
+ },
+ "charges_total_count": {
+ "type": "integer",
+ "title": "Charges Total Count",
+ "default": 0
+ },
+ "charges_truncated": {
+ "type": "boolean",
+ "title": "Charges Truncated",
+ "default": false
+ }
},
"type": "object",
"required": ["user_id"],
@@ -28398,6 +28556,17 @@
{ "type": "null" }
],
"title": "Next Transaction Time"
+ },
+ "next_cursor": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Next Cursor"
+ },
+ "snapshot_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Snapshot At"
}
},
"type": "object",