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): add chart render endpoint for task run living artifacts (#75259)

Sam Penningtondfd18a379604
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 4f6e63ef7e3e..c79920f4a88a 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1151,6 +1151,18 @@ class SubscriptionTestDeliveryThrottle(PersonalApiKeyOrUserRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+class TaskRunChartRenderThrottle(PersonalApiKeyOrUserRateThrottle):
+ # A chart render holds a worker for up to 90s, so it needs a far lower ceiling than the
+ # ClickHouse throttles. Keyed per team so rotating API keys doesn't split the bucket.
+ scope = "task_run_chart_render"
+ rate = "10/minute"
+
+ def get_cache_key(self, request, view):
+ team_id = self.safely_get_team_id_from_view(view)
+ if team_id:
+ return self.cache_format % {"scope": self.scope, "ident": f"team_{team_id}"}
+
+
class AlertTestDeliveryThrottle(PersonalApiKeyOrUserRateThrottle):
scope = "alert_test_delivery"
rate = "10/minute"
diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.py
index 440eb4a8838a..c6e69d42fe92 100644
--- a/products/exports/backend/models/exported_asset.py
+++ b/products/exports/backend/models/exported_asset.py
@@ -1,6 +1,7 @@
import secrets
from datetime import datetime, timedelta
from typing import Optional
+from urllib.parse import urlparse
from django.conf import settings
from django.db import models
@@ -257,7 +258,9 @@ def get_content_response(asset: ExportedAsset, download: bool = False, direct: b
content_type=asset.export_format,
content_disposition=content_disposition,
)
- if presigned_url:
+ # Local dev presigns against the localhost object-storage container, which external
+ # fetchers (e.g. Slack's image proxy through a tunnel) can't reach — serve bytes instead.
+ if presigned_url and not (DEBUG and urlparse(presigned_url).hostname in ("localhost", "127.0.0.1")):
return HttpResponseRedirect(presigned_url)
content = asset.content
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index b1280e719116..8e03114e61d1 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -26,6 +26,7 @@ from urllib.parse import urlparse
from uuid import UUID, uuid4
from django.conf import settings
+from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import IntegrityError, transaction
from django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, QuerySet, Subquery
from django.db.models.fields.json import KeyTextTransform
@@ -1934,6 +1935,14 @@ def _get_visible_run(run_id: str | UUID, task_id: str | UUID, team_id: int) -> T
return _task_run_queryset().filter(pk=run_id, team_id=team_id, task_id=task_id).first()
+def task_run_exists(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bool:
+ """Precheck so callers can 404 before doing expensive work (e.g. a render)."""
+ try:
+ return TaskRun.objects.filter(pk=run_id, team_id=team_id, task_id=task_id).exists()
+ except (ValueError, TypeError, DjangoValidationError):
+ return False
+
+
def task_accessible_for_run_view(
task_id: str | UUID,
team_id: int,
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index 114d7d1c494e..b8de8d105c17 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -100,6 +100,7 @@ def create_living_artifact(
source_artifact_id: str | None = None,
source_storage_path: str | None = None,
metadata: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> TaskArtifact:
_require_living_artifacts_enabled(run)
content_payload = resolve_artifact_content(
@@ -143,6 +144,7 @@ def create_living_artifact(
},
versions=[commit.version],
current_version=1,
+ export_asset_id=export_asset_id,
)
return artifact
@@ -202,6 +204,9 @@ def edit_living_artifact(
locked.adapter = commit.adapter
locked.location = commit.location
locked.metadata = {**(locked.metadata or {}), **(metadata or {}), **commit.metadata}
+ # The export only depicts the version it was rendered from, and an edit replaces the
+ # content — so drop the link rather than let the new version deliver the old picture.
+ locked.export_asset_id = None
locked.versions = versions
locked.current_version = next_version
locked.status = TaskArtifact.Status.ACTIVE
@@ -211,6 +216,7 @@ def edit_living_artifact(
"adapter",
"location",
"metadata",
+ "export_asset_id",
"versions",
"current_version",
"status",
diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
index 9fc0d6c2eefb..1d8844f8e106 100644
--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py
+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
@@ -602,6 +602,60 @@ class TestLivingArtifacts(TestCase):
mock_integration_for_mapping.assert_not_called()
self.assertFalse(TaskArtifact.objects.for_team(self.team.id).exists())
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ def test_caller_metadata_cannot_link_an_export_asset(self, mock_integration_for_mapping, _mock_flag):
+ # Anyone with task:write can pass metadata here, and the export link is what lets
+ # delivery mint an anonymous url for someone else's export. It lives in its own
+ # column, which caller metadata must never populate.
+ self._create_mapping_with_full_scopes()
+ mock_integration_for_mapping.return_value.missing_scopes.return_value = set()
+
+ artifact = create_living_artifact(
+ run=self.task_run,
+ name="chart.png",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ content_bytes=b"png-bytes",
+ content_type="image/png",
+ metadata={"export_asset_id": 4321, "posthog_url": "http://localhost:8010/project/1/insights/abc"},
+ )
+
+ self.assertIsNone(artifact.export_asset_id)
+ self.assertEqual(artifact.metadata["posthog_url"], "http://localhost:8010/project/1/insights/abc")
+
+ # Nor by retrofitting one onto an artifact that already exists.
+ updated = edit_living_artifact(
+ artifact=artifact,
+ content_bytes=b"png-bytes-v2",
+ content_type="image/png",
+ metadata={"export_asset_id": 4321},
+ )
+ self.assertIsNone(updated.export_asset_id)
+
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ def test_editing_a_chart_drops_its_export_link(self, mock_integration_for_mapping, _mock_flag):
+ # The export depicts the version it was rendered from, so a new version must not
+ # deliver the old picture.
+ self._create_mapping_with_full_scopes()
+ mock_integration_for_mapping.return_value.missing_scopes.return_value = set()
+ artifact = create_living_artifact(
+ run=self.task_run,
+ name="chart.png",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ content_bytes=b"png-bytes",
+ content_type="image/png",
+ export_asset_id=321,
+ )
+ self.assertEqual(artifact.export_asset_id, 321)
+ self.assertNotIn("export_asset_id", artifact.metadata)
+
+ updated = edit_living_artifact(artifact=artifact, content_bytes=b"png-bytes-v2", content_type="image/png")
+
+ self.assertIsNone(updated.export_asset_id)
+
@patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=False)
@patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
def test_pending_file_delivery_skipped_when_flag_off(self, mock_integration_for_mapping, _mock_flag):
diff --git a/products/tasks/backend/migrations/0077_taskartifact_export_asset_id.py b/products/tasks/backend/migrations/0077_taskartifact_export_asset_id.py
new file mode 100644
index 000000000000..d3aaea7420d9
--- /dev/null
+++ b/products/tasks/backend/migrations/0077_taskartifact_export_asset_id.py
@@ -0,0 +1,13 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("tasks", "0076_taskrun_task_run_sd_branch_idx")]
+
+ operations = [
+ migrations.AddField(
+ model_name="taskartifact",
+ name="export_asset_id",
+ field=models.BigIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index a92befbb4af7..d439c4d16f3a 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0076_taskrun_task_run_sd_branch_idx
+0077_taskartifact_export_asset_id
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index ae67bb823b78..ccfc3683c117 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2279,6 +2279,11 @@ class TaskArtifact(TeamScopedRootMixin, UUIDModel):
default=list, db_default=models.Value("[]"), help_text="Chronological artifact versions."
)
current_version = models.PositiveIntegerField(default=1, db_default=1)
+ # Slack delivery exchanges this for an anonymous image url that bypasses export access
+ # checks, so it's a dedicated column the API never accepts from callers — only the chart
+ # endpoint sets it, for an export it rendered itself. Plain id, not an FK: exports live in
+ # another product and expire on their own TTL; delivery treats a dangling id as no link.
+ export_asset_id = models.BigIntegerField(null=True, blank=True)
created_at = models.DateTimeField(default=django_timezone.now)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 53fc52c97091..13fea70e05f5 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -11,7 +11,8 @@ from django.utils import timezone as django_timezone
import posthoganalytics
from croniter import croniter
-from drf_spectacular.utils import PolymorphicProxySerializer
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
@@ -959,6 +960,46 @@ class TaskRunLivingArtifactCreateRequestSerializer(serializers.Serializer):
return attrs
+@extend_schema_field(OpenApiTypes.OBJECT)
+class InsightQueryJSONField(serializers.JSONField):
+ """Insight query JSON — freeform across query kinds, so typed as a plain object."""
+
+
+class TaskRunLivingArtifactChartRequestSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ max_length=255,
+ help_text="Chart title, also used as the delivered file name.",
+ )
+ query = InsightQueryJSONField(
+ required=False,
+ help_text=(
+ "Insight query JSON to render ad hoc, e.g. "
+ '{"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. '
+ "SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. "
+ "Provide exactly one of query or insight_id."
+ ),
+ )
+ insight_id = serializers.IntegerField(
+ required=False,
+ help_text="Numeric id of a saved insight to render. Provide exactly one of query or insight_id.",
+ )
+
+ def validate(self, attrs):
+ if (attrs.get("query") is None) == (attrs.get("insight_id") is None):
+ raise serializers.ValidationError({"query": "Provide exactly one of query or insight_id."})
+ return attrs
+
+
+class TaskRunLivingArtifactChartResponseSerializer(serializers.Serializer):
+ artifact = TaskRunLivingArtifactResponseSerializer(help_text="The living artifact registered for delivery.")
+ export_asset_id = serializers.IntegerField(help_text="Id of the rendered PNG export backing the chart.")
+ url = serializers.URLField(
+ allow_null=True,
+ required=False,
+ help_text="Link to explore this chart interactively in PostHog.",
+ )
+
+
class TaskRunLivingArtifactEditRequestSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=255,
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 863a7eecabcf..a86c5e9b5afa 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -5,13 +5,15 @@ import asyncio
import logging
from collections.abc import AsyncGenerator
from datetime import datetime
-from typing import Any
-from urllib.parse import parse_qs, urlparse
+from time import perf_counter
+from typing import TYPE_CHECKING, Any
+from urllib.parse import parse_qs, quote, urlparse
from uuid import UUID
from django.conf import settings
from django.http import HttpResponse, JsonResponse
+import pydantic
import requests as http_requests
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
@@ -19,26 +21,36 @@ 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 NotFound, ParseError, PermissionDenied, ValidationError
+from rest_framework.exceptions import NotAuthenticated, NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import BaseParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
+from posthog.schema import QuerySchemaRoot
+
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import ServerTimingsGathered
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.event_usage import groups
+from posthog.models import User
from posthog.permissions import (
APIScopePermission,
DenyMCPBuiltInAgentOAuth,
get_authenticator_scoped_team_ids,
get_authenticator_scopes,
)
-from posthog.rate_limit import CodeInviteThrottle
+from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
+from posthog.schema_migrations.upgrade import upgrade
+from posthog.utils import absolute_uri
+
+from products.exports.backend.facade.api import render_png_export
+if TYPE_CHECKING:
+ from products.exports.backend.facade.api import ExportedAsset
from products.tasks.backend.facade import (
access as tasks_access,
api as tasks_facade,
@@ -53,6 +65,7 @@ from products.tasks.backend.facade.metrics import (
observe_stream_length_on_connect,
observe_stream_resume_gap,
)
+from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
from products.tasks.backend.facade.streams import (
TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
@@ -104,6 +117,8 @@ from products.tasks.backend.presentation.serializers import (
TaskRunCreateRequestSerializer,
TaskRunDetailSerializer,
TaskRunErrorResponseSerializer,
+ TaskRunLivingArtifactChartRequestSerializer,
+ TaskRunLivingArtifactChartResponseSerializer,
TaskRunLivingArtifactCreateRequestSerializer,
TaskRunLivingArtifactEditRequestSerializer,
TaskRunLivingArtifactOpenResponseSerializer,
@@ -2363,6 +2378,10 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
run_id = self.kwargs.get("parent_lookup_run_id")
if not run_id:
raise NotFound("Run ID is required")
+ try:
+ UUID(run_id)
+ except (ValueError, TypeError):
+ raise NotFound("Run not found")
return run_id
def _ensure_task_accessible(self) -> str:
@@ -2371,7 +2390,11 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
is_read = self.action in ("list", "retrieve")
bypass_visibility = is_read and _can_bypass_visibility(self.request, self.team_id)
if not tasks_facade.task_accessible_for_run_view(
- task_id, self.team_id, getattr(self.request.user, "id", None), bypass_visibility=bypass_visibility
+ task_id,
+ self.team_id,
+ getattr(self.request.user, "id", None),
+ bypass_visibility=bypass_visibility,
+ for_control=not is_read,
):
raise NotFound("Task not found")
return task_id
@@ -2428,6 +2451,161 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
serializer = TaskRunLivingArtifactResponseSerializer(artifact)
return Response(serializer.data)
+ @validated_request(
+ request_serializer=TaskRunLivingArtifactChartRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunLivingArtifactChartResponseSerializer,
+ description="Chart rendered and registered as a living artifact",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Render or delivery failed"),
+ 403: OpenApiResponse(description="Caller may not run queries in this project"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Render an insight chart and attach it as a living artifact",
+ description=(
+ "Renders a PostHog insight (ad-hoc query JSON or a saved insight) to a PNG server-side and registers "
+ "it as a slack_file living artifact in one call. Blocks until the render finishes."
+ ),
+ strict_request_validation=True,
+ operation_id="tasks_runs_living_artifacts_chart",
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="chart",
+ # query:read because the body executes arbitrary insight queries — task:write alone
+ # must not become a data-read scope.
+ required_scopes=["task:write", "query:read"],
+ throttle_classes=[TaskRunChartRenderThrottle],
+ )
+ def chart(self, request, *args, **kwargs):
+ task_id = self._ensure_task_accessible()
+ run_id = self._run_id()
+ # Refuse unknown runs before the expensive render, like every sibling action does.
+ if not tasks_facade.task_run_exists(run_id, task_id, self.team_id):
+ raise NotFound()
+ name = request.validated_data["name"]
+ query = request.validated_data.get("query")
+ started = perf_counter()
+
+ def capture_render(*, failure_reason: str | None = None, export_asset_id: int | None = None) -> None:
+ posthoganalytics.capture(
+ distinct_id=str(getattr(request.user, "distinct_id", None) or self.team.uuid),
+ event="task_chart_render_failed" if failure_reason else "task_chart_render_succeeded",
+ properties={
+ "task_id": task_id,
+ "run_id": run_id,
+ "source": "query" if query is not None else "insight",
+ "duration_ms": round((perf_counter() - started) * 1000, 2),
+ "failure_reason": failure_reason,
+ "export_asset_id": export_asset_id,
+ },
+ groups=groups(self.organization, self.team),
+ )
+
+ if query is not None:
+ # Only InsightVizNode renders a chart deterministically; QuerySchemaRoot
+ # also admits kinds that render as table dumps or nothing.
+ if not isinstance(query, dict) or query.get("kind") != "InsightVizNode":
+ capture_render(failure_reason="unsupported_query")
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "error": "Only insight queries wrapped in an InsightVizNode can be charted — "
+ "SQL and table queries are not supported yet"
+ }
+ ).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ try:
+ # upgrade() only mutates nested nodes in place, so a migrated root must be bound
+ # or we'd validate one shape and render another.
+ query = upgrade(query)
+ QuerySchemaRoot.model_validate(query)
+ except (pydantic.ValidationError, TypeError, KeyError, ValueError):
+ capture_render(failure_reason="invalid_query")
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Invalid insight query"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ # query:read only gates tokens — session auth skips scopes entirely, and the facade's
+ # object-level check covers insight_id, not an ad-hoc export_context.
+ if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
+ raise PermissionDenied("You do not have permission to run queries in this project")
+ if not isinstance(request.user, User):
+ # Scoped-token auth guarantees a real user; the facade's access checks need one.
+ raise NotAuthenticated()
+ try:
+ asset, png = render_png_export(
+ team=self.team,
+ created_by=request.user,
+ export_context={"source": query} if query is not None else None,
+ insight_id=request.validated_data.get("insight_id"),
+ )
+ except ValueError as e:
+ capture_render(failure_reason="invalid_request")
+ return Response(TaskRunErrorResponseSerializer({"error": str(e)}).data, status=status.HTTP_400_BAD_REQUEST)
+ if png is None:
+ # asset.exception is a raw str(e) and the agent relays this field into Slack, so keep
+ # the pipeline internals in the log.
+ logger.warning("Chart render failed for asset %s on team %s: %s", asset.id, self.team_id, asset.exception)
+ capture_render(failure_reason="render_failed", export_asset_id=asset.id)
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Chart render failed"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ # Store a reference, not a url: the delivery token authenticates anonymously and
+ # bypasses the org's publicly-shared-resources setting, while metadata is readable by
+ # anyone with task:read. Slack delivery mints the url from this id when it posts.
+ # It lands in a dedicated column, not metadata, so the generic create/edit actions
+ # (whose metadata is writable by anyone with task:write) can never set it.
+ url = self._chart_url(query, asset)
+ chart_metadata: dict = {}
+ if url:
+ chart_metadata["posthog_url"] = url
+ artifact, error = tasks_facade.create_task_run_living_artifact(
+ run_id,
+ task_id,
+ self.team_id,
+ artifact={
+ "name": self._with_png_extension(name),
+ "artifact_type": TaskArtifactType.FILE,
+ "adapter": TaskArtifactAdapter.SLACK_FILE,
+ "content_type": "image/png",
+ "content_bytes": png,
+ "metadata": chart_metadata,
+ "export_asset_id": asset.id,
+ },
+ )
+ if artifact is None and error is None:
+ raise NotFound()
+ if error is not None:
+ # The render already persisted the export; without this it would sit
+ # orphaned until its own six-month expiry instead of being cleaned up now.
+ asset.delete()
+ capture_render(failure_reason="artifact_create_failed")
+ return Response(TaskRunErrorResponseSerializer({"error": error}).data, status=status.HTTP_400_BAD_REQUEST)
+ capture_render(export_asset_id=asset.id)
+ serializer = TaskRunLivingArtifactChartResponseSerializer(
+ {"artifact": artifact, "export_asset_id": asset.id, "url": url}
+ )
+ return Response(serializer.data)
+
+ @staticmethod
+ def _with_png_extension(name: str) -> str:
+ base, ext = os.path.splitext(name)
+ return name if ext.lower() == ".png" else f"{base or name}.png"
+
+ def _chart_url(self, query: dict | None, asset: "ExportedAsset") -> str | None:
+ if query is not None:
+ # absolute_uri rejects the %5C that json.dumps escapes produce, so append the payload
+ # after resolving the path (same shape as data_catalog's _deep_link).
+ return absolute_uri(f"/project/{self.team_id}/insights/new") + f"#q={quote(json.dumps(query))}"
+ if asset.insight_id and asset.insight:
+ return absolute_uri(f"/project/{self.team_id}/insights/{asset.insight.short_id}")
+ return None
+
@validated_request(
responses={
200: OpenApiResponse(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 9a9da890cdf1..a24346f52461 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -31,10 +31,12 @@ from posthog.models.user_integration import UserIntegration
from posthog.models.utils import generate_random_token_personal
from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
from posthog.storage import object_storage
+from posthog.utils import absolute_uri
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
+from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
from products.tasks.backend.logic.services.code_usage_gate import (
CodeUsageStatus,
_gateway_usage_url,
@@ -75,6 +77,7 @@ from products.tasks.backend.models import (
from products.tasks.backend.presentation.serializers import (
TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,
TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES,
+ TaskRunLivingArtifactChartRequestSerializer,
)
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
@@ -8379,6 +8382,268 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
)
+class TestLivingArtifactChartRequestValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("both", {"name": "c", "query": {"kind": "TrendsQuery"}, "insight_id": 1}),
+ ("neither", {"name": "c"}),
+ ]
+ )
+ def test_requires_exactly_one_of_query_or_insight_id(self, _name, body):
+ serializer = TaskRunLivingArtifactChartRequestSerializer(data=body)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("query", serializer.errors)
+
+
+class TestTaskRunLivingArtifactChartAPI(BaseTaskAPITest):
+ CHART_QUERY: ClassVar[dict[str, Any]] = {
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},
+ }
+ DELIVERY_URL = "https://app.dev/exporter/export-1.png?token=abc"
+
+ def _post_chart(self, scopes, body):
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ return self._post_chart_to_run(scopes, body, task=task, run_id=str(run.id))
+
+ def _auth_headers(self, scopes):
+ api_key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="chart test key",
+ secure_value=hash_key_value(api_key_value),
+ scopes=scopes,
+ )
+ self.client.force_authenticate(None)
+ return {"authorization": f"Bearer {api_key_value}"}
+
+ def _post_chart_to_run(self, scopes, body, *, task, run_id):
+ return self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run_id}/living_artifacts/chart/",
+ body,
+ format="json",
+ headers=self._auth_headers(scopes),
+ )
+
+ def _teammates_experiments_run(self):
+ # Experiments tasks are team-readable but stay creator-driven, so a teammate may read
+ # this run's artifacts and must not be able to mutate them.
+ task = Task.objects.create(
+ team=self.team,
+ created_by=self.create_organization_user("experiment-ender"),
+ title="Clean up feature flag my-experiment-flag",
+ description="Opened on experiment end",
+ origin_product=Task.OriginProduct.EXPERIMENTS,
+ )
+ return task, TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+
+ def _post_chart_with_session(self, body):
+ # Session auth skips scope enforcement, so the query-access check is the only gate here.
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ self.client.force_authenticate(self.user)
+ return self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/living_artifacts/chart/",
+ body,
+ format="json",
+ )
+
+ def _rendered_asset(self, **kwargs):
+ asset = MagicMock(id=321, exception=None, **kwargs)
+ asset.get_subscription_delivery_content_url.return_value = self.DELIVERY_URL
+ return asset
+
+ @parameterized.expand([("task_write_only", ["task:write"]), ("query_read_only", ["query:read"])])
+ def test_rejects_key_missing_either_scope(self, _name, scopes):
+ response = self._post_chart(scopes, {"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def _artifact_response(self):
+ return {
+ "id": "a1",
+ "task_id": "t1",
+ "run_id": "r1",
+ "team_id": self.team.id,
+ "name": "Chart",
+ "artifact_type": "file",
+ "adapter": "slack_file",
+ "status": "active",
+ "location": {},
+ "metadata": {},
+ "current_version": 1,
+ "versions": [],
+ }
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_facade.create_task_run_living_artifact")
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_renders_and_registers_artifact_with_both_scopes(self, mock_render, mock_create):
+ mock_asset = self._rendered_asset()
+ mock_render.return_value = (mock_asset, b"png-bytes")
+ mock_create.return_value = (self._artifact_response(), None)
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["export_asset_id"], 321)
+ mock_render.assert_called_once()
+ render_kwargs = mock_render.call_args.kwargs
+ self.assertEqual(render_kwargs["team"], self.team)
+ self.assertEqual(render_kwargs["created_by"], self.user)
+ self.assertIsNone(render_kwargs["insight_id"])
+ sent_query = render_kwargs["export_context"]["source"]
+ self.assertEqual(sent_query["kind"], "InsightVizNode")
+ self.assertEqual(sent_query["source"]["kind"], self.CHART_QUERY["source"]["kind"])
+ self.assertEqual(sent_query["source"]["series"], self.CHART_QUERY["source"]["series"])
+ expected_url = absolute_uri(f"/project/{self.team.id}/insights/new") + f"#q={quote(json.dumps(sent_query))}"
+ self.assertEqual(data["url"], expected_url)
+ # The delivery token authenticates anonymously and bypasses the org's
+ # publicly-shared-resources setting, so it must not be minted here and persisted
+ # where any task:read reader could lift it.
+ mock_asset.get_subscription_delivery_content_url.assert_not_called()
+ self.assertEqual(
+ mock_create.call_args.kwargs["artifact"],
+ {
+ "name": "Chart.png",
+ "artifact_type": TaskArtifactType.FILE,
+ "adapter": TaskArtifactAdapter.SLACK_FILE,
+ "content_type": "image/png",
+ "content_bytes": b"png-bytes",
+ "metadata": {"posthog_url": expected_url},
+ # Beside metadata, not inside it: metadata is caller-writable, and this id is
+ # what lets delivery mint an anonymous url for the asset.
+ "export_asset_id": 321,
+ },
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "dataviz_node",
+ {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "SELECT 1"}},
+ "InsightVizNode",
+ ),
+ ("bare_hogql", {"kind": "HogQLQuery", "query": "SELECT 1"}, "InsightVizNode"),
+ (
+ "datatable_node",
+ {"kind": "DataTableNode", "source": {"kind": "HogQLQuery", "query": "SELECT 1"}},
+ "InsightVizNode",
+ ),
+ ("string_query", "SELECT 1", "InsightVizNode"),
+ ("list_kind", {"kind": ["TrendsQuery"]}, "InsightVizNode"),
+ (
+ "invalid_source_kind",
+ {"kind": "InsightVizNode", "source": {"kind": "NotAQuery"}},
+ "Invalid insight query",
+ ),
+ # Reaches upgrade(), which raises TypeError comparing a str version against an int.
+ (
+ "unupgradable_version",
+ {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "version": "abc"}},
+ "Invalid insight query",
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_non_chartable_queries_rejected_before_render(self, _name, query, expected_error, mock_render):
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "query": query})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn(expected_error, response.json()["error"])
+ mock_render.assert_not_called()
+
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_unknown_run_rejected_before_render(self, mock_render):
+ response = self._post_chart_to_run(
+ ["task:write", "query:read"],
+ {"name": "Chart", "query": self.CHART_QUERY},
+ task=self.create_task(),
+ run_id="00000000-0000-0000-0000-000000000000",
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_render.assert_not_called()
+
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_render_failure_returns_typed_400(self, mock_render):
+ mock_render.return_value = (MagicMock(id=322, exception="Query exploded"), None)
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "Chart render failed")
+
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_render_value_error_surfaces_message_as_400(self, mock_render):
+ mock_render.side_effect = ValueError("Insight not found")
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "insight_id": 404})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "Insight not found")
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_facade.create_task_run_living_artifact")
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_renders_saved_insight_and_links_to_it(self, mock_render, mock_create):
+ asset = self._rendered_asset(insight_id=7)
+ asset.insight.short_id = "ins123"
+ mock_render.return_value = (asset, b"png-bytes")
+ mock_create.return_value = (self._artifact_response(), None)
+ response = self._post_chart(["task:write", "query:read"], {"name": "Saved chart", "insight_id": 7})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ expected_url = absolute_uri(f"/project/{self.team.id}/insights/ins123")
+ self.assertEqual(response.json()["url"], expected_url)
+ render_kwargs = mock_render.call_args.kwargs
+ self.assertEqual(render_kwargs["insight_id"], 7)
+ self.assertIsNone(render_kwargs["export_context"])
+ self.assertEqual(mock_create.call_args.kwargs["artifact"]["name"], "Saved chart.png")
+ self.assertEqual(
+ mock_create.call_args.kwargs["artifact"]["metadata"],
+ {"posthog_url": expected_url},
+ )
+ self.assertEqual(mock_create.call_args.kwargs["artifact"]["export_asset_id"], 321)
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_facade.create_task_run_living_artifact")
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_registration_error_returns_typed_400(self, mock_render, mock_create):
+ asset = self._rendered_asset()
+ mock_render.return_value = (asset, b"png-bytes")
+ mock_create.return_value = (None, "Slack channel not connected")
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["error"], "Slack channel not connected")
+ asset.delete.assert_called_once()
+
+ @patch("products.tasks.backend.presentation.views.api.tasks_facade.create_task_run_living_artifact")
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_run_vanishing_before_registration_returns_404(self, mock_render, mock_create):
+ mock_render.return_value = (self._rendered_asset(), b"png-bytes")
+ mock_create.return_value = (None, None)
+ response = self._post_chart(["task:write", "query:read"], {"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch("posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_resource")
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_session_auth_without_query_access_is_rejected(self, mock_render, mock_check):
+ mock_check.side_effect = lambda resource, required_level: resource != "query"
+ response = self._post_chart_with_session({"name": "Chart", "query": self.CHART_QUERY})
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ mock_render.assert_not_called()
+
+ @patch("products.tasks.backend.presentation.views.api.render_png_export")
+ def test_charting_a_readable_but_uncontrollable_run_returns_404(self, mock_render):
+ task, run = self._teammates_experiments_run()
+ response = self._post_chart_to_run(
+ ["task:write", "query:read"],
+ {"name": "Chart", "query": self.CHART_QUERY},
+ task=task,
+ run_id=str(run.id),
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_render.assert_not_called()
+
+ def test_listing_artifacts_on_a_readable_run_still_allowed(self):
+ task, run = self._teammates_experiments_run()
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/living_artifacts/",
+ headers=self._auth_headers(["task:read"]),
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+
class TestTaskRepositoryReadinessAPI(BaseTaskAPITest):
@patch("products.tasks.backend.facade.api.compute_repository_readiness")
def test_repository_readiness_endpoint(self, mock_compute):
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index e5eaea9e4ce2..47fec8799a6a 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -3251,6 +3251,35 @@ export interface TaskRunLivingArtifactEditRequestApi {
metadata?: TaskRunLivingArtifactEditRequestApiMetadata
}
+/**
+ * Insight query JSON to render ad hoc, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. Provide exactly one of query or insight_id.
+ */
+export type TaskRunLivingArtifactChartRequestApiQuery = { [key: string]: unknown }
+
+export interface TaskRunLivingArtifactChartRequestApi {
+ /**
+ * Chart title, also used as the delivered file name.
+ * @maxLength 255
+ */
+ name: string
+ /** Insight query JSON to render ad hoc, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. Provide exactly one of query or insight_id. */
+ query?: TaskRunLivingArtifactChartRequestApiQuery
+ /** Numeric id of a saved insight to render. Provide exactly one of query or insight_id. */
+ insight_id?: number
+}
+
+export interface TaskRunLivingArtifactChartResponseApi {
+ /** The living artifact registered for delivery. */
+ artifact: TaskRunLivingArtifactResponseApi
+ /** Id of the rendered PNG export backing the chart. */
+ export_asset_id: number
+ /**
+ * Link to explore this chart interactively in PostHog.
+ * @nullable
+ */
+ url?: string | null
+}
+
export type TaskThreadMessageDTOApiPayload = { [key: string]: unknown }
/**
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index dca90388ad78..1b8f6eae7d87 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -88,6 +88,8 @@ import type {
TaskRunCommandResponseApi,
TaskRunCreateRequestSchemaApi,
TaskRunDetailDTOApi,
+ TaskRunLivingArtifactChartRequestApi,
+ TaskRunLivingArtifactChartResponseApi,
TaskRunLivingArtifactCreateRequestApi,
TaskRunLivingArtifactEditRequestApi,
TaskRunLivingArtifactOpenResponseApi,
@@ -1887,6 +1889,32 @@ export const tasksRunsLivingArtifactsEdit = async (
)
}
+export const getTasksRunsLivingArtifactsChartUrl = (projectId: string, taskId: string, runId: string) => {
+ return `/api/projects/${projectId}/tasks/${taskId}/runs/${runId}/living_artifacts/chart/`
+}
+
+/**
+ * Renders a PostHog insight (ad-hoc query JSON or a saved insight) to a PNG server-side and registers it as a slack_file living artifact in one call. Blocks until the render finishes.
+ * @summary Render an insight chart and attach it as a living artifact
+ */
+export const tasksRunsLivingArtifactsChart = async (
+ projectId: string,
+ taskId: string,
+ runId: string,
+ taskRunLivingArtifactChartRequestApi: TaskRunLivingArtifactChartRequestApi,
+ options?: RequestInit
+): Promise<TaskRunLivingArtifactChartResponseApi> => {
+ return apiMutator<TaskRunLivingArtifactChartResponseApi>(
+ getTasksRunsLivingArtifactsChartUrl(projectId, taskId, runId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskRunLivingArtifactChartRequestApi),
+ }
+ )
+}
+
export const getTasksThreadMessagesListUrl = (
projectId: string,
taskId: string,
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 6983188247a7..152d14ffda8e 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -2817,6 +2817,29 @@ export const TasksRunsLivingArtifactsEditBody = /* @__PURE__ */ zod.object({
.describe('Optional metadata to merge into the artifact registry record.'),
})
+/**
+ * Renders a PostHog insight (ad-hoc query JSON or a saved insight) to a PNG server-side and registers it as a slack_file living artifact in one call. Blocks until the render finishes.
+ * @summary Render an insight chart and attach it as a living artifact
+ */
+export const tasksRunsLivingArtifactsChartBodyNameMax = 255
+
+export const TasksRunsLivingArtifactsChartBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(tasksRunsLivingArtifactsChartBodyNameMax)
+ .describe('Chart title, also used as the delivered file name.'),
+ query: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe(
+ 'Insight query JSON to render ad hoc, e.g. {\"kind\": \"InsightVizNode\", \"source\": {\"kind\": \"TrendsQuery\", ...}}. SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. Provide exactly one of query or insight_id.'
+ ),
+ insight_id: zod
+ .number()
+ .optional()
+ .describe('Numeric id of a saved insight to render. Provide exactly one of query or insight_id.'),
+})
+
/**
* API for a task's thread — the human-only side conversation around a task. Messages
* reach the agent only via the explicit send_to_agent action, gated to the task author.
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 9fb2f449e99d..db40d7e421f6 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -414,6 +414,9 @@ tools:
- created_at
- updated_at
- completed_at
+ tasks-runs-living-artifacts-chart:
+ operation: tasks_runs_living_artifacts_chart
+ enabled: false
tasks-runs-living-artifacts-create:
operation: tasks_runs_living_artifacts_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d00d67823b6e..55634d46f19d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -70806,6 +70806,91 @@ export namespace Schemas {
is_pro?: boolean;
}
+ /**
+ * Insight query JSON to render ad hoc, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. Provide exactly one of query or insight_id.
+ */
+ export type TaskRunLivingArtifactChartRequestQuery = { [key: string]: unknown };
+
+ export interface TaskRunLivingArtifactChartRequest {
+ /**
+ * Chart title, also used as the delivered file name.
+ * @maxLength 255
+ */
+ name: string;
+ /** Insight query JSON to render ad hoc, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}. SQL queries (DataVisualizationNode, HogQLQuery) are not supported yet. Provide exactly one of query or insight_id. */
+ query?: TaskRunLivingArtifactChartRequestQuery;
+ /** Numeric id of a saved insight to render. Provide exactly one of query or insight_id. */
+ insight_id?: number;
+ }
+
+ export type TaskRunLivingArtifactResponseVersionsItem = { [key: string]: unknown };
+
+ export interface TaskRunLivingArtifactResponse {
+ /** Stable living artifact id. Use this id when editing the artifact. */
+ id: string;
+ /** Task id this living artifact belongs to. */
+ task_id: string;
+ /** Task run id that created or currently owns this artifact. */
+ run_id: string;
+ /** Project id that owns this artifact. */
+ team_id: number;
+ /** Human-readable artifact name. */
+ name: string;
+ /** Artifact format or delivery surface, such as document, spreadsheet, slack_canvas, file, or slack_message.
+ *
+ * * `slack_message` - slack_message
+ * * `slack_canvas` - slack_canvas
+ * * `document` - document
+ * * `spreadsheet` - spreadsheet
+ * * `dashboard` - dashboard
+ * * `file` - file
+ * * `github_pr` - github_pr */
+ artifact_type: ArtifactTypeEnum;
+ /** Adapter that currently stores or edits the artifact.
+ *
+ * * `slack_message` - slack_message
+ * * `slack_canvas` - slack_canvas
+ * * `slack_file` - slack_file
+ * * `document_connector` - document_connector
+ * * `github_pr` - github_pr */
+ adapter: AdapterEnum;
+ /** Current registry status for the artifact.
+ *
+ * * `active` - active
+ * * `failed` - failed */
+ status: TaskArtifactStatusEnum;
+ /** Adapter-specific location, such as S3 key or Slack canvas id. */
+ location: unknown;
+ /** Adapter-specific metadata for external storage and source tracking. */
+ metadata: unknown;
+ /** Current version number for the artifact. */
+ current_version: number;
+ /** Chronological version records for this artifact. */
+ versions: TaskRunLivingArtifactResponseVersionsItem[];
+ /**
+ * ISO timestamp when created.
+ * @nullable
+ */
+ created_at?: string | null;
+ /**
+ * ISO timestamp when last updated.
+ * @nullable
+ */
+ updated_at?: string | null;
+ }
+
+ export interface TaskRunLivingArtifactChartResponse {
+ /** The living artifact registered for delivery. */
+ artifact: TaskRunLivingArtifactResponse;
+ /** Id of the rendered PNG export backing the chart. */
+ export_asset_id: number;
+ /**
+ * Link to explore this chart interactively in PostHog.
+ * @nullable
+ */
+ url?: string | null;
+ }
+
/**
* Optional metadata to persist with the living artifact.
*/
@@ -70947,62 +71032,6 @@ export namespace Schemas {
content?: string | null;
}
- export type TaskRunLivingArtifactResponseVersionsItem = { [key: string]: unknown };
-
- export interface TaskRunLivingArtifactResponse {
- /** Stable living artifact id. Use this id when editing the artifact. */
- id: string;
- /** Task id this living artifact belongs to. */
- task_id: string;
- /** Task run id that created or currently owns this artifact. */
- run_id: string;
- /** Project id that owns this artifact. */
- team_id: number;
- /** Human-readable artifact name. */
- name: string;
- /** Artifact format or delivery surface, such as document, spreadsheet, slack_canvas, file, or slack_message.
- *
- * * `slack_message` - slack_message
- * * `slack_canvas` - slack_canvas
- * * `document` - document
- * * `spreadsheet` - spreadsheet
- * * `dashboard` - dashboard
- * * `file` - file
- * * `github_pr` - github_pr */
- artifact_type: ArtifactTypeEnum;
- /** Adapter that currently stores or edits the artifact.
- *
- * * `slack_message` - slack_message
- * * `slack_canvas` - slack_canvas
- * * `slack_file` - slack_file
- * * `document_connector` - document_connector
- * * `github_pr` - github_pr */
- adapter: AdapterEnum;
- /** Current registry status for the artifact.
- *
- * * `active` - active
- * * `failed` - failed */
- status: TaskArtifactStatusEnum;
- /** Adapter-specific location, such as S3 key or Slack canvas id. */
- location: unknown;
- /** Adapter-specific metadata for external storage and source tracking. */
- metadata: unknown;
- /** Current version number for the artifact. */
- current_version: number;
- /** Chronological version records for this artifact. */
- versions: TaskRunLivingArtifactResponseVersionsItem[];
- /**
- * ISO timestamp when created.
- * @nullable
- */
- created_at?: string | null;
- /**
- * ISO timestamp when last updated.
- * @nullable
- */
- updated_at?: string | null;
- }
-
export interface TaskRunLivingArtifactsResponse {
/** Living artifacts for this task run. */
artifacts: TaskRunLivingArtifactResponse[];
diff --git a/tach.toml b/tach.toml
index 0fee23127fa6..2bf98c379115 100644
--- a/tach.toml
+++ b/tach.toml
@@ -713,6 +713,7 @@ depends_on = [
"posthog",
"products.error_tracking",
"products.event_definitions",
+ "products.exports",
"products.feature_flags",
"products.ai_observability",
"products.mcp_store",