Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): expose per-task usage costs (#81008)

Adam Bowkerd4556018cf04
diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.py
index 0f028cdb0da8..2ad4cad813e1 100644
--- a/products/tasks/backend/facade/billing.py
+++ b/products/tasks/backend/facade/billing.py
@@ -11,11 +11,25 @@ from products.tasks.backend.logic.services.sandbox_usage import (
get_billable_sandbox_compute_usage_by_team,
get_task_sandbox_usage_by_team,
)
+from products.tasks.backend.logic.services.task_usage import (
+ TASK_USAGE_SIGNATURE_HEADER,
+ TASK_USAGE_TIMESTAMP_HEADER,
+ TaskTokenUsageUnavailable,
+ TaskUsage,
+ get_local_task_token_cost,
+ get_task_usage,
+)
__all__ = [
"ComputeRateCardConfigurationError",
"SandboxComputeUsageByTeam",
"SandboxUsageByTeam",
+ "TaskUsage",
+ "TaskTokenUsageUnavailable",
+ "TASK_USAGE_SIGNATURE_HEADER",
+ "TASK_USAGE_TIMESTAMP_HEADER",
"get_billable_sandbox_compute_usage_by_team",
+ "get_local_task_token_cost",
"get_task_sandbox_usage_by_team",
+ "get_task_usage",
]
diff --git a/products/tasks/backend/logic/services/task_usage.py b/products/tasks/backend/logic/services/task_usage.py
new file mode 100644
index 000000000000..3b1bb3482397
--- /dev/null
+++ b/products/tasks/backend/logic/services/task_usage.py
@@ -0,0 +1,183 @@
+import hmac
+import json
+import time
+import hashlib
+from dataclasses import dataclass
+from datetime import datetime
+from decimal import Decimal
+from uuid import UUID
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db.models import Q
+from django.utils import timezone
+
+import requests
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.tasks.backend.logic.services.sandbox_pricing import (
+ COMPUTE_RATE_CARDS,
+ calculate_sandbox_compute_cost,
+ validate_compute_rate_cards,
+)
+from products.tasks.backend.models import SandboxSession, Task, TaskClientProvenance
+
+TASK_USAGE_SIGNATURE_HEADER = "X-PostHog-Task-Usage-Signature"
+TASK_USAGE_TIMESTAMP_HEADER = "X-PostHog-Task-Usage-Timestamp"
+TASK_USAGE_CROSS_REGION_TIMEOUT_SECONDS = (3, 15)
+TASK_USAGE_INTERNAL_PATH = "/api/code/internal/task_usage/"
+TASK_TOKEN_COST_CACHE_TIMEOUT_SECONDS = 60
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass(frozen=True)
+class TaskUsage:
+ token_cost_usd: Decimal
+ compute_cost_usd: Decimal
+
+ @property
+ def total_cost_usd(self) -> Decimal:
+ return self.token_cost_usd + self.compute_cost_usd
+
+
+def get_task_usage(*, team_id: int, task_id: UUID, task_created_at: datetime) -> TaskUsage:
+ return TaskUsage(
+ token_cost_usd=_get_task_token_cost(task_id=task_id, task_created_at=task_created_at),
+ compute_cost_usd=_get_task_compute_cost(team_id=team_id, task_id=task_id),
+ )
+
+
+class TaskTokenUsageUnavailable(Exception):
+ pass
+
+
+@frozen
+class TaskUsageRequestSignature:
+ signature: str
+ timestamp: str
+
+
+def sign_task_usage_request(body: bytes, secret: str, *, timestamp: int | None = None) -> TaskUsageRequestSignature:
+ request_timestamp = str(int(time.time()) if timestamp is None else timestamp)
+ signed_value = f"v0:{request_timestamp}:{body.decode('utf-8')}"
+ signature = hmac.new(secret.encode(), signed_value.encode(), hashlib.sha256).hexdigest()
+ return TaskUsageRequestSignature(signature=signature, timestamp=request_timestamp)
+
+
+def _get_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
+ cache_key = _task_token_cost_cache_key(task_id=task_id, task_created_at=task_created_at)
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return Decimal(str(cached))
+
+ if settings.CLOUD_DEPLOYMENT == "EU":
+ token_cost = _get_cross_region_task_token_cost(task_id=task_id, task_created_at=task_created_at)
+ else:
+ token_cost = get_local_task_token_cost(task_id=task_id, task_created_at=task_created_at)
+ cache.set(cache_key, str(token_cost), timeout=TASK_TOKEN_COST_CACHE_TIMEOUT_SECONDS)
+ return token_cost
+
+
+def _task_token_cost_cache_key(*, task_id: UUID, task_created_at: datetime) -> str:
+ return f"task_token_cost:v1:{task_id}:{task_created_at.isoformat()}"
+
+
+def _get_cross_region_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
+ secret = settings.PERSONAL_SPEND_CROSS_REGION_SECRET
+ if not secret:
+ logger.error("task_usage.cross_region_not_configured")
+ raise TaskTokenUsageUnavailable("Cross-region task usage is not configured")
+
+ body = json.dumps({"task_id": str(task_id), "task_created_at": task_created_at.isoformat()}).encode()
+ signed = sign_task_usage_request(body, secret)
+ target = f"{settings.SITE_URL if settings.DEBUG else 'https://us.posthog.com'}{TASK_USAGE_INTERNAL_PATH}"
+ try:
+ response = requests.post(
+ target,
+ data=body,
+ headers={
+ "Content-Type": "application/json",
+ TASK_USAGE_SIGNATURE_HEADER: signed.signature,
+ TASK_USAGE_TIMESTAMP_HEADER: signed.timestamp,
+ },
+ timeout=TASK_USAGE_CROSS_REGION_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ return Decimal(str(response.json()["token_cost_usd"]))
+ except (requests.RequestException, ValueError, KeyError, TypeError) as error:
+ logger.exception("task_usage.cross_region_request_failed", error_type=type(error).__name__)
+ raise TaskTokenUsageUnavailable("Cross-region task usage is unavailable") from error
+
+
+def get_local_task_token_cost(*, task_id: UUID, task_created_at: datetime) -> Decimal:
+ query = parse_select(
+ """
+ SELECT round(sum(toFloat(properties.$ai_total_cost_usd)), 6)
+ FROM events
+ WHERE equals(event, '$ai_generation')
+ AND greaterOrEquals(timestamp, {task_created_at})
+ AND equals(properties.ai_product, 'posthog_code')
+ AND (
+ equals(properties.task_id, {task_id})
+ OR equals(properties.$ai_session_id, {task_id})
+ )
+ """
+ )
+ with tags_context(product=Product.POSTHOG_CODE, feature=Feature.QUERY):
+ result = execute_hogql_query(
+ query=query,
+ placeholders={
+ "task_created_at": ast.Constant(value=task_created_at),
+ "task_id": ast.Constant(value=str(task_id)),
+ },
+ team=Team.objects.get(pk=settings.LLM_ANALYTICS_INTERNAL_TEAM_ID),
+ query_type="TaskUsageTokenCost",
+ )
+ value = (result.results or [(0,)])[0][0]
+ return Decimal(str(value or 0))
+
+
+def _get_task_compute_cost(*, team_id: int, task_id: UUID) -> Decimal:
+ if not COMPUTE_RATE_CARDS:
+ return Decimal(0)
+
+ rate_cards = validate_compute_rate_cards(COMPUTE_RATE_CARDS)
+ calculated_at = timezone.now()
+ sessions = (
+ SandboxSession.objects.for_team(team_id)
+ .filter(
+ task_run__task_id=task_id,
+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,
+ user_attributed_at__isnull=False,
+ )
+ .filter(
+ Q(origin_product=Task.OriginProduct.USER_CREATED)
+ | Q(
+ origin_product=Task.OriginProduct.LOOP,
+ task_run__task__loop__isnull=False,
+ task_run__task__loop__internal=False,
+ )
+ )
+ )
+ return sum(
+ (
+ calculate_sandbox_compute_cost(
+ session,
+ rate_cards[0].effective_at,
+ calculated_at,
+ calculated_at=calculated_at,
+ rate_cards=rate_cards,
+ ).total_cost_usd
+ for session in sessions.iterator()
+ ),
+ Decimal(0),
+ )
diff --git a/products/tasks/backend/logic/services/tests/test_task_usage.py b/products/tasks/backend/logic/services/tests/test_task_usage.py
new file mode 100644
index 000000000000..f4da7aada498
--- /dev/null
+++ b/products/tasks/backend/logic/services/tests/test_task_usage.py
@@ -0,0 +1,152 @@
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from types import SimpleNamespace
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
+
+from products.tasks.backend.logic.services import task_usage
+from products.tasks.backend.logic.services.sandbox_pricing import ComputeRateCard
+from products.tasks.backend.models import SandboxSession, Task, TaskClientProvenance, TaskRun
+
+
+class TestTaskUsageQueryTagging(SimpleTestCase):
+ def test_token_cost_query_is_attributed_to_posthog_code(self) -> None:
+ captured_tags: dict[str, object] = {}
+
+ def capture_query_tags(**kwargs: object) -> SimpleNamespace:
+ tags = get_query_tags()
+ captured_tags["product"] = tags.product
+ captured_tags["feature"] = tags.feature
+ return SimpleNamespace(results=[(0,)])
+
+ with (
+ self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=1),
+ patch.object(task_usage.Team.objects, "get", return_value=object()),
+ patch.object(task_usage, "execute_hogql_query", side_effect=capture_query_tags),
+ ):
+ task_usage.get_local_task_token_cost(
+ task_id=UUID("00000000-0000-0000-0000-000000000001"),
+ task_created_at=datetime(2026, 8, 1, tzinfo=UTC),
+ )
+
+ assert captured_tags == {"product": Product.POSTHOG_CODE, "feature": Feature.QUERY}
+
+
+class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Usage task",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ client_provenance=TaskClientProvenance.POSTHOG_DESKTOP,
+ )
+
+ def test_token_cost_only_includes_generations_for_the_task_and_product(self) -> None:
+ for task_id, product, cost in (
+ (str(self.task.id), "posthog_code", 2.5),
+ (str(self.task.id), "background_agents", 10),
+ ("00000000-0000-0000-0000-000000000001", "posthog_code", 20),
+ ):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=str(self.user.distinct_id),
+ timestamp=self.task.created_at + timedelta(seconds=1),
+ properties={"task_id": task_id, "ai_product": product, "$ai_total_cost_usd": cost},
+ )
+ flush_persons_and_events()
+
+ with self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id):
+ usage = task_usage.get_task_usage(
+ team_id=self.team.id,
+ task_id=self.task.id,
+ task_created_at=self.task.created_at,
+ )
+
+ assert usage.token_cost_usd == Decimal("2.5")
+ assert usage.compute_cost_usd == 0
+ assert usage.total_cost_usd == Decimal("2.5")
+
+ def test_compute_cost_only_includes_billable_desktop_sessions(self) -> None:
+ rate_start = datetime(2026, 8, 1, tzinfo=UTC)
+ rate_card = ComputeRateCard(
+ version="test",
+ effective_at=rate_start,
+ expires_at=None,
+ cpu_core_second_usd=Decimal("0.01"),
+ memory_gib_second_usd=Decimal("0.01"),
+ )
+ for provenance in (TaskClientProvenance.POSTHOG_DESKTOP, None):
+ run = TaskRun.objects.create(task=self.task, team=self.team)
+ SandboxSession.objects.unscoped().create(
+ team=self.team,
+ task_run=run,
+ sandbox_id=f"sandbox-{provenance or 'untrusted'}",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ client_provenance=provenance,
+ cpu_cores=1,
+ memory_gb=1,
+ ttl_seconds=3600,
+ burstable=False,
+ created_at=rate_start,
+ ttl_expires_at=rate_start + timedelta(hours=1),
+ user_attributed_at=rate_start,
+ ended_at=rate_start + timedelta(seconds=10),
+ )
+
+ with (
+ patch.object(task_usage, "COMPUTE_RATE_CARDS", (rate_card,)),
+ patch.object(task_usage, "_get_task_token_cost", return_value=Decimal(0)),
+ patch.object(task_usage.timezone, "now", return_value=rate_start + timedelta(minutes=1)),
+ ):
+ usage = task_usage.get_task_usage(
+ team_id=self.team.id,
+ task_id=self.task.id,
+ task_created_at=self.task.created_at,
+ )
+
+ assert usage.compute_cost_usd == Decimal("0.20")
+
+ def test_eu_token_cost_uses_cross_region_source(self) -> None:
+ with (
+ self.settings(
+ CLOUD_DEPLOYMENT="EU",
+ PERSONAL_SPEND_CROSS_REGION_SECRET="secret",
+ DEBUG=False,
+ ),
+ patch.object(task_usage.requests, "post") as post,
+ ):
+ post.return_value.json.return_value = {"token_cost_usd": 1.25}
+ token_cost = task_usage._get_task_token_cost(
+ task_id=self.task.id,
+ task_created_at=self.task.created_at,
+ )
+
+ assert token_cost == Decimal("1.25")
+ assert post.call_args.args[0] == "https://us.posthog.com/api/code/internal/task_usage/"
+
+ def test_eu_token_cost_is_unavailable_without_cross_region_secret(self) -> None:
+ with (
+ self.settings(CLOUD_DEPLOYMENT="EU", PERSONAL_SPEND_CROSS_REGION_SECRET=""),
+ self.assertRaises(task_usage.TaskTokenUsageUnavailable),
+ ):
+ task_usage._get_task_token_cost(task_id=self.task.id, task_created_at=self.task.created_at)
+
+ def test_token_cost_is_cached(self) -> None:
+ with patch.object(task_usage, "get_local_task_token_cost", return_value=Decimal("1.25")) as get_cost:
+ first = task_usage._get_task_token_cost(task_id=self.task.id, task_created_at=self.task.created_at)
+ second = task_usage._get_task_token_cost(task_id=self.task.id, task_created_at=self.task.created_at)
+
+ assert first == second == Decimal("1.25")
+ get_cost.assert_called_once()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 4bb59c291151..31fd1f28df27 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1951,6 +1951,23 @@ class TaskArtifactsResponseSerializer(serializers.Serializer):
artifacts = TaskArtifactSerializer(many=True, help_text="Artifacts and canvases linked to this task.")
+class TaskUsageResponseSerializer(serializers.Serializer):
+ token_cost_usd = serializers.FloatField(help_text="Estimated model cost attributed to this task in US dollars.")
+ compute_cost_usd = serializers.FloatField(
+ help_text="Estimated cloud compute cost attributed to this task in US dollars."
+ )
+ total_cost_usd = serializers.FloatField(help_text="Estimated total cost attributed to this task in US dollars.")
+
+
+class InternalTaskUsageRequestSerializer(serializers.Serializer):
+ task_id = serializers.UUIDField(help_text="Task identifier used to attribute model generations.")
+ task_created_at = serializers.DateTimeField(help_text="Lower timestamp bound for attributed model generations.")
+
+
+class InternalTaskUsageResponseSerializer(serializers.Serializer):
+ token_cost_usd = serializers.FloatField(help_text="Estimated model cost attributed to this task in US dollars.")
+
+
class TaskCommentsQuerySerializer(serializers.Serializer):
artifact_id = serializers.CharField(
required=False, max_length=72, help_text="Artifact id returned by the artifacts endpoint."
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index f62aaed2960f..9e43ca559d80 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -21,7 +21,14 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_sche
from rest_framework import status, viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
-from rest_framework.exceptions import NotAuthenticated, NotFound, ParseError, PermissionDenied, ValidationError
+from rest_framework.exceptions import (
+ APIException,
+ NotAuthenticated,
+ NotFound,
+ ParseError,
+ PermissionDenied,
+ ValidationError,
+)
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import BaseParser
from rest_framework.permissions import IsAuthenticated
@@ -63,6 +70,7 @@ from products.tasks.backend.facade.access import (
compute_quota_limit_response,
usage_limit_response,
)
+from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_task_usage
from products.tasks.backend.facade.client_provenance import get_task_client_provenance
from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceeded
from products.tasks.backend.facade.metrics import (
@@ -157,6 +165,7 @@ from products.tasks.backend.presentation.serializers import (
TaskStagedArtifactsPrepareUploadResponseSerializer,
TaskSummariesRequestSerializer,
TaskSummarySerializer,
+ TaskUsageResponseSerializer,
TaskWriteSerializer,
WarmTaskRequestSerializer,
WarmTaskResponseSerializer,
@@ -279,6 +288,12 @@ def _parse_slack_thread_url(url: str) -> tuple[str, str] | None:
return channel, f"{raw_ts[:-6]}.{raw_ts[-6:]}"
+class TaskUsageUpstreamUnavailable(APIException):
+ status_code = status.HTTP_502_BAD_GATEWAY
+ default_detail = "Task usage is temporarily unavailable."
+ default_code = "task_usage_upstream_unavailable"
+
+
@extend_schema(tags=["tasks"])
class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
@@ -394,6 +409,31 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
return Response(TaskSerializer(task).data)
+ @extend_schema(
+ operation_id="tasks_usage_retrieve",
+ responses={200: TaskUsageResponseSerializer},
+ summary="Get task usage",
+ description="Return estimated model and cloud compute costs attributed to a task.",
+ )
+ @action(detail=True, methods=["get"], url_path="usage", required_scopes=["task:read"])
+ def usage(self, request, pk=None, **kwargs):
+ task = tasks_facade.get_task_detail(pk, self.team_id, self._user_id())
+ if task is None or task.created_at is None:
+ raise NotFound()
+ try:
+ usage = get_task_usage(team_id=self.team_id, task_id=task.id, task_created_at=task.created_at)
+ except TaskTokenUsageUnavailable as error:
+ raise TaskUsageUpstreamUnavailable() from error
+ return Response(
+ TaskUsageResponseSerializer(
+ {
+ "token_cost_usd": usage.token_cost_usd,
+ "compute_cost_usd": usage.compute_cost_usd,
+ "total_cost_usd": usage.total_cost_usd,
+ }
+ ).data
+ )
+
@extend_schema(operation_id="tasks_artifacts_list", responses=TaskArtifactsResponseSerializer)
@action(detail=True, methods=["get"], url_path="artifacts", required_scopes=["task:read"])
def artifacts(self, request, pk=None, **kwargs):
diff --git a/products/tasks/backend/presentation/views/task_usage_api.py b/products/tasks/backend/presentation/views/task_usage_api.py
new file mode 100644
index 000000000000..fa894c5f669b
--- /dev/null
+++ b/products/tasks/backend/presentation/views/task_usage_api.py
@@ -0,0 +1,57 @@
+from typing import Any
+
+from django.conf import settings
+from django.contrib.auth.models import AnonymousUser
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import exceptions, permissions, status, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import WebhookSignatureAuthentication
+
+from products.tasks.backend.facade.billing import (
+ TASK_USAGE_SIGNATURE_HEADER,
+ TASK_USAGE_TIMESTAMP_HEADER,
+ get_local_task_token_cost,
+)
+from products.tasks.backend.presentation.serializers import (
+ InternalTaskUsageRequestSerializer,
+ InternalTaskUsageResponseSerializer,
+)
+
+
+class TaskUsageCrossRegionAuthentication(WebhookSignatureAuthentication):
+ def get_signature_header(self) -> str:
+ return TASK_USAGE_SIGNATURE_HEADER
+
+ def get_timestamp_header(self) -> str:
+ return TASK_USAGE_TIMESTAMP_HEADER
+
+ def build_hmac_input(self, timestamp: str, body: str) -> str:
+ return f"v0:{timestamp}:{body}"
+
+ def get_signing_secret(self, request: Request) -> str | None:
+ return settings.PERSONAL_SPEND_CROSS_REGION_SECRET or None
+
+ def authenticate(self, request: Request) -> tuple[AnonymousUser, Any] | None:
+ try:
+ return super().authenticate(request)
+ except UnicodeDecodeError:
+ raise exceptions.AuthenticationFailed("Invalid request body encoding.")
+
+
+class InternalTaskUsageViewSet(viewsets.ViewSet):
+ authentication_classes = [TaskUsageCrossRegionAuthentication]
+ permission_classes = [permissions.AllowAny]
+ throttle_classes = []
+
+ @extend_schema(exclude=True)
+ def create(self, request: Request) -> Response:
+ serializer = InternalTaskUsageRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ token_cost = get_local_task_token_cost(**serializer.validated_data)
+ return Response(
+ InternalTaskUsageResponseSerializer({"token_cost_usd": token_cost}).data,
+ status=status.HTTP_200_OK,
+ )
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index 89969a8346ea..e031ac8188a2 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -4,6 +4,7 @@ import products.tasks.backend.presentation.views.api as tasks
import products.tasks.backend.presentation.views.loops as loops
import products.tasks.backend.presentation.views.seat_api as seats
import products.tasks.backend.presentation.views.channels_api as channels
+import products.tasks.backend.presentation.views.task_usage_api as task_usage
import products.tasks.backend.presentation.views.sandbox_pricing_api as sandbox_pricing
@@ -45,3 +46,4 @@ def register_routes(routers: RouterRegistry) -> None:
r"code/sandbox-pricing", sandbox_pricing.SandboxComputePricingViewSet, "sandbox_compute_pricing"
)
routers.root.register(r"seats", seats.SeatViewSet, "seats")
+ routers.root.register(r"code/internal/task_usage", task_usage.InternalTaskUsageViewSet, "internal_task_usage")
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index aff085d5a23d..cab8283c4ee6 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -6,6 +6,7 @@ import asyncio
import hashlib
from collections.abc import AsyncGenerator, Iterator
from datetime import timedelta
+from decimal import Decimal
from typing import Any, ClassVar, cast
from urllib.parse import quote
@@ -57,6 +58,7 @@ from products.tasks.backend.logic.services.staged_artifacts import (
cache_task_staged_artifact,
get_task_staged_artifacts,
)
+from products.tasks.backend.logic.services.task_usage import TaskTokenUsageUnavailable, TaskUsage
from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamEntryOrKeepalive,
@@ -1098,6 +1100,35 @@ class TestTaskAPI(BaseTaskAPITest):
client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")
return client
+ @patch("products.tasks.backend.presentation.views.api.get_task_usage")
+ def test_usage_returns_task_cost_breakdown(self, mock_get_task_usage: MagicMock) -> None:
+ task = self.create_task()
+ mock_get_task_usage.return_value = TaskUsage(
+ token_cost_usd=Decimal("12.34"),
+ compute_cost_usd=Decimal("0.56"),
+ )
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/usage/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "token_cost_usd": 12.34,
+ "compute_cost_usd": 0.56,
+ "total_cost_usd": 12.9,
+ }
+
+ @patch("products.tasks.backend.presentation.views.api.get_task_usage")
+ def test_usage_returns_bad_gateway_when_token_usage_is_unavailable(self, mock_get_task_usage: MagicMock) -> None:
+ task = self.create_task()
+ mock_get_task_usage.side_effect = TaskTokenUsageUnavailable()
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/usage/")
+
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+ body = response.json()
+ assert body["detail"] == "Task usage is temporarily unavailable."
+ assert body["code"] == "task_usage_upstream_unavailable"
+
def test_desktop_oauth_task_creation_records_trusted_provenance(self):
client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)
@@ -9026,6 +9057,7 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
[
("task:read", "GET", "/api/projects/@current/tasks/", True),
("task:read", "GET", f"/api/projects/@current/tasks/{{task_id}}/", True),
+ ("task:read", "GET", f"/api/projects/@current/tasks/{{task_id}}/usage/", True),
("task:read", "GET", f"/api/projects/@current/tasks/{{task_id}}/runs/", True),
("task:read", "GET", f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/", True),
("task:read", "GET", f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/connection_token/", False),
diff --git a/products/tasks/backend/tests/test_task_usage_api.py b/products/tasks/backend/tests/test_task_usage_api.py
new file mode 100644
index 000000000000..677c17ad9b6a
--- /dev/null
+++ b/products/tasks/backend/tests/test_task_usage_api.py
@@ -0,0 +1,37 @@
+from datetime import UTC, datetime
+from decimal import Decimal
+from uuid import UUID
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from rest_framework.parsers import JSONParser
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
+
+from products.tasks.backend.presentation.views.task_usage_api import InternalTaskUsageViewSet
+
+
+class TestInternalTaskUsageViewSet(SimpleTestCase):
+ @patch(
+ "products.tasks.backend.presentation.views.task_usage_api.get_local_task_token_cost",
+ return_value=Decimal("1.25"),
+ )
+ def test_create_returns_token_cost(self, _get_token_cost) -> None:
+ request = Request(
+ APIRequestFactory().post(
+ "/",
+ {
+ "task_id": str(UUID("00000000-0000-0000-0000-000000000001")),
+ "task_created_at": datetime(2026, 8, 1, tzinfo=UTC).isoformat(),
+ },
+ format="json",
+ ),
+ parsers=[JSONParser()],
+ )
+
+ response = InternalTaskUsageViewSet().create(request)
+
+ assert response.status_code == 200
+ assert response.data == {"token_cost_usd": 1.25}
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 0da815226e2a..acfc26fede22 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2771,6 +2771,15 @@ export interface TaskStagedArtifactsPrepareUploadResponseApi {
artifacts: TaskStagedArtifactPrepareUploadResponseApi[]
}
+export interface TaskUsageResponseApi {
+ /** Estimated model cost attributed to this task in US dollars. */
+ token_cost_usd: number
+ /** Estimated cloud compute cost attributed to this task in US dollars. */
+ compute_cost_usd: number
+ /** Estimated total cost attributed to this task in US dollars. */
+ total_cost_usd: number
+}
+
export interface PaginatedTaskRunDetailDTOListApi {
count: number
/** @nullable */
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 83b38252e578..6d9077a4611f 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -121,6 +121,7 @@ import type {
TaskSummariesRequestApi,
TaskThreadMessageDTOApi,
TaskThreadMessageWriteApi,
+ TaskUsageResponseApi,
TaskWriteApi,
TasksCommentsListParams,
TasksCommentsRetrieveParams,
@@ -1565,6 +1566,25 @@ export const tasksStagedArtifactsPrepareUploadCreate = async (
)
}
+export const getTasksUsageRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/usage/`
+}
+
+/**
+ * Return estimated model and cloud compute costs attributed to a task.
+ * @summary Get task usage
+ */
+export const tasksUsageRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<TaskUsageResponseApi> => {
+ return apiMutator<TaskUsageResponseApi>(getTasksUsageRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTasksRunsListUrl = (projectId: string, taskId: string, params?: TasksRunsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 23879b3a6a5d..e5b7e850e70b 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -652,6 +652,9 @@ tools:
tasks-update:
operation: tasks_update
enabled: false
+ tasks-usage-retrieve:
+ operation: tasks_usage_retrieve
+ enabled: false
tasks-warm-create:
operation: tasks_warm_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7388787810af..db37ef04e101 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79278,6 +79278,15 @@ export namespace Schemas {
content: string;
}
+ export interface TaskUsageResponse {
+ /** Estimated model cost attributed to this task in US dollars. */
+ token_cost_usd: number;
+ /** Estimated cloud compute cost attributed to this task in US dollars. */
+ compute_cost_usd: number;
+ /** Estimated total cost attributed to this task in US dollars. */
+ total_cost_usd: number;
+ }
+
/**
* Request body for creating or updating a task.
*