: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): add saved views (#66827)
Jon McCallumf215a875267a
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex f9fedafa27c0..362bb7915dad 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -254,6 +254,7 @@ rules:|ReviewQueueItem|TraceReview|TraceReviewScore+ |TracingView|UploadedMedia|UserInterview|UserInterviewTopic@@ -518,6 +519,7 @@ rules:|ReviewQueueItem|TraceReview|TraceReviewScore+ |TracingView|UploadedMedia|UserInterview|UserInterviewTopicdiff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c185f47c7e39..c0d0124129c3 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -480,6 +480,7 @@ export const FEATURE_FLAGS = {TOGGLE_PROPERTY_ARRAYS: 'toggle-property-arrays', // owner: @arthurdedeus #team-customer-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracing+ TRACING_SAVED_VIEWS: 'tracing-saved-views', // owner: #team-apm — gates saved views (saved filter sets) in tracingTRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsUSER_INTERVIEWS: 'user-interviews', // owner: @Twixes @jurajmajerikUX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveysdiff --git a/products/tracing/backend/migrations/0001_initial.py b/products/tracing/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..0dfd67674c61--- /dev/null+++ b/products/tracing/backend/migrations/0001_initial.py@@ -0,0 +1,88 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.utils+import posthog.models.utils+from posthog.migration_helpers import AddForeignKeyNotValid+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("posthog", "1245_duckgres_sink_schema_state"),+ ]++ operations = [+ migrations.CreateModel(+ name="TracingView",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "short_id",+ models.CharField(+ blank=True,+ default=posthog.utils.generate_short_id,+ max_length=12,+ ),+ ),+ ("name", models.CharField(max_length=400)),+ ("filters", models.JSONField(default=dict)),+ ("pinned", models.BooleanField(default=False)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "tracing_tracingview",+ "indexes": [+ models.Index(+ fields=["team_id", "-created_at"],+ name="tracing_view_team_created_idx",+ )+ ],+ "unique_together": {("team", "short_id")},+ },+ ),+ AddForeignKeyNotValid(+ model_name="tracingview",+ name="tracingview_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="tracingview",+ name="tracingview_created_by_id_fk",+ column="created_by_id",+ to_table="posthog_user",+ to_column="id",+ ),+ ]diff --git a/products/tracing/backend/migrations/__init__.py b/products/tracing/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/tracing/backend/migrations/max_migration.txt b/products/tracing/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/tracing/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/tracing/backend/models.py b/products/tracing/backend/models.pyindex f0d1606fdc77..18b2e771abf7 100644--- a/products/tracing/backend/models.py+++ b/products/tracing/backend/models.py@@ -1,5 +1,10 @@"""Django models for tracing."""+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel+from posthog.utils import generate_short_id# Define your models here# Important:@@ -7,3 +12,34 @@# - Use types from facade/contracts.py or facade/enums.py where applicable# - Do not use ForeignKeys to models outside this app unless allowed, as you will make implicit dependencies.# - If you make a ForeignKey to a common model, disallow reverse relations with related_name='+'+++class TracingView(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):+ """A saved set of tracing filters (date range, services, attribute filters, sort, view mode).++ Content-only storage — `filters` mirrors the frontend `TracingFilters` shape; restoring a view+ just replays those filters into `tracingFiltersLogic`.+ """++ # FKs to the hot posthog_team / posthog_user tables use db_constraint=False so creating this+ # table takes no lock on those parents; the real constraints are added lock-free via+ # AddForeignKeyNotValid in the migration. created_by overrides CreatedMetaFields for the same reason.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )+ # Human-friendly id used in the API/URL instead of exposing the UUID primary key.+ short_id = models.CharField(max_length=12, blank=True, default=generate_short_id)+ name = models.CharField(max_length=400)+ filters = models.JSONField(default=dict)+ pinned = models.BooleanField(default=False)++ class Meta:+ db_table = "tracing_tracingview"+ unique_together = ("team", "short_id")+ indexes = [+ models.Index(fields=["team_id", "-created_at"], name="tracing_view_team_created_idx"),+ ]++ def __str__(self) -> str:+ return f"{self.name} (Team: {self.team})"diff --git a/products/tracing/backend/presentation/views_api.py b/products/tracing/backend/presentation/views_api.pynew file mode 100644index 000000000000..239215d21d14--- /dev/null+++ b/products/tracing/backend/presentation/views_api.py@@ -0,0 +1,91 @@+from __future__ import annotations++from typing import cast++from django.db.models import QuerySet++from rest_framework import serializers, viewsets++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.event_usage import report_user_action+from posthog.models import User+from posthog.permissions import PostHogFeatureFlagPermission++from products.tracing.backend.models import TracingView+++class TracingViewSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="User who created the view.")+ filters = serializers.DictField(+ required=False,+ default=dict,+ help_text=(+ "Saved tracing filters — a subset of the frontend TracingFilters shape. May contain "+ "dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode."+ ),+ )++ class Meta:+ model = TracingView+ fields = [+ "id",+ "short_id",+ "name",+ "filters",+ "pinned",+ "created_at",+ "created_by",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "short_id",+ "created_at",+ "created_by",+ "updated_at",+ ]+ extra_kwargs = {+ "name": {"help_text": "Human-readable name shown in the saved views list."},+ "pinned": {"help_text": "Whether the view is pinned for quick access."},+ }+++class TracingViewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+ scope_object = "tracing"+ serializer_class = TracingViewSerializer+ lookup_field = "short_id"+ posthog_feature_flag = "tracing-saved-views"+ permission_classes = [PostHogFeatureFlagPermission]+ # Fail-closed manager raises if `.all()` runs at import; the real per-request+ # scoping happens in safely_get_queryset.+ queryset = TracingView.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[TracingView]) -> QuerySet[TracingView]:+ return TracingView.objects.for_team(self.team_id).select_related("created_by").order_by("-created_at")++ def _track(self, event: str, instance: TracingView) -> None:+ report_user_action(+ self.request.user,+ event,+ {+ "id": str(instance.id),+ "short_id": instance.short_id,+ "name": instance.name,+ "pinned": instance.pinned,+ "has_filters": bool(instance.filters),+ },+ team=self.team,+ request=self.request,+ )++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ instance = serializer.save(team=self.team, created_by=cast(User, self.request.user))+ self._track("tracing view created", instance)++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ self._track("tracing view updated", serializer.save())++ def perform_destroy(self, instance: TracingView) -> None:+ self._track("tracing view deleted", instance)+ super().perform_destroy(instance)diff --git a/products/tracing/backend/routes.py b/products/tracing/backend/routes.pyindex 685f48632e32..7cae31977b34 100644--- a/products/tracing/backend/routes.py+++ b/products/tracing/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryfrom products.tracing.backend.presentation.views import SpansViewSet+from products.tracing.backend.presentation.views_api import TracingViewViewSetdef register_routes(routers: RouterRegistry) -> None:@@ -10,3 +11,9 @@ def register_routes(routers: RouterRegistry) -> None:"project_tracing_spans",["team_id"],)+ routers.register_legacy_dual_route(+ r"tracing/views",+ TracingViewViewSet,+ "project_tracing_views",+ ["team_id"],+ )diff --git a/products/tracing/backend/tests/test_views_api.py b/products/tracing/backend/tests/test_views_api.pynew file mode 100644index 000000000000..af8d11967418--- /dev/null+++ b/products/tracing/backend/tests/test_views_api.py@@ -0,0 +1,238 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIClient++from posthog.models.team.team import Team++from products.tracing.backend.models import TracingView+++class TestTracingViewAPI(APIBaseTest):+ base_url: str++ def setUp(self):+ super().setUp()+ self.base_url = f"/api/environments/{self.team.pk}/tracing/views/"+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ self._ff_patcher.start()+ self.addCleanup(self._ff_patcher.stop)++ def _valid_payload(self, **overrides) -> dict:+ defaults = {+ "name": "Slow checkout traces",+ "filters": {"serviceNames": ["checkout"], "viewMode": "traces"},+ }+ defaults.update(overrides)+ return defaults++ def _create_via_api(self, **overrides) -> dict:+ response = self.client.post(self.base_url, self._valid_payload(**overrides), format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ return response.json()++ # --- CRUD ---++ @patch("products.tracing.backend.presentation.views_api.report_user_action")+ def test_create(self, mock_report):+ data = self._create_via_api()+ assert data["name"] == "Slow checkout traces"+ assert data["filters"] == {"serviceNames": ["checkout"], "viewMode": "traces"}+ assert data["pinned"] is False+ assert data["short_id"] is not None+ assert data["created_by"]["id"] == self.user.pk++ mock_report.assert_called_once()+ assert mock_report.call_args[0][1] == "tracing view created"+ assert mock_report.call_args[0][2]["name"] == "Slow checkout traces"+ assert mock_report.call_args[0][2]["has_filters"] is True++ def test_list(self):+ self._create_via_api(name="View 1")+ self._create_via_api(name="View 2")++ response = self.client.get(self.base_url)+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 2+ assert {r["name"] for r in results} == {"View 1", "View 2"}++ def test_retrieve(self):+ created = self._create_via_api()++ response = self.client.get(f"{self.base_url}{created['short_id']}/")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["short_id"] == created["short_id"]+ assert response.json()["name"] == "Slow checkout traces"++ @patch("products.tracing.backend.presentation.views_api.report_user_action")+ def test_partial_update(self, mock_report):+ created = self._create_via_api()+ mock_report.reset_mock()++ response = self.client.patch(+ f"{self.base_url}{created['short_id']}/",+ {"name": "Renamed view"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["name"] == "Renamed view"++ mock_report.assert_called_once()+ assert mock_report.call_args[0][1] == "tracing view updated"+ assert mock_report.call_args[0][2]["name"] == "Renamed view"++ def test_partial_update_preserves_filters(self):+ created = self._create_via_api(filters={"serviceNames": ["api"], "viewMode": "spans"})++ response = self.client.patch(+ f"{self.base_url}{created['short_id']}/",+ {"name": "Just rename"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["name"] == "Just rename"+ assert response.json()["filters"] == {"serviceNames": ["api"], "viewMode": "spans"}++ @patch("products.tracing.backend.presentation.views_api.report_user_action")+ def test_delete(self, mock_report):+ created = self._create_via_api()+ mock_report.reset_mock()++ response = self.client.delete(f"{self.base_url}{created['short_id']}/")+ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert not TracingView.objects.unscoped().filter(pk=created["id"]).exists()++ mock_report.assert_called_once()+ assert mock_report.call_args[0][1] == "tracing view deleted"+ assert mock_report.call_args[0][2]["name"] == "Slow checkout traces"++ # --- Filters are optional ---++ def test_create_with_empty_filters(self):+ data = self._create_via_api(filters={})+ assert data["filters"] == {}++ def test_create_with_no_filters(self):+ response = self.client.post(self.base_url, {"name": "Minimal view"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["filters"] == {}++ def test_create_with_complex_filters(self):+ filters = {+ "dateRange": {"date_from": "-24h", "date_to": None},+ "serviceNames": ["api", "worker"],+ "orderBy": "duration",+ "orderDirection": "DESC",+ "viewMode": "spans",+ "filterGroup": {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [{"key": "http.status_code", "value": "500", "type": "span", "operator": "exact"}],+ }+ ],+ },+ }+ data = self._create_via_api(filters=filters)+ assert data["filters"] == filters++ # --- Validation ---++ @parameterized.expand(+ [+ ("missing_name", {"filters": {}}),+ ("blank_name", {"name": "", "filters": {}}),+ ]+ )+ def test_create_rejects_invalid_name(self, _label, payload):+ response = self.client.post(self.base_url, payload, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ # --- Read-only fields ---++ def test_short_id_ignored_on_create(self):+ data = self._create_via_api(short_id="custom123")+ assert data["short_id"] != "custom123"++ def test_short_id_ignored_on_update(self):+ created = self._create_via_api()+ original_short_id = created["short_id"]++ response = self.client.patch(+ f"{self.base_url}{created['short_id']}/",+ {"short_id": "changed"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["short_id"] == original_short_id++ # --- Team isolation ---++ def test_list_only_own_team(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")+ TracingView.objects.unscoped().create(team=team2, name="Other team view", created_by=self.user)+ self._create_via_api(name="My view")++ response = self.client.get(self.base_url)+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["name"] == "My view"++ def test_cannot_retrieve_other_teams_view(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")+ other_view = TracingView.objects.unscoped().create(team=team2, name="Other", created_by=self.user)++ response = self.client.get(f"{self.base_url}{other_view.short_id}/")+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_cannot_update_other_teams_view(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")+ other_view = TracingView.objects.unscoped().create(team=team2, name="Other", created_by=self.user)++ response = self.client.patch(+ f"{self.base_url}{other_view.short_id}/",+ {"name": "Hacked"},+ format="json",+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND+ other_view.refresh_from_db()+ assert other_view.name == "Other"++ def test_cannot_delete_other_teams_view(self):+ team2 = Team.objects.create(organization=self.organization, name="Team 2")+ other_view = TracingView.objects.unscoped().create(team=team2, name="Other", created_by=self.user)++ response = self.client.delete(f"{self.base_url}{other_view.short_id}/")+ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert TracingView.objects.unscoped().filter(pk=other_view.id).exists()++ # --- Auth ---++ def test_unauthorized_access(self):+ client = APIClient()+ response = client.get(self.base_url)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ # --- Feature flag ---++ @patch("posthoganalytics.feature_enabled", return_value=False)+ def test_returns_403_when_feature_flag_disabled(self, _mock_feature_enabled):+ response = self.client.get(self.base_url)+ assert response.status_code == status.HTTP_403_FORBIDDEN++ # --- Pinned ---++ def test_pin_view(self):+ created = self._create_via_api()++ response = self.client.patch(+ f"{self.base_url}{created['short_id']}/",+ {"pinned": True},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["pinned"] is Truediff --git a/products/tracing/frontend/TracingFilterBar.tsx b/products/tracing/frontend/TracingFilterBar.tsxindex 11c16f76f561..52a5bc1d6a9c 100644--- a/products/tracing/frontend/TracingFilterBar.tsx+++ b/products/tracing/frontend/TracingFilterBar.tsx@@ -35,6 +35,7 @@ import {UniversalFiltersGroup,} from '~/types'+import { SavedViewsButton } from './savedViews/SavedViewsButton'import { tracingDataLogic } from './tracingDataLogic'import { tracingFiltersLogic, type TracingViewMode } from './tracingFiltersLogic'import { tracingServiceFilterLogic, TracingServiceFilterLogicProps } from './tracingServiceFilterLogic'@@ -191,6 +192,7 @@ export function TracingFilterBar(): JSX.Element {onClick={() => runQuery()}loading={spansLoading}/>+ <SavedViewsButton /></div></div><TracingAppliedFilters />diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex bd955d1808e0..5db5e6ddf019 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -485,6 +485,118 @@ export interface _TracingTreeRequestApi {query: _TracingTreeQueryBodyApi}+/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++/**+ * Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.+ */+export type TracingViewApiFilters = { [key: string]: unknown }++export interface TracingViewApi {+ readonly id: string+ readonly short_id: string+ /**+ * Human-readable name shown in the saved views list.+ * @maxLength 400+ */+ name: string+ /** Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode. */+ filters?: TracingViewApiFilters+ /** Whether the view is pinned for quick access. */+ pinned?: boolean+ readonly created_at: string+ /** User who created the view. */+ readonly created_by: UserBasicApi | null+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedTracingViewListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: TracingViewApi[]+}++/**+ * Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.+ */+export type PatchedTracingViewApiFilters = { [key: string]: unknown }++export interface PatchedTracingViewApi {+ readonly id?: string+ readonly short_id?: string+ /**+ * Human-readable name shown in the saved views list.+ * @maxLength 400+ */+ name?: string+ /** Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode. */+ filters?: PatchedTracingViewApiFilters+ /** Whether the view is pinned for quick access. */+ pinned?: boolean+ readonly created_at?: string+ /** User who created the view. */+ readonly created_by?: UserBasicApi | null+ /** @nullable */+ readonly updated_at?: string | null+}+export type TracingSpansAttributesRetrieveParams = {/*** Type of attributes: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.@@ -578,3 +690,14 @@ export const TracingSpansValuesRetrieveAttributeType = {SpanAttribute: 'span_attribute',SpanResourceAttribute: 'span_resource_attribute',} as const++export type TracingViewsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.tsindex 9d2ad4f0ffcc..f931c762b5e9 100644--- a/products/tracing/frontend/generated/api.ts+++ b/products/tracing/frontend/generated/api.ts@@ -9,9 +9,13 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ PaginatedTracingViewListApi,+ PatchedTracingViewApi,TracingSpansAttributesRetrieveParams,TracingSpansServiceNamesRetrieveParams,TracingSpansValuesRetrieveParams,+ TracingViewApi,+ TracingViewsListParams,_HasSpansResponseApi,_SymbolStatsRequestApi,_SymbolStatsResponseApi,@@ -27,6 +31,23 @@ import type {_TracingTreeRequestApi,} from './api.schemas'+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>+export const getTracingSpansAggregateCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/tracing/spans/aggregate/`}@@ -281,3 +302,109 @@ export const tracingSpansValuesRetrieve = async (method: 'GET',})}++export const getTracingViewsListUrl = (projectId: string, params?: TracingViewsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/tracing/views/?${stringifiedParams}`+ : `/api/projects/${projectId}/tracing/views/`+}++export const tracingViewsList = async (+ projectId: string,+ params?: TracingViewsListParams,+ options?: RequestInit+): Promise<PaginatedTracingViewListApi> => {+ return apiMutator<PaginatedTracingViewListApi>(getTracingViewsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getTracingViewsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tracing/views/`+}++export const tracingViewsCreate = async (+ projectId: string,+ tracingViewApi: NonReadonly<TracingViewApi>,+ options?: RequestInit+): Promise<TracingViewApi> => {+ return apiMutator<TracingViewApi>(getTracingViewsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(tracingViewApi),+ })+}++export const getTracingViewsRetrieveUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/tracing/views/${shortId}/`+}++export const tracingViewsRetrieve = async (+ projectId: string,+ shortId: string,+ options?: RequestInit+): Promise<TracingViewApi> => {+ return apiMutator<TracingViewApi>(getTracingViewsRetrieveUrl(projectId, shortId), {+ ...options,+ method: 'GET',+ })+}++export const getTracingViewsUpdateUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/tracing/views/${shortId}/`+}++export const tracingViewsUpdate = async (+ projectId: string,+ shortId: string,+ tracingViewApi: NonReadonly<TracingViewApi>,+ options?: RequestInit+): Promise<TracingViewApi> => {+ return apiMutator<TracingViewApi>(getTracingViewsUpdateUrl(projectId, shortId), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(tracingViewApi),+ })+}++export const getTracingViewsPartialUpdateUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/tracing/views/${shortId}/`+}++export const tracingViewsPartialUpdate = async (+ projectId: string,+ shortId: string,+ patchedTracingViewApi?: NonReadonly<PatchedTracingViewApi>,+ options?: RequestInit+): Promise<TracingViewApi> => {+ return apiMutator<TracingViewApi>(getTracingViewsPartialUpdateUrl(projectId, shortId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedTracingViewApi),+ })+}++export const getTracingViewsDestroyUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/tracing/views/${shortId}/`+}++export const tracingViewsDestroy = async (projectId: string, shortId: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getTracingViewsDestroyUrl(projectId, shortId), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 7ffb64ed1b8a..93555d8e32b8 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -750,3 +750,52 @@ export const TracingSpansTreeCreateBody = /* @__PURE__ */ zod.object({}).describe('The span call-tree aggregation query to execute.'),})++export const tracingViewsCreateBodyNameMax = 400++export const TracingViewsCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(tracingViewsCreateBodyNameMax)+ .describe('Human-readable name shown in the saved views list.'),+ filters: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.'+ ),+ pinned: zod.boolean().optional().describe('Whether the view is pinned for quick access.'),+})++export const tracingViewsUpdateBodyNameMax = 400++export const TracingViewsUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(tracingViewsUpdateBodyNameMax)+ .describe('Human-readable name shown in the saved views list.'),+ filters: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.'+ ),+ pinned: zod.boolean().optional().describe('Whether the view is pinned for quick access.'),+})++export const tracingViewsPartialUpdateBodyNameMax = 400++export const TracingViewsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(tracingViewsPartialUpdateBodyNameMax)+ .optional()+ .describe('Human-readable name shown in the saved views list.'),+ filters: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.'+ ),+ pinned: zod.boolean().optional().describe('Whether the view is pinned for quick access.'),+})diff --git a/products/tracing/frontend/savedViews/SavedViewsButton.tsx b/products/tracing/frontend/savedViews/SavedViewsButton.tsxnew file mode 100644index 000000000000..d0f2d2bc94c5--- /dev/null+++ b/products/tracing/frontend/savedViews/SavedViewsButton.tsx@@ -0,0 +1,38 @@+import { useActions } from 'kea'++import { IconBookmark } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'++import { SavedViewsModal } from './SavedViewsModal'+import { tracingViewsListLogic } from './tracingViewsListLogic'++function SavedViewsButtonInner(): JSX.Element {+ const { openModal } = useActions(tracingViewsListLogic)++ return (+ <>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconBookmark />}+ onClick={openModal}+ data-attr="tracing-saved-views-button"+ >+ Saved views+ </LemonButton>+ <SavedViewsModal />+ </>+ )+}++export function SavedViewsButton(): JSX.Element | null {+ const enabled = useFeatureFlag('TRACING_SAVED_VIEWS')++ if (!enabled) {+ return null+ }++ return <SavedViewsButtonInner />+}diff --git a/products/tracing/frontend/savedViews/SavedViewsModal.tsx b/products/tracing/frontend/savedViews/SavedViewsModal.tsxnew file mode 100644index 000000000000..696c5022565d--- /dev/null+++ b/products/tracing/frontend/savedViews/SavedViewsModal.tsx@@ -0,0 +1,176 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { useKeepMountedWhileOpen } from 'lib/hooks/useKeepMountedWhileOpen'+import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'++import { getTracingFiltersSummaryLines } from './savedViewsSummary'+import { tracingViewsListLogic } from './tracingViewsListLogic'+import { TracingView, tracingViewsLogic } from './tracingViewsLogic'++function FiltersSummaryDisplay({ filters }: { filters: Record<string, any> }): JSX.Element {+ const lines = getTracingFiltersSummaryLines(filters)+ if (lines.length === 0) {+ return <span className="text-muted text-xs">No filters</span>+ }+ return (+ <div className="text-xs text-muted space-y-0.5">+ {lines.map((line) => (+ <div key={line.label}>+ <span className="font-medium">{line.label}:</span> {line.value}+ </div>+ ))}+ </div>+ )+}++function SaveViewModal(): JSX.Element | null {+ const { isSaveModalOpen, viewName, filters } = useValues(tracingViewsListLogic)+ const { closeSaveModal, setViewName, saveView } = useActions(tracingViewsListLogic)+ const shouldRender = useKeepMountedWhileOpen(isSaveModalOpen)++ if (!shouldRender) {+ return null+ }++ return (+ <LemonModal+ isOpen={isSaveModalOpen}+ onClose={closeSaveModal}+ title="Save current view"+ footer={+ <>+ <LemonButton type="secondary" onClick={closeSaveModal}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={saveView}+ disabledReason={!viewName.trim() ? 'Enter a name' : undefined}+ >+ Save view+ </LemonButton>+ </>+ }+ >+ <div className="space-y-2">+ <LemonInput+ placeholder="View name"+ value={viewName}+ onChange={setViewName}+ autoFocus+ onPressEnter={saveView}+ />+ <FiltersSummaryDisplay filters={filters} />+ </div>+ </LemonModal>+ )+}++export function SavedViewsModal(): JSX.Element {+ const { isModalOpen } = useValues(tracingViewsListLogic)+ const { closeModal, openSaveModal } = useActions(tracingViewsListLogic)+ const { views, viewsLoading } = useValues(tracingViewsLogic)+ const { deleteView, loadView } = useActions(tracingViewsLogic)+ const shouldRenderList = useKeepMountedWhileOpen(isModalOpen)++ const columns: LemonTableColumns<TracingView> = [+ {+ title: 'Name',+ dataIndex: 'name',+ render: (_, view) => <span className="font-medium">{view.name}</span>,+ },+ {+ title: 'Filters',+ render: (_, view) => <FiltersSummaryDisplay filters={view.filters ?? {}} />,+ },+ {+ title: 'Created by',+ dataIndex: 'created_by',+ render: (_, view) => (+ <span className="text-muted text-xs">+ {view.created_by?.first_name || view.created_by?.email || '—'}+ </span>+ ),+ },+ {+ title: 'Created',+ dataIndex: 'created_at',+ render: (_, view) => <TZLabel time={view.created_at} />,+ },+ {+ title: '',+ render: (_, view) => (+ <div className="flex items-center gap-1">+ <LemonButton type="secondary" size="xsmall" onClick={() => loadView(view)}>+ Load+ </LemonButton>+ <More+ overlay={+ <LemonMenuOverlay+ items={[+ {+ label: 'Delete',+ status: 'danger',+ onClick: () => {+ LemonDialog.open({+ title: `Delete "${view.name}"?`,+ description:+ 'This view will be permanently deleted. This action cannot be undone.',+ primaryButton: {+ children: 'Delete',+ type: 'primary',+ status: 'danger',+ onClick: () => deleteView(view.short_id),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ },+ },+ ]}+ />+ }+ />+ </div>+ ),+ },+ ]++ return (+ <>+ {shouldRenderList && (+ <LemonModal+ isOpen={isModalOpen}+ onClose={closeModal}+ title="Saved views"+ width={720}+ footer={+ <div className="flex justify-between w-full">+ <LemonButton type="primary" onClick={openSaveModal}>+ Save current view+ </LemonButton>+ <LemonButton type="secondary" onClick={closeModal}>+ Close+ </LemonButton>+ </div>+ }+ >+ <LemonTable+ columns={columns}+ dataSource={views}+ rowKey="id"+ loading={viewsLoading}+ emptyState="No saved views yet."+ size="small"+ />+ </LemonModal>+ )}+ <SaveViewModal />+ </>+ )+}diff --git a/products/tracing/frontend/savedViews/savedViewsSummary.test.ts b/products/tracing/frontend/savedViews/savedViewsSummary.test.tsnew file mode 100644index 000000000000..d4bc824f7eb8--- /dev/null+++ b/products/tracing/frontend/savedViews/savedViewsSummary.test.ts@@ -0,0 +1,82 @@+import { getTracingFiltersSummaryLines } from './savedViewsSummary'++describe('getTracingFiltersSummaryLines', () => {+ it('returns no lines for empty filters', () => {+ expect(getTracingFiltersSummaryLines({})).toEqual([])+ })++ it('summarizes a date range with both bounds', () => {+ const lines = getTracingFiltersSummaryLines({ dateRange: { date_from: '-24h', date_to: '-1h' } })+ expect(lines).toEqual([{ label: 'Date range', value: '-24h → -1h' }])+ })++ it('summarizes a relative date range with only date_from', () => {+ const lines = getTracingFiltersSummaryLines({ dateRange: { date_from: '-1h', date_to: null } })+ expect(lines).toEqual([{ label: 'Date range', value: '-1h' }])+ })++ it('uses singular/plural service labels', () => {+ expect(getTracingFiltersSummaryLines({ serviceNames: ['api'] })).toEqual([{ label: 'Service', value: 'api' }])+ expect(getTracingFiltersSummaryLines({ serviceNames: ['api', 'worker'] })).toEqual([+ { label: 'Services', value: 'api, worker' },+ ])+ })++ it('truncates long service lists with a +N more suffix', () => {+ const lines = getTracingFiltersSummaryLines({ serviceNames: ['a', 'b', 'c', 'd', 'e'] })+ expect(lines).toEqual([{ label: 'Services', value: 'a, b, c +2 more' }])+ })++ it('summarizes attribute filters from the filter group', () => {+ const filterGroup = {+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [{ key: 'http.status_code', value: '500', type: 'span', operator: 'exact' }],+ },+ ],+ }+ const lines = getTracingFiltersSummaryLines({ filterGroup })+ expect(lines).toEqual([{ label: 'Filter', value: 'http.status_code=500' }])+ })++ it('includes attribute filters from every top-level group, not just the first', () => {+ const filterGroup = {+ type: 'AND',+ values: [+ { type: 'AND', values: [{ key: 'a', value: '1', type: 'span', operator: 'exact' }] },+ { type: 'AND', values: [{ key: 'b', value: '2', type: 'span', operator: 'exact' }] },+ ],+ }+ const lines = getTracingFiltersSummaryLines({ filterGroup })+ expect(lines).toEqual([{ label: 'Filters', value: 'a=1, b=2' }])+ })++ it('maps view mode and sort to readable lines', () => {+ const lines = getTracingFiltersSummaryLines({+ viewMode: 'spans',+ orderBy: 'duration',+ orderDirection: 'ASC',+ })+ expect(lines).toEqual([+ { label: 'View', value: 'Spans' },+ { label: 'Sort', value: 'duration (ascending)' },+ ])+ })++ it('combines all filter types in order', () => {+ const lines = getTracingFiltersSummaryLines({+ dateRange: { date_from: '-1h', date_to: null },+ serviceNames: ['api'],+ filterGroup: {+ type: 'AND',+ values: [{ type: 'AND', values: [{ key: 'env', value: 'prod', type: 'span', operator: 'exact' }] }],+ },+ viewMode: 'traces',+ orderBy: 'timestamp',+ orderDirection: 'DESC',+ })+ expect(lines.map((l) => l.label)).toEqual(['Date range', 'Service', 'Filter', 'View', 'Sort'])+ })+})diff --git a/products/tracing/frontend/savedViews/savedViewsSummary.ts b/products/tracing/frontend/savedViews/savedViewsSummary.tsnew file mode 100644index 000000000000..630e06928108--- /dev/null+++ b/products/tracing/frontend/savedViews/savedViewsSummary.ts@@ -0,0 +1,70 @@+import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'++import { AnyPropertyFilter } from '~/types'++export interface FiltersSummaryLine {+ label: string+ value: string+}++function formatFilterGroupValues(filterGroup: Record<string, any> | undefined): string[] {+ const groups = filterGroup?.values+ if (!Array.isArray(groups)) {+ return []+ }++ // The outer `values` array can hold multiple sibling groups — flatten leaf property filters+ // across all of them so the summary doesn't silently drop groups past the first.+ return groups+ .filter((group) => group && Array.isArray(group.values))+ .flatMap((group) => group.values.filter(isValidPropertyFilter))+ .map((filter: AnyPropertyFilter) => {+ const key = filter.key || '?'+ const value = Array.isArray(filter.value) ? filter.value.join(', ') : String(filter.value ?? '')+ const truncatedValue = value.length > 15 ? `${value.slice(0, 15)}...` : value+ return `${key}=${truncatedValue}`+ })+}++// Compact, human-readable summary of a saved view's filters — shown in the list and save dialog so a+// user can tell views apart without loading them. Mirrors the shape produced by tracingFiltersLogic.+export function getTracingFiltersSummaryLines(filters: Record<string, any>): FiltersSummaryLine[] {+ const lines: FiltersSummaryLine[] = []++ if (filters.dateRange?.date_from) {+ const value = filters.dateRange.date_to+ ? `${filters.dateRange.date_from} → ${filters.dateRange.date_to}`+ : filters.dateRange.date_from+ lines.push({ label: 'Date range', value })+ }++ if (filters.serviceNames?.length) {+ const maxDisplayed = 3+ const displayed = filters.serviceNames.slice(0, maxDisplayed)+ const remaining = filters.serviceNames.length - displayed.length+ const serviceText = displayed.join(', ')+ lines.push({+ label: filters.serviceNames.length === 1 ? 'Service' : 'Services',+ value: remaining > 0 ? `${serviceText} +${remaining} more` : serviceText,+ })+ }++ const attributeFilters = formatFilterGroupValues(filters.filterGroup)+ if (attributeFilters.length > 0) {+ lines.push({+ label: attributeFilters.length === 1 ? 'Filter' : 'Filters',+ value: attributeFilters.join(', '),+ })+ }++ if (filters.viewMode) {+ lines.push({ label: 'View', value: filters.viewMode === 'spans' ? 'Spans' : 'Traces' })+ }++ if (filters.orderBy) {+ const direction = filters.orderDirection === 'ASC' ? 'ascending' : 'descending'+ lines.push({ label: 'Sort', value: `${filters.orderBy} (${direction})` })+ }++ return lines+}diff --git a/products/tracing/frontend/savedViews/tracingViewsListLogic.ts b/products/tracing/frontend/savedViews/tracingViewsListLogic.tsnew file mode 100644index 000000000000..4afc32155901--- /dev/null+++ b/products/tracing/frontend/savedViews/tracingViewsListLogic.ts@@ -0,0 +1,68 @@+import { actions, connect, kea, listeners, path, reducers } from 'kea'++import { tracingFiltersLogic } from '../tracingFiltersLogic'+import type { tracingViewsListLogicType } from './tracingViewsListLogicType'+import { tracingViewsLogic } from './tracingViewsLogic'++export const tracingViewsListLogic = kea<tracingViewsListLogicType>([+ path(['products', 'tracing', 'frontend', 'savedViews', 'tracingViewsListLogic']),++ connect(() => ({+ values: [tracingFiltersLogic, ['filters']],+ actions: [tracingViewsLogic, ['createView', 'createViewSuccess', 'loadView', 'loadViews']],+ })),++ actions({+ openModal: true,+ closeModal: true,+ openSaveModal: true,+ closeSaveModal: true,+ setViewName: (viewName: string) => ({ viewName }),+ saveView: true,+ }),++ reducers({+ isModalOpen: [+ false,+ {+ openModal: () => true,+ closeModal: () => false,+ loadView: () => false,+ },+ ],+ isSaveModalOpen: [+ false,+ {+ openSaveModal: () => true,+ closeSaveModal: () => false,+ createViewSuccess: () => false,+ },+ ],+ viewName: [+ '',+ {+ setViewName: (_, { viewName }) => viewName,+ closeSaveModal: () => '',+ createViewSuccess: () => '',+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ openModal: () => {+ actions.loadViews()+ },+ saveView: () => {+ const name = values.viewName.trim()+ if (!name) {+ return+ }+ // Persist only the subset a view should restore — drop ephemeral compare-mode state.+ const { dateRange, serviceNames, filterGroup, orderBy, orderDirection, viewMode } = values.filters+ actions.createView({+ name,+ filters: { dateRange, serviceNames, filterGroup, orderBy, orderDirection, viewMode },+ })+ },+ })),+])diff --git a/products/tracing/frontend/savedViews/tracingViewsLogic.test.ts b/products/tracing/frontend/savedViews/tracingViewsLogic.test.tsnew file mode 100644index 000000000000..e703c9069b20--- /dev/null+++ b/products/tracing/frontend/savedViews/tracingViewsLogic.test.ts@@ -0,0 +1,131 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import { tracingFiltersLogic } from '../tracingFiltersLogic'+import { tracingViewsListLogic } from './tracingViewsListLogic'+import { TracingView, tracingViewsLogic } from './tracingViewsLogic'++const mockView = (overrides: Partial<TracingView> = {}): TracingView => ({+ id: 'view-1',+ short_id: 'abc123',+ name: 'My view',+ filters: {},+ pinned: false,+ created_at: '2026-06-01T00:00:00Z',+ created_by: null,+ updated_at: null,+ ...overrides,+})++describe('tracing saved views', () => {+ let filtersLogic: ReturnType<typeof tracingFiltersLogic.build>+ let viewsLogic: ReturnType<typeof tracingViewsLogic.build>+ let listLogic: ReturnType<typeof tracingViewsListLogic.build>++ beforeEach(() => {+ initKeaTests()+ // openModal triggers loadViews → api.get; keep it from hitting the network.+ jest.spyOn(api, 'get').mockResolvedValue({ results: [] })+ filtersLogic = tracingFiltersLogic()+ filtersLogic.mount()+ viewsLogic = tracingViewsLogic()+ viewsLogic.mount()+ listLogic = tracingViewsListLogic()+ listLogic.mount()+ })++ afterEach(() => {+ listLogic?.unmount()+ viewsLogic?.unmount()+ filtersLogic?.unmount()+ jest.restoreAllMocks()+ })++ describe('saveView', () => {+ it('persists only the saveable filter subset, excluding ephemeral compare state', async () => {+ const createSpy = jest.spyOn(api, 'create').mockResolvedValue(mockView())++ filtersLogic.actions.setServiceNames(['api'])+ filtersLogic.actions.setViewMode('spans')+ filtersLogic.actions.setSort('duration', 'ASC')+ // Ephemeral state that must NOT be saved.+ filtersLogic.actions.setCompareMode(true)++ listLogic.actions.setViewName('Slow spans')+ await expectLogic(listLogic, () => {+ listLogic.actions.saveView()+ }).toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledTimes(1)+ const payload = createSpy.mock.calls[0][1] as { name: string; filters: Record<string, any> }+ expect(payload.name).toBe('Slow spans')+ expect(payload.filters).toEqual({+ dateRange: { date_from: '-1h', date_to: null },+ serviceNames: ['api'],+ filterGroup: filtersLogic.values.filterGroup,+ orderBy: 'duration',+ orderDirection: 'ASC',+ viewMode: 'spans',+ })+ expect(payload.filters).not.toHaveProperty('compareMode')+ expect(payload.filters).not.toHaveProperty('currentWindowOverride')+ expect(payload.filters).not.toHaveProperty('previousWindowOverride')+ })++ it('does nothing when the name is blank', async () => {+ const createSpy = jest.spyOn(api, 'create').mockResolvedValue(mockView())++ listLogic.actions.setViewName(' ')+ await expectLogic(listLogic, () => {+ listLogic.actions.saveView()+ }).toFinishAllListeners()++ expect(createSpy).not.toHaveBeenCalled()+ })+ })++ describe('loadView', () => {+ it('restores the saved filters into tracingFiltersLogic', async () => {+ const view = mockView({+ filters: { serviceNames: ['web'], viewMode: 'spans', orderBy: 'duration', orderDirection: 'DESC' },+ })++ await expectLogic(viewsLogic, () => {+ viewsLogic.actions.loadView(view)+ }).toFinishAllListeners()++ expect(filtersLogic.values.serviceNames).toEqual(['web'])+ expect(filtersLogic.values.viewMode).toBe('spans')+ expect(filtersLogic.values.orderBy).toBe('duration')+ expect(filtersLogic.values.orderDirection).toBe('DESC')+ })++ it('closes the list modal when a view is loaded', async () => {+ listLogic.actions.openModal()+ expect(listLogic.values.isModalOpen).toBe(true)++ viewsLogic.actions.loadView(mockView())+ expect(listLogic.values.isModalOpen).toBe(false)+ })+ })++ describe('deleteView', () => {+ it('optimistically removes the view from the list', async () => {+ jest.spyOn(api, 'delete').mockResolvedValue(undefined)+ // Seed the loader state with two views.+ jest.spyOn(api, 'get').mockResolvedValue({+ results: [mockView({ short_id: 'keep' }), mockView({ short_id: 'drop' })],+ })+ await expectLogic(viewsLogic, () => {+ viewsLogic.actions.loadViews()+ }).toFinishAllListeners()+ expect(viewsLogic.values.views).toHaveLength(2)++ viewsLogic.actions.deleteView('drop')+ expect(viewsLogic.values.views.map((v) => v.short_id)).toEqual(['keep'])+ })+ })+})diff --git a/products/tracing/frontend/savedViews/tracingViewsLogic.ts b/products/tracing/frontend/savedViews/tracingViewsLogic.tsnew file mode 100644index 000000000000..412743f3754a--- /dev/null+++ b/products/tracing/frontend/savedViews/tracingViewsLogic.ts@@ -0,0 +1,98 @@+import { actions, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'++import { TracingFilters, tracingFiltersLogic } from '../tracingFiltersLogic'+import type { tracingViewsLogicType } from './tracingViewsLogicType'++// Subset of TracingFilters persisted in a saved view. Compare-mode and the dragged overlay windows+// are ephemeral UI state tied to on-screen sparkline data, so they're intentionally excluded.+export type SavedTracingFilters = Pick<+ TracingFilters,+ 'dateRange' | 'serviceNames' | 'filterGroup' | 'orderBy' | 'orderDirection' | 'viewMode'+>++// Handwritten until `hogli build:openapi` generates `TracingViewApi` from TracingViewSerializer.+export interface TracingView {+ id: string+ short_id: string+ name: string+ filters: Partial<SavedTracingFilters>+ pinned: boolean+ created_at: string+ created_by: {+ first_name?: string+ email?: string+ } | null+ updated_at: string | null+}++const tracingViewsUrl = (teamId: number | null): string => `api/projects/${teamId}/tracing/views`++export const tracingViewsLogic = kea<tracingViewsLogicType>([+ path(['products', 'tracing', 'frontend', 'savedViews', 'tracingViewsLogic']),++ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ actions: [tracingFiltersLogic, ['setFilters']],+ })),++ actions({+ deleteView: (shortId: string) => ({ shortId }),+ loadView: (view: TracingView) => ({ view }),+ }),++ loaders(({ values }) => ({+ views: [+ [] as TracingView[],+ {+ loadViews: async () => {+ // nosemgrep: prefer-codegen-api+ const response = await api.get(`${tracingViewsUrl(values.currentTeamId)}/`)+ return response.results+ },+ createView: async ({ name, filters }: { name: string; filters: Partial<SavedTracingFilters> }) => {+ // nosemgrep: prefer-codegen-api+ const created: TracingView = await api.create(`${tracingViewsUrl(values.currentTeamId)}/`, {+ name,+ filters,+ })+ lemonToast.success('View saved')+ return [created, ...values.views]+ },+ },+ ],+ })),++ reducers({+ views: {+ deleteView: (state, { shortId }) => state.filter((v) => v.short_id !== shortId),+ },+ }),++ listeners(({ actions, values }) => ({+ deleteView: async ({ shortId }) => {+ try {+ // nosemgrep: prefer-codegen-api+ await api.delete(`${tracingViewsUrl(values.currentTeamId)}/${shortId}/`)+ lemonToast.success('View deleted')+ } catch {+ lemonToast.error('Failed to delete view')+ actions.loadViews()+ }+ },+ loadView: ({ view }) => {+ actions.setFilters(view.filters || {})+ },+ createViewFailure: () => {+ lemonToast.error('Failed to save view')+ },+ loadViewsFailure: () => {+ lemonToast.error('Failed to load saved views')+ },+ })),+])diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yamlindex 85a2dc0e2a6c..9fd3fb359099 100644--- a/products/tracing/mcp/tools.yaml+++ b/products/tracing/mcp/tools.yaml@@ -209,3 +209,21 @@ tools:tracing-spans-symbol-stats-create:operation: tracing_spans_symbol_stats_createenabled: false+ tracing-views-create:+ operation: tracing_views_create+ enabled: false+ tracing-views-destroy:+ operation: tracing_views_destroy+ enabled: false+ tracing-views-list:+ operation: tracing_views_list+ enabled: false+ tracing-views-partial-update:+ operation: tracing_views_partial_update+ enabled: false+ tracing-views-retrieve:+ operation: tracing_views_retrieve+ enabled: false+ tracing-views-update:+ operation: tracing_views_update+ enabled: falsediff --git a/pyproject.toml b/pyproject.tomlindex d4c3bde01cc4..53861d8e51f3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -533,6 +533,9 @@ ignore_imports = ["products.tracing.backend.presentation.views -> products.tracing.backend.logic","products.tracing.backend.presentation.views -> products.tracing.backend.sparkline_query_runner","products.tracing.backend.presentation.views -> products.tracing.backend.has_spans_query_runner",+ # Saved-views ModelViewSet needs the model class for its serializer; same accepted pattern as+ # logs' views_api. TODO: route through facade with the broader presentation cleanup.+ "products.tracing.backend.presentation.views_api -> products.tracing.backend.models","products.user_interviews.backend.presentation.views -> products.user_interviews.backend.models","products.user_interviews.backend.presentation.views -> products.user_interviews.backend.invite_email","products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.models",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6ebfc251e94d..394a79482d13 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34417,6 +34417,39 @@ export namespace Schemas {results: TraceReview[];}+ /**+ * Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.+ */+ export type TracingViewFilters = { [key: string]: unknown };++ export interface TracingView {+ readonly id: string;+ readonly short_id: string;+ /**+ * Human-readable name shown in the saved views list.+ * @maxLength 400+ */+ name: string;+ /** Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode. */+ filters?: TracingViewFilters;+ /** Whether the view is pinned for quick access. */+ pinned?: boolean;+ readonly created_at: string;+ /** User who created the view. */+ readonly created_by: UserBasic | null;+ /** @nullable */+ readonly updated_at: string | null;+ }++ export interface PaginatedTracingViewList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: TracingView[];+ }+/*** Insight enriched with view-count and recent-viewer fields, used by the trending action.*/@@ -41470,6 +41503,30 @@ export namespace Schemas {queue_id?: string | null;}+ /**+ * Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode.+ */+ export type PatchedTracingViewFilters = { [key: string]: unknown };++ export interface PatchedTracingView {+ readonly id?: string;+ readonly short_id?: string;+ /**+ * Human-readable name shown in the saved views list.+ * @maxLength 400+ */+ name?: string;+ /** Saved tracing filters — a subset of the frontend TracingFilters shape. May contain dateRange, serviceNames, filterGroup, orderBy, orderDirection, and viewMode. */+ filters?: PatchedTracingViewFilters;+ /** Whether the view is pinned for quick access. */+ pinned?: boolean;+ readonly created_at?: string;+ /** User who created the view. */+ readonly created_by?: UserBasic | null;+ /** @nullable */+ readonly updated_at?: string | null;+ }+export type SessionReplayListWidgetUpdateRequestOpenApiWidgetType = typeof SessionReplayListWidgetUpdateRequestOpenApiWidgetType[keyof typeof SessionReplayListWidgetUpdateRequestOpenApiWidgetType];@@ -58255,6 +58312,17 @@ export namespace Schemas {SpanResourceAttribute: 'span_resource_attribute',} as const;+ export type EnvironmentsTracingViewsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type EnvironmentsUserInterviewTopicsListParams = {/*** Number of results to return per page.@@ -65586,6 +65654,17 @@ export namespace Schemas {SpanResourceAttribute: 'span_resource_attribute',} as const;+ export type TracingViewsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type UploadedMediaCreate201 = { [key: string]: unknown };export type UserInterviewTopicsListParams = {