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.

revert: "feat(dashboards): metric widgets replace the metrics insight tab" (#127286)

Frank Hamandd7e6c93c7b62
diff --git a/.agents/skills/manage-dashboard-widgets/references/architecture.md b/.agents/skills/manage-dashboard-widgets/references/architecture.md
index 2bea1f96d8f1..1b9c871abb52 100644
--- a/.agents/skills/manage-dashboard-widgets/references/architecture.md
+++ b/.agents/skills/manage-dashboard-widgets/references/architecture.md
@@ -64,8 +64,6 @@ Dashboards already have **insight tiles** for HogQL/query visualizations — com
If intake is chart-only, **stop** — help the engineer add the right insight to the dashboard instead of a new `widget_type`. Lists may include small non-chart metadata (badges, sparklines in a row) when the product scene does; the tile body is still a list, not a chart canvas.
-**Exception: `metrics`.** Metrics are not an insight type, so the `metrics` widget is the dashboard chart for them. It reuses the metrics product's editor (builder, PromQL, SQL), runner, and panels, and follows the dashboard date range like an insight tile (`dashboard_filter_keys`). Do not use it as a precedent for a chart over an insight query kind.
-
Per-type add flow (ordered checklist): [checklist-new-widget-type.md](checklist-new-widget-type.md).
## Backend registry entry shape
@@ -95,8 +93,6 @@ WIDGET_SPECS[YOUR_TYPE] = WidgetSpec(
```
- Config validation is **Pydantic-only** — no per-type `validate_<type>_config` functions
-- Optional `WidgetSpec` fields: `dashboard_filter_keys` (the `DashboardFilter` keys the widget follows; run_widgets passes `dashboard_id` and only those keys, saved filters merged with the viewer's override, and the manifest writes them as `dashboardFilterKeys` so the frontend refetches the tile only when one of them changes), `session_throttle="per_viewer"` (a browser session counts against a per-viewer chart throttle instead of the shared per-team widget throttle; API keys and OAuth keep the shared one), `public_config_exclude` (config keys shared dashboards never receive), `creation_flag` (also written to `widget-form-fields.json` as `creationFlag`, which hides the type in the picker)
-- Raise `WidgetQueryError(message)` from `widgets/errors.py` for an expected failure the viewer should read (no access, an invalid query). The tile shows the message; other exceptions show a generic error and are logged
- `run_<type>_widget` lives in `widgets/<widget_type>.py` — call the **same** query runner the standalone product uses
- Registry wiring checklist: [checklist-new-widget-type.md §1–2](checklist-new-widget-type.md)
- Product RBAC: [permissions-and-sharing.md § Product RBAC](permissions-and-sharing.md#product-rbac)
@@ -125,8 +121,6 @@ Catalog entry in `widget_types/catalog.ts` drives add modal, layouts, headers, a
Optional catalog `availability` declares project setup prerequisites (exception autocapture, etc.). Gating runs at **tile render** via `WidgetRuntimeAvailabilityGuard`, not in the add modal — see [availability-and-gating.md](availability-and-gating.md).
-Other optional catalog fields: `pickerPresets` (several picker cards for one `widget_type`, each with its own label and `defaultConfig`; selection keys are `<widget_type>:<preset id>` and previews get `presetId`), `openEditorOnAdd` (the settings modal opens when one such tile is added), and `dashboardControls(config)` (the dashboard filter controls the tile follows, for a spec with `dashboard_filter_keys`). Registry entries can set `getDefaultTitle(config)` for the card title of an unnamed tile.
-
## Widget type vs catalog group
| Field | Role |
diff --git a/bin/build-dashboard-widget-types.py b/bin/build-dashboard-widget-types.py
index ac8023231b36..fbb51685d2ff 100755
--- a/bin/build-dashboard-widget-types.py
+++ b/bin/build-dashboard-widget-types.py
@@ -109,8 +109,6 @@ def main() -> int:
"formSchemaExport": config_schema_export.replace("ConfigSchema", "FormSchema"),
"formFields": list(spec.form_fields),
"live": spec.is_live,
- "creationFlag": spec.creation_flag,
- "dashboardFilterKeys": list(spec.dashboard_filter_keys),
}
FORM_FIELDS_JSON.write_text(json.dumps({"widgets": form_fields_manifest}, indent=2) + "\n", encoding="utf-8")
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 9d420589da2a..f7c08a422c45 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6879,9 +6879,9 @@ snapshots:
products-dashboards-add-insight-to-dashboard-modal--with-more-insight-types--light:
hash: v1.k794b7964.6c001db5555f48832f11ae8d9dcc535dff4e22044bb6dfce15db3a2a522f1fa9.GQCxp64JkEqDCNEeSD6gPtc5rwlzjHFJ-QnZu4lRips
products-dashboards-dashboard-widgets-overview--all-widget-types--dark:
- hash: v1.k794b7964.8c43b61d44c87ddef002ef6b5ab9e3d906faa7162bf6531250930b0c2b295c35.EX8sBg56ArQHH22POg64OBvuwXb7w1vhtF3O_OWQ_Bw
+ hash: v1.k794b7964.3b3689c002c42da7502405c35d4ebe2285aeaeda2015418d9e700bfe9dc47205.ByGuHj3aUBKZNgl5AzGDwbuMXT-HGQhG-Vcab7mz4Yw
products-dashboards-dashboard-widgets-overview--all-widget-types--light:
- hash: v1.k794b7964.1e52efb65d57a638a089968e83d52c7a8239361ec0ecf67e124fbf0dd27fc877.XBN5pZxH9EHRJuDFVYlEDeODhVz53t1wkWUsjooK-Ds
+ hash: v1.k794b7964.5e698b6d14402a5cec101c50a753e278e4df1ee6b6716173f979dd5fc1ca4ed8.lU9zONwMvT_2B6JdB4yli0CxsyWPoQZyPrag6_qyNv4
products-dashboards-dashboard-widgets-widget-types-activity-recent-events--default--dark:
hash: v1.k794b7964.c69d28ef03335511de9b7dd75d5ad1c0458272d5d8f340083cdb86acc3b3c888.KB3MNhE9xEjVSl9hmVpz2jLC0IAmOTvaVZBmrl3pNKs
products-dashboards-dashboard-widgets-widget-types-activity-recent-events--default--light:
@@ -6994,42 +6994,6 @@ snapshots:
hash: v1.k794b7964.4ae62d5f33b6c84c07ea4ba432e926a6932d8fce7032c5b97fa64aa7108b830e.YIiqojByDCspu7LkfSZvjalgZDPBtEgZ9Ik6VxowBPw
products-dashboards-dashboard-widgets-widget-types-logs-recent-logs-widget-settings--default--light:
hash: v1.k794b7964.6e8bbccc040e6efa945f7c581b7572d10b842114ce968c7a68534942e5a7bb5c.bFiSuo3krHeearnHMvK9Efsexc9ejeP4GqPsfkR2txw
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--empty--dark:
- hash: v1.k794b7964.f7ba811737d04cd844fc12444253e2a876822c483a6821418ea0f9057194276d.w_FOcDxRQZl5DSiAm0T036an4BHl545n4zojpXkNq1E
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--empty--light:
- hash: v1.k794b7964.7e402b3ecfd9192da5b0e929e66aa929f71b42a071959f4942d6fc7977b27c7d.oOJzLSuzxn8FMiaX5kNQc0AidRlzU0ANyCuV24emISI
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--heatmap--dark:
- hash: v1.k794b7964.f2ba57221f4b4730331c662011ddf7f7474008568e3f21628f057d7ac8515cda.A7P6RaGuIzsiZ6kIbc-by4MUsmZbRmJCR1V_wUICU4I
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--heatmap--light:
- hash: v1.k794b7964.6a7d1b531d7b30be44d2df2e9891eb004e39e5e1ffbf5b1c1f369b2ccbec0238.HwCaGtfRr-JPrM_P97OPsBEoJtNpCTrYhL6rG4dZ87I
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--loading--dark:
- hash: v1.k794b7964.656efed3600f9c6dc797a18a3c4f5ea40a4883c789a83bfa93ee817b545c7cbd.zPXiDW3B3iMt2URkJj9wPcnuhdy2MwT6NJ6AoTzzvGg
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--loading--light:
- hash: v1.k794b7964.7f1d4200a23fb9ee6699f98d51bae3e7fdae7736e6594577c695b93ae48be0dc.5fpV9CP-yIC40UqOf55Z4AlYIo2kd1vV2QS5G91yfUU
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--needs-configuration--dark:
- hash: v1.k794b7964.3b61e2348f1c46a34e61bc054c20530af1edbe74a3e441410847cb4a81e86409.4KORbUfNeTHacsiOTSwtyxNy6Ns8pVjd7RBGYZxXCMI
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--needs-configuration--light:
- hash: v1.k794b7964.618f1ed31d077047ac4ba6f1c8f7ed09dde201ff0b7b3242708f87ca6be5f6b0.t3Pi_SkiyiaA6YvEzoho8hRwDwPjbbFrpOcY8P2gpio
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--query-error--dark:
- hash: v1.k794b7964.2cf4aaf8f66007712dd4ea3fac6b3698524dbc8edb1684d40acea8dd22d39179.RKhzGH05CQH6xQ8DDtdM7xdjzsqumaIQF17PqLRHv1w
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--query-error--light:
- hash: v1.k794b7964.28ca3b6b6a6759baf88c5606a873960238e4ab8b272f698b1c3f0f55fa8d7aff.cgKlw5If6dkFl0Q49jmYJ2kZ99OuJfh42EwXdCPJEIU
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--single-stat--dark:
- hash: v1.k794b7964.c5cd37c72bd95f6aa01a44214ab95eaa72edd6ca426485ecdfde61c81a545557.5Azw3P2-43IkuxQp_wJHvhNQr8AT-ud_atFAumNjNAE
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--single-stat--light:
- hash: v1.k794b7964.8e5bda7d611f39f9094e7c132f8f838c4be1941b80b7f14c9239da5358204382.xFzOX_rEuF5UBXuTo6rCiDHALE61UwKEn2ZXvIXHI9A
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--time-series--dark:
- hash: v1.k794b7964.01b23320f1eebe34fb4518f04d69b4707e6a5de9f48dad8beedf430eef0bf5c5.-iLOxV4X47VntW-8aaOOW-SapIw5aZCnyrO574NpB6w
- products-dashboards-dashboard-widgets-widget-types-metrics-metric--time-series--light:
- hash: v1.k794b7964.6a5e9931dbe549ffd359e0eaf70bafccb31d72b5804fdda694fc07a8d2abc072.TO1KQ3lkC1Z67EhSMswAtma7spAyiQssclUdI3Riigk
- products-dashboards-dashboard-widgets-widget-types-metrics-metric-widget-settings--new-widget--dark:
- hash: v1.k794b7964.1fdc14837ad9dd6e477abf5f4767d74e10bb119962d9da7f21c6a31db7aa9ba4.Dr-Wy1eCsbA9GbiIbPZYvhAuB2zqznBjH8Beni4_yKA
- products-dashboards-dashboard-widgets-widget-types-metrics-metric-widget-settings--new-widget--light:
- hash: v1.k794b7964.96fbffa52477ca4a8c218fd89b3f984342f065e17655becd89a4dc991f9f1d4d.arVe4ghgxMHLt5Z1GFJvMlza5YkZgR4z0sSJ2WAXZSI
- products-dashboards-dashboard-widgets-widget-types-metrics-metric-widget-settings--with-metric--dark:
- hash: v1.k794b7964.081ec41b751bbc0ee6e1d65709af7b7a9666809ab0c170e3bb2822bf21a08fd8.tRqnxwL5wvYZrK46-jSpohuoshXCpyO2lgJeWtwjj8A
- products-dashboards-dashboard-widgets-widget-types-metrics-metric-widget-settings--with-metric--light:
- hash: v1.k794b7964.d45a20b1751f24866a3ea59bc9d132c7a28e0c2828d21e5cc2b6f8cdfa342aca.3cID6iAU3vmGYGEC3TFL4MR3QrBa17uhX3fgvzhsSvs
products-dashboards-dashboard-widgets-widget-types-metrics-metrics-table--empty--dark:
hash: v1.k794b7964.4f059c7baaf27703213dd545b602a2895498f592d171381453d1f826542d02ea.Zglpsr767jz-_6zt0OahlYMiaVcXH9hCTinkPNAvUYA
products-dashboards-dashboard-widgets-widget-types-metrics-metrics-table--empty--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index eb478e28e07b..e17054fe6d93 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -653,6 +653,7 @@ export const INSIGHT_VISUAL_ORDER = {
lifecycle: 60,
calendarHeatmap: 70,
sql: 80,
+ metrics: 85,
hog: 90,
}
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index f0a35c0a010c..da1f98c32174 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -27,6 +27,7 @@ import {
HogQLFilters,
HogQLQuery,
HogQLVariable,
+ MetricsQuery,
Node,
NodeKind,
ProductItemCategory,
@@ -2304,6 +2305,17 @@ export const getTreeItemsNew = (): FileSystemImport[] => [
visualOrder: INSIGHT_VISUAL_ORDER.lifecycle,
sceneKeys: ['Insight'],
},
+ {
+ path: `Insight/Metrics`,
+ type: 'insight',
+ href: urls.insightNew({
+ query: { kind: NodeKind.MetricsQuery, clauses: [], dateRange: { date_from: '-1h' } } as MetricsQuery,
+ }),
+ flag: FEATURE_FLAGS.METRICS_INSIGHT_BUILDER,
+ iconType: 'metrics',
+ visualOrder: INSIGHT_VISUAL_ORDER.metrics,
+ sceneKeys: ['Insight'],
+ },
{
path: `Insight/Retention`,
type: 'insight',
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index fe8c445b1687..becd61ec3647 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -121,7 +121,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
copyGroupToDashboardLoading,
widgetResultsByTileId,
widgetRefreshStatus,
- widgetEditorTileId,
scrollToBottomSignal,
sizeKey,
tileGroupSectionsEnabled,
@@ -160,7 +159,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
selectTileGroupTab,
updateTileGroupSectionLayout,
moveTileToSection,
- setWidgetEditorTileId,
} = useActions(dashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
// dashboard_tiles is empty because this selector covers a whole group, not one tile; the
@@ -758,8 +756,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
error={getDashboardWidgetFetchDisplayError(runResult?.error ?? refreshState?.error)}
loading={!!refreshState?.loading}
lastFetchedAt={refreshState?.fetchedAt}
- openEditorOnMount={widgetEditorTileId === tile.id}
- onEditorClose={widgetEditorTileId === tile.id ? () => setWidgetEditorTileId(null) : undefined}
onRefresh={tileActions.refreshWidget}
onRefreshWidgetData={scheduleRefreshDashboardWidgets}
onApplyWidgetIssueMetadataChange={onWidgetIssueMetadataChange}
diff --git a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
index b19648878a0f..77e14203a1e0 100644
--- a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
+++ b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
@@ -1,12 +1,7 @@
-import { useActions, useAsyncActions, useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { BindLogic } from 'kea'
import posthog from 'posthog-js'
-import {
- getDashboardWidgetGroupIcon,
- getDashboardWidgetPickerItem,
-} from '@posthog/products-dashboards/frontend/widget_types/catalog'
-
import { IconInsightFunnels, IconInsightRetention, IconInsightTrends } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -25,9 +20,6 @@ import { AddSavedInsightsToDashboard } from 'products/product_analytics/frontend
import { addInsightToDashboardLogic } from '../addInsightToDashboardModalLogic'
import { dashboardLogic } from '../dashboardLogic'
-const METRICS_WIDGET_PICKER_ITEM = getDashboardWidgetPickerItem('metrics:time_series')
-const MetricsWidgetIcon = getDashboardWidgetGroupIcon('metrics')
-
const QUICK_CREATE_TYPES = [
{ type: InsightType.TRENDS, icon: IconInsightTrends, label: 'Trend' },
{ type: InsightType.FUNNELS, icon: IconInsightFunnels, label: 'Funnel' },
@@ -37,8 +29,7 @@ const QUICK_CREATE_TYPES = [
export function AddInsightToDashboardModal(): JSX.Element {
const { hideAddInsightToDashboardModal, toggleShowMoreInsightTypes } = useActions(addInsightToDashboardLogic)
const { addInsightToDashboardModalVisible, showMoreInsightTypes } = useValues(addInsightToDashboardLogic)
- const { dashboard, addWidgetTileLoading } = useValues(dashboardLogic)
- const { addWidgetTiles } = useAsyncActions(dashboardLogic)
+ const { dashboard } = useValues(dashboardLogic)
const { featureFlags } = useValues(featureFlagLogic)
const handleClose = (): void => {
@@ -53,30 +44,6 @@ export function AddInsightToDashboardModal(): JSX.Element {
handleClose()
}
- // New metrics charts are metric widgets, so this adds a widget and opens its editor instead of the insight editor.
- const offerMetricsWidget =
- !!METRICS_WIDGET_PICKER_ITEM &&
- METRICS_WIDGET_PICKER_ITEM.requiredFlags.every(
- (flag) => !!(featureFlags as Record<string, boolean | string | undefined>)[flag]
- )
-
- const handleNewMetricsWidgetClicked = async (): Promise<void> => {
- if (!dashboard?.id || !METRICS_WIDGET_PICKER_ITEM) {
- return
- }
- posthog.capture('insight dashboard modal - new insight clicked', {
- insight_type: METRICS_WIDGET_PICKER_ITEM.widgetType,
- })
- // addWidgetTiles toasts and rethrows on failure, so the modal stays open for another try.
- await addWidgetTiles({
- dashboardId: dashboard.id,
- widgets: [
- { widgetType: METRICS_WIDGET_PICKER_ITEM.widgetType, config: METRICS_WIDGET_PICKER_ITEM.defaultConfig },
- ],
- })
- handleClose()
- }
-
const additionalTypes = Object.entries(INSIGHT_TYPES_METADATA).filter(
([type, meta]) =>
isInsightTypeCreatable(meta, featureFlags) &&
@@ -148,19 +115,6 @@ export function AddInsightToDashboardModal(): JSX.Element {
</LemonButton>
)
})}
- {offerMetricsWidget ? (
- <LemonButton
- type="tertiary"
- fullWidth
- icon={MetricsWidgetIcon ? <MetricsWidgetIcon /> : undefined}
- loading={addWidgetTileLoading}
- disabledReason={!dashboard?.id ? 'Loading dashboard' : undefined}
- data-attr="create-metrics-widget"
- onClick={() => void handleNewMetricsWidgetClicked().catch(() => {})}
- >
- Metrics
- </LemonButton>
- ) : null}
</div>
}
>
diff --git a/frontend/src/scenes/dashboard/dashboardControls.test.ts b/frontend/src/scenes/dashboard/dashboardControls.test.ts
index 1105dbe4d7a1..c10d00fa4bed 100644
--- a/frontend/src/scenes/dashboard/dashboardControls.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardControls.test.ts
@@ -28,17 +28,17 @@ describe('dashboardControls', () => {
expect(dashboardControlsForQuery(tile.insight?.query)).toEqual(expected)
})
- it('counts the insights and metric widgets that each control changes', () => {
- const scopes = getDashboardControlScopes([trendsTile, retentionTile, metricsTile], [['dateRange']])
+ it('counts the insights that each control changes', () => {
+ const scopes = getDashboardControlScopes([trendsTile, retentionTile, metricsTile])
- expect(scopes.dateRange).toEqual({ applies: 4, total: 4 })
- expect(scopes.interval).toEqual({ applies: 1, total: 4 })
- expect(scopes.properties).toEqual({ applies: 2, total: 4 })
- expect(scopes.metricVariables).toEqual({ applies: 1, total: 4 })
+ expect(scopes.dateRange).toEqual({ applies: 3, total: 3 })
+ expect(scopes.interval).toEqual({ applies: 1, total: 3 })
+ expect(scopes.properties).toEqual({ applies: 2, total: 3 })
+ expect(scopes.metricVariables).toEqual({ applies: 1, total: 3 })
})
it.each([
- [{ applies: 4, total: 9 }, 'Applies to 4 of 9 charts'],
+ [{ applies: 4, total: 9 }, 'Applies to 4 of 9 insights'],
[{ applies: 9, total: 9 }, null],
[{ applies: 0, total: 9 }, null],
[{ applies: 0, total: 0 }, null],
diff --git a/frontend/src/scenes/dashboard/dashboardControls.ts b/frontend/src/scenes/dashboard/dashboardControls.ts
index 4d7213e7434c..df255e9729a3 100644
--- a/frontend/src/scenes/dashboard/dashboardControls.ts
+++ b/frontend/src/scenes/dashboard/dashboardControls.ts
@@ -12,9 +12,9 @@ export type DashboardControl =
| 'metricVariables'
export interface DashboardControlScope {
- /** Chart tiles that the control changes. */
+ /** Insight tiles that the control changes. */
applies: number
- /** All chart tiles on the dashboard: insights, and widgets that follow dashboard filters. */
+ /** All insight tiles on the dashboard. */
total: number
}
@@ -47,35 +47,30 @@ export function dashboardControlsForQuery(query: Node | null | undefined): Dashb
return (source?.kind && CONTROLS_BY_QUERY_KIND[source.kind as NodeKind]) || DEFAULT_CONTROLS
}
-/** `widgetControls` holds the controls of each widget tile that follows dashboard filters. */
export function getDashboardControlScopes(
- insightTiles: DashboardTile[],
- widgetControls: DashboardControl[][] = []
+ insightTiles: DashboardTile[]
): Record<DashboardControl, DashboardControlScope> {
- const tileControls = [
- ...insightTiles.map((tile) => dashboardControlsForQuery(tile.insight?.query)),
- ...widgetControls,
- ]
+ const queries = insightTiles.map((tile) => tile.insight?.query)
const scopes = Object.fromEntries(
- ALL_CONTROLS.map((control) => [control, { applies: 0, total: tileControls.length }])
+ ALL_CONTROLS.map((control) => [control, { applies: 0, total: queries.length }])
) as Record<DashboardControl, DashboardControlScope>
- for (const controls of tileControls) {
- for (const control of controls) {
+ for (const query of queries) {
+ for (const control of dashboardControlsForQuery(query)) {
scopes[control].applies++
}
}
return scopes
}
-/** Text for a control that changes only some of the charts. Null when it changes all or none of them. */
+/** Text for a control that changes only some of the insights. Null when it changes all or none of them. */
export function dashboardControlScopeText(scope: DashboardControlScope): string | null {
if (scope.applies === 0 || scope.applies === scope.total) {
return null
}
- return `Applies to ${scope.applies} of ${scope.total} charts`
+ return `Applies to ${scope.applies} of ${scope.total} insights`
}
-/** A control that changes no chart is hidden, unless it has a value that the user must be able to clear. */
+/** A control that changes no insight is hidden, unless it has a value that the user must be able to clear. */
export function isDashboardControlHidden(scope: DashboardControlScope, hasValue: boolean): boolean {
return scope.total > 0 && scope.applies === 0 && !hasValue
}
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index f4d6841b1e71..9be47b9b0582 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -6272,10 +6272,7 @@ describe('dashboardLogic', () => {
expect(fetchRunWidgetsMock).not.toHaveBeenCalled()
})
- it.each([
- ['a network error', new Error('Network error')],
- ['a gateway timeout', Object.assign(new Error('Gateway timeout'), { status: 504 })],
- ])('refreshDashboardWidgets sets friendly error when run_widgets fails with %s', async (_name, error) => {
+ it('refreshDashboardWidgets sets friendly error when run_widgets fails', async () => {
logic = dashboardLogic({ id: 5 })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
@@ -6284,7 +6281,7 @@ describe('dashboardLogic', () => {
const previousFetchedAt = logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.fetchedAt
logic.actions.updateDashboardLastRefresh(dayjs())
expect(logic.values.blockRefresh).toBe(true)
- fetchRunWidgetsMock.mockRejectedValueOnce(error)
+ fetchRunWidgetsMock.mockRejectedValueOnce(new Error('Network error'))
await expectLogic(logic, () => {
logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
@@ -6466,151 +6463,41 @@ describe('dashboardLogic', () => {
resumeKeaLoadersErrors()
})
- it.each([
- ['error_tracking_list', { limit: 5 }, null],
- ['metrics', { query: { kind: 'MetricsQuery', clauses: [] } }, 99],
- ])(
- 'addWidgetTiles refreshes a new %s tile, and opens its settings when the type asks: %s',
- async (widgetType, config, expectedEditorTileId) => {
- const addedTile = {
- id: 99,
- widget: { id: '3', widget_type: widgetType, config },
- layouts: { sm: { i: '99', x: 0, y: 10, w: 6, h: 5 } },
- color: null,
- } as unknown as DashboardTile
-
- jest.spyOn(api, 'create').mockResolvedValueOnce({
- tiles: [addedTile],
- })
-
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- fetchRunWidgetsMock.mockResolvedValueOnce([
- {
- tile_id: addedTile.id,
- widget_type: widgetType,
- result: { results: [], hasMore: false },
- error: null,
- },
- ])
-
- await expectLogic(logic, () => {
- logic.actions.addWidgetTiles({
- dashboardId: 5,
- widgets: [{ widgetType, config }],
- })
- })
- .toDispatchActions(['refreshDashboardWidgets'])
- .toFinishAllListeners()
-
- expect(fetchRunWidgetsMock).toHaveBeenCalledWith(
- String(MOCK_TEAM_ID),
- 5,
- [addedTile.id],
- expect.anything()
- )
- expect(logic.values.widgetEditorTileId).toEqual(expectedEditorTileId)
- }
- )
-
- it('keeps the newest widget result when an older request for the tile returns last', async () => {
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- let releaseOlder: (value: Awaited<ReturnType<typeof widgetFetchUtils.fetchRunWidgets>>) => void = () => {}
- const result = (marker: string): Awaited<ReturnType<typeof widgetFetchUtils.fetchRunWidgets>> => [
- { tile_id: WIDGET_TILE.id, widget_type: 'error_tracking_list', result: { marker }, error: null },
- ]
- fetchRunWidgetsMock.mockClear()
- fetchRunWidgetsMock
- .mockImplementationOnce(() => new Promise((resolve) => (releaseOlder = resolve)))
- .mockResolvedValueOnce(result('newer'))
-
- logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
- // Let the older refresh pass its breakpoint and send its request before the newer one starts.
- await new Promise((resolve) => setTimeout(resolve, 0))
- expect(fetchRunWidgetsMock).toHaveBeenCalledTimes(1)
- await expectLogic(logic, () => {
- logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
- }).toDispatchActions(['setWidgetRunResults'])
- releaseOlder(result('older'))
- await expectLogic(logic).toFinishAllListeners()
-
- expect(logic.values.widgetResultsByTileId[WIDGET_TILE.id]?.result).toEqual({ marker: 'newer' })
- })
-
- it('keeps a previewed date range on a dashboard with only metric widgets', async () => {
- const metricsTile = {
- id: 9,
- widget: {
- id: '4',
- widget_type: 'metrics',
- config: { query: { kind: 'MetricsQuery', clauses: [{ name: 'a', metricName: 'cpu' }] } },
- },
- layouts: {},
+ it('addWidgetTiles refreshes newly created widget tiles', async () => {
+ const addedTile = {
+ id: 99,
+ widget: { id: '3', widget_type: 'error_tracking_list', config: { limit: 5 } },
+ layouts: { sm: { i: '99', x: 0, y: 10, w: 6, h: 5 } },
color: null,
} as unknown as DashboardTile
- useMocks({
- get: {
- '/api/environments/:team_id/dashboards/5/': () => [200, { ...dashboards[5], tiles: [metricsTile] }],
- },
+
+ jest.spyOn(api, 'create').mockResolvedValueOnce({
+ tiles: [addedTile],
})
+
logic = dashboardLogic({ id: 5 })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
- await expectLogic(logic, () => {
- logic.actions.setDates('-3h', null)
- }).toFinishAllListeners()
-
- expect(logic.values.previewedDashboardSettings?.filters.date_from).toEqual('-3h')
- expect(logic.values.effectiveRefreshFilters.date_from).toEqual('-3h')
- })
-
- it('refetches only the widgets that follow dashboard filters when the filters change', async () => {
- const metricsTile: DashboardTile = {
- id: 9,
- widget: {
- id: '4',
- widget_type: 'metrics',
- config: { query: { kind: 'MetricsQuery', clauses: [{ name: 'a', metricName: 'cpu' }] } },
- },
- layouts: {},
- color: null,
- } as unknown as DashboardTile
- useMocks({
- get: {
- '/api/environments/:team_id/dashboards/5/': () => [
- 200,
- { ...dashboards[5], tiles: [...dashboards[5].tiles, WIDGET_TILE, metricsTile] },
- ],
+ fetchRunWidgetsMock.mockResolvedValueOnce([
+ {
+ tile_id: addedTile.id,
+ widget_type: 'error_tracking_list',
+ result: { results: [], hasMore: false },
+ error: null,
},
- })
- fetchRunWidgetsMock.mockImplementation(async (_projectId, _dashboardId, tileIds) =>
- tileIds.map((tileId) => ({ tile_id: tileId, widget_type: 'any', result: { results: [] }, error: null }))
- )
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- await expectLogic(logic, () => {
- logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id, metricsTile.id], forceRefresh: true })
- }).toFinishAllListeners()
- fetchRunWidgetsMock.mockClear()
+ ])
- logic.actions.setExternalFilters({ date_from: '-3h' })
await expectLogic(logic, () => {
- logic.actions.refreshDashboardWidgets({
- tileIds: [WIDGET_TILE.id, metricsTile.id],
- forceRefresh: false,
+ logic.actions.addWidgetTiles({
+ dashboardId: 5,
+ widgets: [{ widgetType: 'error_tracking_list', config: { limit: 5 } }],
})
- }).toFinishAllListeners()
+ })
+ .toDispatchActions(['refreshDashboardWidgets'])
+ .toFinishAllListeners()
- const fetchedTileIds = fetchRunWidgetsMock.mock.calls.flatMap(([, , tileIds]) => tileIds)
- expect(fetchedTileIds).toContain(metricsTile.id)
- expect(fetchedTileIds).not.toContain(WIDGET_TILE.id)
- expect(fetchRunWidgetsMock.mock.calls.at(-1)?.[3]?.filtersOverride).toMatchObject({ date_from: '-3h' })
+ expect(fetchRunWidgetsMock).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 5, [addedTile.id], expect.anything())
})
it('addWidgetTiles keeps an existing tile movement unsaved', async () => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 854e3b633f29..06536fa62b0b 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -28,8 +28,6 @@ import { LemonButton, LemonDialog, lemonToast } from '@posthog/lemon-ui'
import { dashboardsCopyGroupCreate } from '@posthog/products-dashboards/frontend/generated/api'
import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'
import { isWidgetConfigValidationError, updateDashboardWidgetTile } from '@posthog/products-dashboards/frontend/utils'
-import { tryGetDashboardWidgetCatalogEntry } from '@posthog/products-dashboards/frontend/widget_types/catalog'
-import { getDashboardWidgetFilterKeys } from '@posthog/products-dashboards/frontend/widget_types/widgetManifest'
import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'
import {
applyIssueMetadataToWidgetListResult,
@@ -76,7 +74,6 @@ import {
findNewlyAddedWidgetTiles,
isWidgetStale,
WIDGET_CLIENT_TTL_MS,
- widgetDashboardFilters,
} from 'scenes/dashboard/widgetFetchUtils'
import { createDashboardWidgetTileRefreshScheduler } from 'scenes/dashboard/widgetTileRefreshScheduler'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
@@ -833,8 +830,6 @@ export interface dashboardLogicValues {
urlVariables: Record<string, HogQLVariable>
variablesDirty: boolean
waitingTileRefresh: WaitingTileRefresh | null
- widgetEditorTileId: number | null
- widgetFiltersKeys: Record<number, string>
widgetRefreshStatus: Record<
number,
{
@@ -1164,8 +1159,7 @@ export interface dashboardLogicActions {
forceRefresh?: boolean | undefined
previewUnsavedFilters?: boolean | undefined
}
- refreshDashboardWidgets: (payload: { filters?: DashboardFilter; forceRefresh?: boolean; tileIds: number[] }) => {
- filters?: DashboardFilter | undefined
+ refreshDashboardWidgets: (payload: { forceRefresh?: boolean; tileIds: number[] }) => {
forceRefresh?: boolean | undefined
tileIds: number[]
}
@@ -1468,12 +1462,6 @@ export interface dashboardLogicActions {
setWaitingTileRefresh: (waiting: WaitingTileRefresh) => {
waiting: WaitingTileRefresh
}
- setWidgetEditorTileId: (tileId: number | null) => {
- tileId: number | null
- }
- setWidgetFiltersKeys: (filtersKeys: Record<number, string>) => {
- filtersKeys: Record<number, string>
- }
setWidgetRefreshStatuses: (
tileIds: number[],
loading: boolean,
@@ -1762,10 +1750,7 @@ export interface dashboardLogicMeta {
collapsedTileIds: (tileGroupKeys: Map<number, string>, collapsedTileGroupKeys: string[]) => Set<number>
insightTiles: (tiles: DashboardTile[]) => DashboardTile[]
textTiles: (tiles: DashboardTile[]) => DashboardTile[]
- dashboardControlScopes: (
- insightTiles: DashboardTile[],
- widgetTiles: DashboardTile[]
- ) => Record<DashboardControl, DashboardControlScope>
+ dashboardControlScopes: (insightTiles: DashboardTile[]) => Record<DashboardControl, DashboardControlScope>
itemsLoading: (
dashboardLoading: boolean,
dashboardStreaming: boolean,
@@ -2040,9 +2025,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
forceRefresh?: boolean
previewUnsavedFilters?: boolean
}) => payload,
- /** `filters` are the dashboard filters the insights refresh with; the applied filters by default. */
- refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean; filters?: DashboardFilter }) =>
- payload,
+ refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean }) => payload,
toggleTileGroup: (groupKey: string) => ({ groupKey }),
selectTileGroupTab: (sectionKey: string) => ({ sectionKey }),
refreshOpenTileGroupsWaiting: true,
@@ -2081,9 +2064,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
widgets: { widgetType: string; config: Record<string, unknown> }[]
}) => payload,
setAddWidgetModalOpen: (open: boolean) => ({ open }),
- /** A newly added tile whose widget settings open as soon as it renders. */
- setWidgetEditorTileId: (tileId: number | null) => ({ tileId }),
- setWidgetFiltersKeys: (filtersKeys: Record<number, string>) => ({ filtersKeys }),
toggleAddWidgetSelectedType: (widgetType: string) => ({ widgetType }),
clearAddWidgetSelectedTypes: true,
toggleAddWidgetCollapsedGroup: (groupId: string) => ({ groupId }),
@@ -3438,19 +3418,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
}),
},
],
- // The dashboard filters each widget tile last ran with, for widgets that follow dashboard filters.
- widgetFiltersKeys: [
- {} as Record<number, string>,
- {
- setWidgetFiltersKeys: (state, { filtersKeys }) => ({ ...state, ...filtersKeys }),
- },
- ],
- widgetEditorTileId: [
- null as number | null,
- {
- setWidgetEditorTileId: (_, { tileId }) => tileId,
- },
- ],
refreshEligibilityTick: [0, { recheckRefreshEligibility: (state) => state + 1 }],
addWidgetTileLoading: [
false,
@@ -3992,21 +3959,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
],
textTiles: [(s) => [s.tiles], (tiles: DashboardTile[]) => tiles.filter((t) => !!t.text)],
dashboardControlScopes: [
- (s) => [s.insightTiles, s.widgetTiles],
- (
- insightTiles: DashboardTile[],
- widgetTiles: DashboardTile[]
- ): Record<DashboardControl, DashboardControlScope> =>
- getDashboardControlScopes(
- insightTiles,
- widgetTiles.flatMap((tile) => {
- const widget = tile.widget
- const dashboardControls = widget
- ? tryGetDashboardWidgetCatalogEntry(widget.widget_type)?.dashboardControls
- : undefined
- return widget && dashboardControls ? [dashboardControls(widget.config)] : []
- })
- ),
+ (s) => [s.insightTiles],
+ (insightTiles: DashboardTile[]): Record<DashboardControl, DashboardControlScope> =>
+ getDashboardControlScopes(insightTiles),
],
itemsLoading: [
(s) => [s.dashboardLoading, s.dashboardStreaming, s.refreshStatus, s.initialVariablesLoaded],
@@ -5473,18 +5428,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
const sortedTilesToRefresh = staleTiles.filter((tile) => !collapsedTileIds.has(tile.id))
const widgetTileIds = values.widgetTiles.map((tile) => tile.id)
const openWidgetTileIds = widgetTileIds.filter((id) => !collapsedTileIds.has(id))
- let widgetsRefreshed = false
- const refreshWidgets = (): void => {
- if (widgetsRefreshed || openWidgetTileIds.length === 0) {
- return
- }
- widgetsRefreshed = true
- actions.refreshDashboardWidgets({
- tileIds: openWidgetTileIds,
- forceRefresh: !!forceRefresh,
- filters: combineDashboardFilters(settingsToRefresh.filters, values.externalFilters),
- })
- }
const waiting = nextWaitingTileRefresh({
previous: values.waitingTileRefresh,
tileGroupKeys: values.tileGroupKeys,
@@ -5517,9 +5460,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.abortAnyRunningQuery()
cache.abortController = new AbortController()
- // Widgets load alongside the insights, so a filter change reaches metric widgets without
- // waiting for every insight to finish.
- refreshWidgets()
}
const openGroupsWaiting = (): Set<string> =>
@@ -5663,7 +5603,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.forceRefreshIfStale()
}
- refreshWidgets()
+ if (openWidgetTileIds.length > 0) {
+ actions.refreshDashboardWidgets({ tileIds: openWidgetTileIds, forceRefresh: !!forceRefresh })
+ }
},
toggleTileGroup: ({ groupKey }) => {
const collapse = !values.collapsedTileGroupKeys.includes(groupKey)
@@ -5799,34 +5741,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
})
)
},
- refreshDashboardWidgets: async ({ tileIds, forceRefresh, filters }, breakpoint) => {
+ refreshDashboardWidgets: async ({ tileIds, forceRefresh }, breakpoint) => {
if (values.placement === DashboardPlacement.Export || values.placement === DashboardPlacement.Public) {
return
}
- const dashboardFilters = filters ?? values.effectiveRefreshFilters
- const filterKeysByTileId = new Map(
- values.widgetTiles.map((tile) => [
- tile.id,
- tile.widget ? getDashboardWidgetFilterKeys(tile.widget.widget_type) : [],
- ])
- )
- // Each tile's key covers only the filters it follows, so a tile refetches only when one of them changes.
- const filtersKeyByTileId: Record<number, string> = Object.fromEntries(
- tileIds.map((tileId) => [
- tileId,
- JSON.stringify(widgetDashboardFilters(dashboardFilters, filterKeysByTileId.get(tileId) ?? [])),
- ])
- )
- const filtersChanged = (tileId: number): boolean =>
- values.widgetFiltersKeys[tileId] !== undefined &&
- values.widgetFiltersKeys[tileId] !== filtersKeyByTileId[tileId]
- // A tile whose filters changed loads again even while an older load runs, so the newest filters win.
const loadingTileIds = forceRefresh
? []
- : tileIds.filter((tileId) => values.widgetRefreshStatus[tileId]?.loading && !filtersChanged(tileId))
+ : tileIds.filter((tileId) => values.widgetRefreshStatus[tileId]?.loading)
const staleTileIds = tileIds.filter((tileId) => {
- if (forceRefresh || filtersChanged(tileId)) {
+ if (forceRefresh) {
return true
}
const fetchedAt = values.widgetRefreshStatus[tileId]?.fetchedAt
@@ -5854,46 +5778,21 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setWidgetRefreshStatuses(staleTileIds, true)
await breakpoint()
- // A later load of the same tile (after a filter change, say) wins, even when this one returns last.
- cache.widgetRefreshGeneration = (cache.widgetRefreshGeneration ?? 0) + 1
- const generation: number = cache.widgetRefreshGeneration
- const latestRefreshByTileId: Record<number, number> = (cache.widgetLatestRefreshByTileId ??= {})
- for (const tileId of staleTileIds) {
- latestRefreshByTileId[tileId] = generation
- }
- const isLatest = (tileId: number): boolean => latestRefreshByTileId[tileId] === generation
-
const projectId = String(values.currentTeamId)
const dashboardId = props.id
const queue = tileLoadQueue(cache)
const loadRefresh = { forceRefresh: !!forceRefresh, settings: values.settingsForRefresh }
const fetchFunctions = chunkTileIds(staleTileIds, 4).map((chunk) => async () => {
const { signal: chunkSignal, finish } = tileLoads(cache).start(chunk, signal, loadRefresh)
- const chunkFilterKeys = [...new Set(chunk.flatMap((tileId) => filterKeysByTileId.get(tileId) ?? []))]
try {
const results = await queue.run(
- () =>
- fetchRunWidgets(projectId, dashboardId, chunk, {
- signal: chunkSignal,
- filtersOverride:
- chunkFilterKeys.length > 0
- ? widgetDashboardFilters(dashboardFilters, chunkFilterKeys)
- : undefined,
- refresh: !!forceRefresh,
- }),
+ () => fetchRunWidgets(projectId, dashboardId, chunk, { signal: chunkSignal }),
chunkSignal
)
- const latestResults = results.filter((result) => isLatest(result.tile_id))
- actions.setWidgetRunResults(
- Object.fromEntries(latestResults.map((result) => [result.tile_id, result]))
- )
- actions.setWidgetFiltersKeys(
- Object.fromEntries(chunk.filter(isLatest).map((tileId) => [tileId, filtersKeyByTileId[tileId]]))
- )
- actions.clearWaitingTileRefresh(
- latestResults.filter((result) => !result.error).map((result) => result.tile_id)
- )
- for (const result of latestResults) {
+ const resultsByTileId = Object.fromEntries(results.map((result) => [result.tile_id, result]))
+ actions.setWidgetRunResults(resultsByTileId)
+ actions.clearWaitingTileRefresh(results.filter((result) => !result.error).map((r) => r.tile_id))
+ for (const result of results) {
actions.setWidgetRefreshStatuses(
[result.tile_id],
false,
@@ -5908,11 +5807,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
)
return
}
- actions.setWidgetRefreshStatuses(
- chunk.filter(isLatest),
- false,
- DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE
- )
+ actions.setWidgetRefreshStatuses(chunk, false, DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)
} finally {
finish()
}
@@ -5936,14 +5831,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
{ widgets: widgetsPayload }
)
const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)
- const [onlyCreatedTile] = createdTiles.length === 1 ? createdTiles : []
- // Set before the tile renders, so it mounts with its settings open.
- if (
- onlyCreatedTile?.widget &&
- tryGetDashboardWidgetCatalogEntry(onlyCreatedTile.widget.widget_type)?.openEditorOnAdd
- ) {
- actions.setWidgetEditorTileId(onlyCreatedTile.id)
- }
if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {
const dashboard = {
...values.dashboard,
diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts
index d851d05c466f..a9597ad98f30 100644
--- a/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts
+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts
@@ -1,7 +1,6 @@
-import type { DashboardFilter } from '~/queries/schema/schema-general'
import type { DashboardTile } from '~/types'
-import { chunkTileIds, findNewlyAddedWidgetTiles, isWidgetStale, widgetDashboardFilters } from './widgetFetchUtils'
+import { chunkTileIds, findNewlyAddedWidgetTiles, isWidgetStale } from './widgetFetchUtils'
describe('widgetFetchUtils', () => {
it('treats failed widgets as stale but not loading or missing widgets', () => {
@@ -45,32 +44,6 @@ describe('widgetFetchUtils', () => {
})
})
- describe('widgetDashboardFilters', () => {
- const DATE_KEYS = ['date_from', 'date_to']
-
- it.each([
- [
- 'keeps a cleared filter explicit, so it replaces the saved one',
- {},
- DATE_KEYS,
- { date_from: null, date_to: null },
- ],
- [
- 'keeps the widget keys and drops the rest',
- {
- date_from: '-1h',
- properties: [],
- breakdown_filter: {},
- metricVariables: [{ name: 'window', type: 'interval', values: ['5m'], current: '5m' }],
- },
- DATE_KEYS,
- { date_from: '-1h', date_to: null },
- ],
- ])('%s', (_name, filters, keys, expected) => {
- expect(widgetDashboardFilters(filters as DashboardFilter, keys)).toEqual(expected)
- })
- })
-
describe('chunkTileIds', () => {
it('returns empty array for empty input', () => {
expect(chunkTileIds([])).toEqual([])
diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.ts
index a8782a5cfe3f..2a4ad92d4509 100644
--- a/frontend/src/scenes/dashboard/widgetFetchUtils.ts
+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.ts
@@ -1,7 +1,6 @@
import { dashboardsRunWidgetsRetrieve } from '@posthog/products-dashboards/frontend/generated/api'
import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'
-import type { DashboardFilter } from '~/queries/schema/schema-general'
import type { DashboardTile } from '~/types'
import { DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES } from './dashboardUtils'
@@ -37,20 +36,8 @@ export function chunkTileIds(tileIds: number[], chunkSize = 4): number[][] {
return chunks
}
-/** The dashboard filters a widget follows (`WidgetSpec.dashboard_filter_keys`). Other keys would only make the
- * widget refetch for a change it ignores. Empty values stay in as null, because the server merges the override
- * onto the saved filters, and a cleared filter must replace the saved one. */
-export function widgetDashboardFilters(filters: DashboardFilter, keys: readonly string[]): DashboardFilter {
- const record = filters as Record<string, unknown>
- return Object.fromEntries([...keys].sort().map((key) => [key, record[key] ?? null])) as DashboardFilter
-}
-
export type FetchRunWidgetsOptions = {
signal?: AbortSignal
- /** The dashboard's current filters, for widgets that follow them. */
- filtersOverride?: DashboardFilter
- /** A manual refresh: widgets that follow dashboard filters skip their query cache. */
- refresh?: boolean
}
export async function fetchRunWidgets(
@@ -63,15 +50,10 @@ export async function fetchRunWidgets(
return []
}
- const filtersOverride = options?.filtersOverride
const response = await dashboardsRunWidgetsRetrieve(
projectId,
dashboardId,
- {
- tile_ids: tileIds.join(','),
- ...(filtersOverride ? { filters_override: JSON.stringify(filtersOverride) } : {}),
- ...(options?.refresh ? { refresh: true } : {}),
- },
+ { tile_ids: tileIds.join(',') },
{ signal: options?.signal }
)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 313a4519aec3..68f70402989a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -871,7 +871,6 @@ SPECTACULAR_SETTINGS = {
"ConversationsRecentTicketsWidgetTypeEnum": ["conversations_recent_tickets"],
"CanvasAppWidgetTypeEnum": ["canvas_app"],
"MetricsTableWidgetTypeEnum": ["metrics_table"],
- "MetricsWidgetTypeEnum": ["metrics"],
}
),
}
diff --git a/products/dashboards/AGENTS.md b/products/dashboards/AGENTS.md
index 0689f47c928a..fed42f5609a9 100644
--- a/products/dashboards/AGENTS.md
+++ b/products/dashboards/AGENTS.md
@@ -18,5 +18,5 @@ Do not treat every dashboard change as a widget change.
- Register every widget type in the backend and frontend registries.
- Define each widget config in `backend/widget_specs/configs.py` before you change generated frontend config types.
- Run `hogli build:openapi` after you change `widget_specs/`.
-- Use dashboard insight tiles for charts and trends of insight queries. Do not create a widget type for them. The metrics widgets (`metrics` and `metrics_table`) are the exception, because metrics are not an insight type.
+- Use dashboard insight tiles for charts and trends. Do not create a widget type for them.
- Read [`manage-dashboard-widgets`](../../.agents/skills/manage-dashboard-widgets/SKILL.md) when you add a widget type or change a shipped widget.
diff --git a/products/dashboards/CONTRIBUTING.md b/products/dashboards/CONTRIBUTING.md
index 0b79ea9d1311..f5ae5e8e600e 100644
--- a/products/dashboards/CONTRIBUTING.md
+++ b/products/dashboards/CONTRIBUTING.md
@@ -40,7 +40,7 @@ Layer table, registry shapes, copy/move, analytics, and typing details: [`.agent
**Critical rules:**
- Product RBAC is registry-driven — see [permissions-and-sharing.md § Product RBAC](../../.agents/skills/manage-dashboard-widgets/references/permissions-and-sharing.md#product-rbac).
-- **Charts/trends on a dashboard → insight tiles**, not new widget types — [architecture.md § Charts](../../.agents/skills/manage-dashboard-widgets/references/architecture.md#charts--use-insight-tiles-not-widgets). The `metrics` widget is the documented exception.
+- **Charts/trends on a dashboard → insight tiles**, not new widget types — [architecture.md § Charts](../../.agents/skills/manage-dashboard-widgets/references/architecture.md#charts--use-insight-tiles-not-widgets).
## Frontend / backend parity
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 46cc59fed792..21949f3b46d0 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -5,9 +5,11 @@ import json
import uuid
import builtins
import contextvars
-from collections.abc import AsyncGenerator
+from collections.abc import AsyncGenerator, Callable
+from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import nullcontext
from enum import StrEnum
+from functools import partial
from typing import Any, Optional, TypedDict, cast
from django.conf import settings
@@ -40,7 +42,6 @@ import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from opentelemetry import trace
-from pydantic import ValidationError as PydanticValidationError
from rest_framework import exceptions, serializers, status, viewsets
from rest_framework.fields import empty
from rest_framework.permissions import SAFE_METHODS, BasePermission
@@ -50,7 +51,7 @@ from rest_framework.serializers import BaseSerializer
from rest_framework.utils import html
from rest_framework.utils.serializer_helpers import ReturnDict
-from posthog.schema import DashboardFilter, InsightVizNode
+from posthog.schema import InsightVizNode
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
@@ -88,7 +89,6 @@ from posthog.helpers.trigram_search import (
from posthog.hogql_queries.apply_dashboard_filters import normalize_dashboard_filters_properties
from posthog.hogql_queries.query_runner import team_configs_for_cache_key
from posthog.hogql_queries.refresh_policy import ComputeSurface
-from posthog.hogql_queries.utils.caller_context import map_in_caller_context
from posthog.models.activity_logging.activity_log import Change
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, join_path, split_path
@@ -190,26 +190,21 @@ from products.dashboards.backend.widget_access import (
check_widget_tile_product_access,
get_widget_api_scope_error,
get_widget_product_access_error,
- is_api_key_or_oauth_request,
)
from products.dashboards.backend.widget_availability import get_widget_feature_enabled
from products.dashboards.backend.widget_catalog import get_widget_catalog_entries, parse_widget_type_filter
from products.dashboards.backend.widget_create import create_widget_tile, prepare_widget_tile_create
from products.dashboards.backend.widget_layouts import collect_dashboard_sm_layouts_for_dashboard
-from products.dashboards.backend.widget_query_throttle import (
- get_dashboard_chart_widget_session_throttle_error,
- get_dashboard_widget_query_throttle_error,
-)
+from products.dashboards.backend.widget_query_throttle import get_dashboard_widget_query_throttle_error
from products.dashboards.backend.widget_registry import (
EXPECTED_WIDGET_TYPES,
SESSION_REPLAY_LIST_WIDGET_TYPE,
count_active_widget_filters,
extract_widget_filters,
get_widget_registry_entry,
- get_widget_spec,
validate_widget_config,
)
-from products.dashboards.backend.widgets.errors import WidgetQueryError
+from products.dashboards.backend.widget_specs.configs import CONVERSATIONS_RECENT_TICKETS_WIDGET_TYPE
from products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_template
from products.notifications.backend.facade.api import (
NotificationData,
@@ -377,18 +372,10 @@ class _RunWidgetQueryWorkItem(TypedDict):
query_fn: Any
config: dict[str, Any]
user: User | None
- dashboard_filter_keys: tuple[str, ...]
- dashboard_filters: DashboardFilter | None
-def _widget_dashboard_filters(filters: dict[str, Any], keys: tuple[str, ...]) -> DashboardFilter | None:
- widget_filters = {key: filters[key] for key in keys if filters.get(key)}
- if not widget_filters:
- return None
- try:
- return DashboardFilter.model_validate(widget_filters)
- except PydanticValidationError as error:
- raise exceptions.ValidationError({"filters_override": "Invalid dashboard filters."}) from error
+def _run_in_context(context: contextvars.Context, work: Callable[[], dict[str, Any]]) -> dict[str, Any]:
+ return context.run(work)
def _run_widget_query(
@@ -397,7 +384,6 @@ def _run_widget_query(
*,
dashboard_id: int,
distinct_id: str,
- force_refresh: bool = False,
) -> dict[str, Any]:
tile_id = work_item["tile_id"]
widget_type = work_item["widget_type"]
@@ -418,21 +404,11 @@ def _run_widget_query(
) as slo:
try:
query_fn = work_item["query_fn"]
- dashboard_kwargs: dict[str, Any] = (
- {
- "dashboard_id": dashboard_id,
- "dashboard_filters": work_item["dashboard_filters"],
- "force_refresh": force_refresh,
- }
- if work_item["dashboard_filter_keys"]
- else {}
- )
result = query_fn(
team,
work_item["config"],
user=work_item["user"],
include_total_count=False,
- **dashboard_kwargs,
)
return {
"tile_id": tile_id,
@@ -440,18 +416,6 @@ def _run_widget_query(
"result": result,
"error": None,
}
- except WidgetQueryError as error:
- # The message is safe to show, so it is not logged as an exception. Only failures on our side count
- # against the delivery SLO.
- if error.operational:
- slo.fail()
- return {
- "tile_id": tile_id,
- "widget_type": widget_type,
- "result": None,
- "error": error.user_message,
- "error_is_user_facing": True,
- }
except Exception:
logger.exception("dashboard_run_widgets_failed", tile_id=tile_id, widget_type=widget_type)
slo.fail()
@@ -1174,10 +1138,12 @@ class SharedDashboardWidgetMetadataSerializer(serializers.ModelSerializer):
@extend_schema_field(DashboardWidgetConfigField(required=False))
def get_config(self, widget: DashboardWidget) -> dict[str, Any]:
+ # Rows of a retired widget type can still exist, and nothing says which of their config keys are public.
+ if widget.widget_type not in EXPECTED_WIDGET_TYPES:
+ return {}
config = dict(widget.config)
- spec = get_widget_spec(widget.widget_type)
- for key in spec.public_config_exclude if spec else ():
- config.pop(key, None)
+ if widget.widget_type == CONVERSATIONS_RECENT_TICKETS_WIDGET_TYPE:
+ config.pop("search", None)
return config
@@ -1305,13 +1271,6 @@ class DashboardWidgetRunResultSerializer(serializers.Serializer):
allow_null=True,
help_text="Error message when the widget could not be run.",
)
- error_is_user_facing = serializers.BooleanField(
- required=False,
- help_text=(
- "True when `error` explains the failure to the viewer (for example, no access or an invalid query) and "
- "can be shown as is. Other errors are generic."
- ),
- )
class RunWidgetsResponseSerializer(serializers.Serializer):
@@ -4167,17 +4126,6 @@ class DashboardsViewSet(
required=True,
description="Comma-separated dashboard tile IDs to run widgets for.",
),
- FILTERS_OVERRIDE_PARAM,
- OpenApiParameter(
- name="refresh",
- type=OpenApiTypes.BOOL,
- location=OpenApiParameter.QUERY,
- required=False,
- description=(
- "Recompute widgets that follow dashboard filters (such as metrics) instead of serving their "
- "query cache, as a manual refresh of an insight tile does."
- ),
- ),
],
responses={200: RunWidgetsResponseSerializer},
)
@@ -4245,14 +4193,7 @@ class DashboardsViewSet(
}
continue
- spec = get_widget_spec(widget.widget_type)
- widget_throttle_error = (
- get_dashboard_chart_widget_session_throttle_error(request, self)
- if spec is not None
- and spec.session_throttle == "per_viewer"
- and not is_api_key_or_oauth_request(request)
- else get_dashboard_widget_query_throttle_error(request, self)
- )
+ widget_throttle_error = get_dashboard_widget_query_throttle_error(request, self)
if widget_throttle_error:
results_by_id[tile_id] = {
"tile_id": tile_id,
@@ -4280,46 +4221,36 @@ class DashboardsViewSet(
"query_fn": registry_entry["query_fn"],
"config": widget.config,
"user": cast(User, request.user),
- "dashboard_filter_keys": spec.dashboard_filter_keys if spec else (),
- "dashboard_filters": None,
}
)
- if any(work_item["dashboard_filter_keys"] for work_item in query_work_items):
- dashboard_filters = self._run_widgets_dashboard_filters(request, dashboard)
- for work_item in query_work_items:
- work_item["dashboard_filters"] = _widget_dashboard_filters(
- dashboard_filters, work_item["dashboard_filter_keys"]
- )
-
- force_refresh = str_to_bool(request.query_params.get("refresh", "false"))
-
- # Workers close their Postgres connections on the way out, and keep the request's query tags.
- widget_results = map_in_caller_context(
- lambda work_item: _run_widget_query(
- self.team,
- work_item,
- dashboard_id=dashboard.id,
- distinct_id=distinct_id,
- force_refresh=force_refresh,
- ),
- query_work_items,
- max_workers=RUN_WIDGETS_QUERY_CONCURRENCY,
- thread_name_prefix="run_widgets",
- )
- for work_item, widget_result in zip(query_work_items, widget_results):
- results_by_id[work_item["tile_id"]] = widget_result
+ if query_work_items:
+ max_workers = min(RUN_WIDGETS_QUERY_CONCURRENCY, len(query_work_items))
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ # Each worker gets a copy of the request context, so the query tags (such as the API key
+ # access method that the metrics concurrency limits read) reach the widget query.
+ futures = {
+ executor.submit(
+ _run_in_context,
+ contextvars.copy_context(),
+ partial(
+ _run_widget_query,
+ self.team,
+ work_item,
+ dashboard_id=dashboard.id,
+ distinct_id=distinct_id,
+ ),
+ ): work_item["tile_id"]
+ for work_item in query_work_items
+ }
+ for future in as_completed(futures):
+ tile_id = futures[future]
+ results_by_id[tile_id] = future.result()
results = [results_by_id[tile_id] for tile_id in tile_ids]
return Response({"results": results})
- @staticmethod
- def _run_widgets_dashboard_filters(request: Request, dashboard: Dashboard) -> dict[str, Any]:
- # Same merge as insight tiles: saved dashboard filters, then the viewer's unsaved overrides. Shared and
- # embedded access never honors a client override. Each widget then takes only its own filter keys.
- return filters_override_requested_by_client(request, dashboard)
-
@extend_schema(
parameters=[
OpenApiParameter(
diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.py
index 615940a27d05..f23faf93f377 100644
--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py
+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py
@@ -24,7 +24,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_templates import DashboardTemplate
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
-from products.dashboards.backend.widget_registry import EXPECTED_WIDGET_TYPES, DashboardWidgetType
+from products.dashboards.backend.widget_registry import EXPECTED_WIDGET_TYPES
from products.product_analytics.backend.facade.models import Insight
@@ -1355,25 +1355,14 @@ class TestDashboardWidgets(APIBaseTest):
assert properties["current_count"] == 19
assert properties["crossing_threshold"] is True
- @parameterized.expand(
- [
- ("conversations_recent_tickets", {"limit": 10, "search": "sensitive ticket text"}, "search"),
- (
- "metrics",
- {"query": {"kind": "MetricsQuery", "clauses": [], "language": "sql", "sql": "SELECT 1"}},
- "query",
- ),
- ]
- )
@override_settings(IN_UNIT_TESTING=True)
- def test_shared_dashboard_tile_serializer_omits_widget_payload(
- self, widget_type: DashboardWidgetType, config: dict, private_key: str
- ) -> None:
+ def test_shared_dashboard_tile_serializer_omits_widget_payload(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})
- with patch("products.dashboards.backend.widget_create.widget_flag_enabled", return_value=True):
- _, dashboard_json = self.dashboard_api.create_widget_tile(
- dashboard_id, widget_type=widget_type, config=config
- )
+ _, dashboard_json = self.dashboard_api.create_widget_tile(
+ dashboard_id,
+ widget_type="conversations_recent_tickets",
+ config={"limit": 10, "search": "sensitive ticket text"},
+ )
tile = DashboardTile.objects.get(id=dashboard_json["tiles"][0]["id"])
class ViewShim:
@@ -1388,9 +1377,19 @@ class TestDashboardWidgets(APIBaseTest):
shared_widget = DashboardTileSerializer(tile, context=shared_context).data["widget"]
assert shared_widget is not None
assert set(shared_widget.keys()) == {"id", "widget_type", "name", "description", "config"}
- assert shared_widget["widget_type"] == widget_type
- assert private_key in full_widget["config"]
- assert private_key not in shared_widget["config"]
+ assert shared_widget["widget_type"] == "conversations_recent_tickets"
+ assert shared_widget["config"]["limit"] == 10
+ assert "search" not in shared_widget["config"]
+
+ assert tile.widget_id is not None
+ DashboardWidget.objects.for_team(self.team.id).filter(id=tile.widget_id).update(
+ widget_type="metrics", config={"query": {"kind": "MetricsQuery", "sql": "select secret"}}
+ )
+ tile.refresh_from_db()
+ retired_widget = DashboardTileSerializer(tile, context=shared_context).data["widget"]
+ assert retired_widget is not None
+ assert retired_widget["widget_type"] == "metrics"
+ assert retired_widget["config"] == {}
class TestDashboardWidgetsBatchUpdate(APIBaseTest):
diff --git a/products/dashboards/backend/api/test/test_experiment_widgets.py b/products/dashboards/backend/api/test/test_experiment_widgets.py
index 3cfd1a2da243..96570913207f 100644
--- a/products/dashboards/backend/api/test/test_experiment_widgets.py
+++ b/products/dashboards/backend/api/test/test_experiment_widgets.py
@@ -1,3 +1,4 @@
+from concurrent.futures import Future
from typing import Any
from posthog.test.base import APIBaseTest
@@ -331,10 +332,38 @@ class TestExperimentResultsWidget(APIBaseTest):
assert entry["result"] is None
+class _InlineExecutor:
+ """Runs run_widgets work items on the test thread so widget queries can see
+ data created inside the test transaction (real threads get new DB connections)."""
+
+ def __init__(self, max_workers: int | None = None) -> None:
+ pass
+
+ def __enter__(self) -> "_InlineExecutor":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ pass
+
+ def submit(self, fn: Any, *args: Any, **kwargs: Any) -> "Future[Any]":
+ future: Future[Any] = Future()
+ future.set_result(fn(*args, **kwargs))
+ return future
+
+
class TestExperimentWidgetsViaRunWidgetsEndpoint(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+ self.executor_patcher = patch(
+ "products.dashboards.backend.api.dashboard.ThreadPoolExecutor",
+ _InlineExecutor,
+ )
+ self.executor_patcher.start()
+
+ def tearDown(self) -> None:
+ self.executor_patcher.stop()
+ super().tearDown()
def _run(self, dashboard_id: int, tile_ids: list[int]) -> dict[str, Any]:
response = self.client.get(
diff --git a/products/dashboards/backend/api/test/test_metrics_widget.py b/products/dashboards/backend/api/test/test_metrics_widget.py
deleted file mode 100644
index 31b47d532946..000000000000
--- a/products/dashboards/backend/api/test/test_metrics_widget.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from unittest.mock import MagicMock, patch
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
-
-from products.dashboards.backend.widgets.errors import WidgetQueryError
-from products.dashboards.backend.widgets.metrics import _run_with_capacity_retries
-
-
-class TestMetricsWidgetCapacityRetries(SimpleTestCase):
- @parameterized.expand([("a slot frees up", 2, True), ("the dashboard stays full", 99, False)])
- @patch("products.dashboards.backend.widgets.metrics.time.sleep")
- def test_retries_a_run_that_misses_a_dashboard_query_slot(
- self, _name: str, failures: int, succeeds: bool, _sleep: MagicMock
- ) -> None:
- attempts = {"count": 0}
-
- def run() -> str:
- attempts["count"] += 1
- if attempts["count"] <= failures:
- raise ConcurrencyLimitExceeded("full")
- return "result"
-
- if succeeds:
- self.assertEqual(_run_with_capacity_retries(run), "result")
- else:
- with self.assertRaises(WidgetQueryError):
- _run_with_capacity_retries(run)
diff --git a/products/dashboards/backend/api/test/test_run_widgets.py b/products/dashboards/backend/api/test/test_run_widgets.py
index b752de0d8ff4..3a2a9a4daa63 100644
--- a/products/dashboards/backend/api/test/test_run_widgets.py
+++ b/products/dashboards/backend/api/test/test_run_widgets.py
@@ -9,7 +9,6 @@ from django.test.utils import override_settings
from parameterized import parameterized
from rest_framework import status
-from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.schema import RecordingOrder, RecordingOrderDirection
@@ -46,7 +45,6 @@ from products.dashboards.backend.widget_specs.configs import (
ACTIVITY_EVENTS_LIST_WIDGET_TYPE,
ERROR_TRACKING_LIST_WIDGET_TYPE,
LOGS_LIST_WIDGET_TYPE,
- METRICS_WIDGET_TYPE,
SESSION_REPLAY_LIST_WIDGET_TYPE,
ErrorTrackingListWidgetConfig,
SessionReplayOrderBy,
@@ -57,7 +55,6 @@ from products.dashboards.backend.widgets.activity_events_list import (
run_activity_events_list_widget,
)
from products.dashboards.backend.widgets.error_tracking_list import run_error_tracking_list_widget
-from products.dashboards.backend.widgets.errors import WidgetQueryError
from products.dashboards.backend.widgets.logs_list import run_logs_list_widget
from products.dashboards.backend.widgets.session_replay_list import run_session_replay_list_widget
from products.error_tracking.backend.facade.query_utils import ERROR_TRACKING_LISTING_VOLUME_RESOLUTION
@@ -129,21 +126,6 @@ class TestWidgetRegistry(SimpleTestCase):
with self.assertRaises(Exception):
validate_widget_config(LOGS_LIST_WIDGET_TYPE, config)
- @parameterized.expand(
- [
- ("runtime_response", {"clauses": [], "response": {"results": []}}),
- ("variables", {"clauses": [], "variables": {"service": {"selection": "checkout"}}}),
- ("oversized_sql", {"clauses": [], "language": "sql", "sql": "x" * 10_001}),
- ("too_many_series", {"clauses": [{"name": f"s{i}", "metricName": "cpu"} for i in range(11)]}),
- ("oversized_formula", {"clauses": [], "formula": "a" * 70_000}),
- ("malformed_kind", {"kind": [], "clauses": []}),
- ("malformed_nested_node", {"clauses": [], "x": {"kind": "RetentionQuery", "version": "a"}}),
- ]
- )
- def test_validate_metrics_config_rejects_what_a_stored_widget_must_not_hold(self, _label: str, query: dict) -> None:
- with self.assertRaises(DRFValidationError):
- validate_widget_config(METRICS_WIDGET_TYPE, {"query": {"kind": "MetricsQuery", **query}})
-
def test_validate_logs_list_config_accepts_severity_and_services(self) -> None:
validated = validate_widget_config(
LOGS_LIST_WIDGET_TYPE,
@@ -1523,42 +1505,17 @@ class TestDashboardRunWidgets(APIBaseTest):
self.assertEqual(started_calls[0].kwargs["properties"]["tile_id"], tile_id)
self.assertEqual(completed_calls[0].kwargs["properties"]["outcome"], SloOutcome.SUCCESS)
- @parameterized.expand(
- [
- ("an unexpected exception", Exception("boom"), SloOutcome.FAILURE, "Widget query failed."),
- (
- "an operational widget error",
- WidgetQueryError("The query timed out.", operational=True),
- SloOutcome.FAILURE,
- "The query timed out.",
- ),
- (
- "a viewer-facing widget error",
- WidgetQueryError("You do not have access to metrics."),
- SloOutcome.SUCCESS,
- "You do not have access to metrics.",
- ),
- ]
- )
@patch("products.dashboards.backend.widgets.error_tracking_list.ErrorTrackingQueryRunner")
@patch("posthog.slo.events.posthoganalytics.capture")
- def test_run_widgets_slo_outcome_when_widget_query_raises(
- self,
- _name: str,
- error: Exception,
- expected_outcome: SloOutcome,
- expected_error_prefix: str,
- mock_capture: MagicMock,
- mock_runner_cls: MagicMock,
+ def test_run_widgets_emits_slo_failure_when_widget_query_raises(
+ self, mock_capture: MagicMock, mock_runner_cls: MagicMock
) -> None:
- mock_runner_cls.return_value.calculate.side_effect = error
+ mock_runner_cls.return_value.calculate.side_effect = Exception("boom")
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})
_, dashboard_json = self.dashboard_api.create_widget_tile(dashboard_id, config={"limit": 10})
tile_id = dashboard_json["tiles"][0]["id"]
- body = self._run(dashboard_id, [tile_id])
-
- self.assertTrue(body["results"][0]["error"].startswith(expected_error_prefix))
+ self._run(dashboard_id, [tile_id])
completed_calls = [
call
@@ -1567,5 +1524,5 @@ class TestDashboardRunWidgets(APIBaseTest):
and call.kwargs.get("properties", {}).get("operation") == SloOperation.DASHBOARD_WIDGET_DELIVERY
]
self.assertEqual(len(completed_calls), 1)
- self.assertEqual(completed_calls[0].kwargs["properties"]["outcome"], expected_outcome)
+ self.assertEqual(completed_calls[0].kwargs["properties"]["outcome"], SloOutcome.FAILURE)
self.assertEqual(completed_calls[0].kwargs["properties"]["widget_type"], "error_tracking_list")
diff --git a/products/dashboards/backend/constants.py b/products/dashboards/backend/constants.py
index 9b1de97ef447..3b7727b4a794 100644
--- a/products/dashboards/backend/constants.py
+++ b/products/dashboards/backend/constants.py
@@ -36,11 +36,6 @@ METRICS_TABLE_RETRY_BUCKETS = 6
# Metrics queries span at most 31 days, so the longer widget presets are not allowed.
METRICS_TABLE_UNSUPPORTED_DATE_FROM_VALUES = frozenset({"-90d"})
-# Metrics widgets store a whole query in their config; these caps keep a stored config small.
-METRICS_WIDGET_MAX_CLAUSES = 10
-METRICS_WIDGET_MAX_QUERY_TEXT_LENGTH = 10_000
-METRICS_WIDGET_MAX_QUERY_JSON_LENGTH = 64_000
-
# Cap widgets per batch create / run-widgets request.
MAX_WIDGETS_BATCH_SIZE = 10
diff --git a/products/dashboards/backend/widget_access.py b/products/dashboards/backend/widget_access.py
index fbefa390d882..cd800ecd87ed 100644
--- a/products/dashboards/backend/widget_access.py
+++ b/products/dashboards/backend/widget_access.py
@@ -26,10 +26,6 @@ def _get_request_api_key_scopes(request: Request) -> list[str] | None:
return None
-def is_api_key_or_oauth_request(request: Request) -> bool:
- return _get_request_api_key_scopes(request) is not None
-
-
def get_widget_api_scope_error(
registry_entry: WidgetRegistryEntry,
request: Request,
diff --git a/products/dashboards/backend/widget_query_throttle.py b/products/dashboards/backend/widget_query_throttle.py
index 27fe6415c3c4..6c23e7557d50 100644
--- a/products/dashboards/backend/widget_query_throttle.py
+++ b/products/dashboards/backend/widget_query_throttle.py
@@ -27,47 +27,8 @@ class DashboardWidgetQuerySustainedRateThrottle(PersonalApiKeyRateThrottle):
return self._allow_request_internal(request, view, personal_api_key_only=False)
-class _PerViewerWidgetQueryThrottle(PersonalApiKeyRateThrottle):
- """Keyed per signed-in viewer, so one member's loads or refresh loop can't use up the team's budget."""
-
- def allow_request(self, request, view) -> bool:
- return self._allow_request_internal(request, view, personal_api_key_only=False)
-
- def get_cache_key(self, request, view):
- if request.user.is_authenticated:
- return self.cache_format % {"scope": self.scope, "ident": request.user.pk}
- return super().get_cache_key(request, view)
-
-
-class DashboardChartWidgetQueryBurstRateThrottle(_PerViewerWidgetQueryThrottle):
- """Per-viewer burst cap on chart widget runs from a browser session (a 20-tile dashboard loads 6 times)."""
-
- scope = "dashboard_chart_widget_query_burst"
- rate = "120/minute"
-
-
-class DashboardChartWidgetQuerySustainedRateThrottle(_PerViewerWidgetQueryThrottle):
- """Per-viewer sustained cap on chart widget runs from a browser session."""
-
- scope = "dashboard_chart_widget_query_sustained"
- rate = "1200/hour"
-
-
def get_dashboard_widget_query_throttle_error(request, view) -> str | None:
"""Return a client-facing error when dashboard widget query throttles would block this request."""
- return _throttle_error(
- request, view, (DashboardWidgetQueryBurstRateThrottle, DashboardWidgetQuerySustainedRateThrottle)
- )
-
-
-def get_dashboard_chart_widget_session_throttle_error(request, view) -> str | None:
- """Return a client-facing error when the per-viewer chart widget throttles would block this session request."""
- return _throttle_error(
- request, view, (DashboardChartWidgetQueryBurstRateThrottle, DashboardChartWidgetQuerySustainedRateThrottle)
- )
-
-
-def _throttle_error(request, view, throttle_classes: tuple[type[PersonalApiKeyRateThrottle], ...]) -> str | None:
if not is_rate_limit_enabled(round(time.time() / 60)):
return None
@@ -75,7 +36,7 @@ def _throttle_error(request, view, throttle_classes: tuple[type[PersonalApiKeyRa
if team_id is not None and team_is_allowed_to_bypass_throttle(team_id):
return None
- for throttle_cls in throttle_classes:
+ for throttle_cls in (DashboardWidgetQueryBurstRateThrottle, DashboardWidgetQuerySustainedRateThrottle):
throttle = throttle_cls()
if throttle.allow_request(request, view):
continue
diff --git a/products/dashboards/backend/widget_registry.py b/products/dashboards/backend/widget_registry.py
index ec190c1ba947..a6ded6ae9958 100644
--- a/products/dashboards/backend/widget_registry.py
+++ b/products/dashboards/backend/widget_registry.py
@@ -24,7 +24,6 @@ from products.dashboards.backend.widget_specs.registry import (
count_active_widget_filters,
extract_widget_filters,
get_widget_registry_entry,
- get_widget_spec,
validate_widget_config,
)
@@ -51,6 +50,5 @@ __all__ = [
"count_active_widget_filters",
"extract_widget_filters",
"get_widget_registry_entry",
- "get_widget_spec",
"validate_widget_config",
]
diff --git a/products/dashboards/backend/widget_specs/configs.py b/products/dashboards/backend/widget_specs/configs.py
index 0039cff431a3..2c356b80b99f 100644
--- a/products/dashboards/backend/widget_specs/configs.py
+++ b/products/dashboards/backend/widget_specs/configs.py
@@ -1,14 +1,11 @@
from __future__ import annotations
-from typing import Annotated, Any, Literal, Self
+from typing import Annotated, Literal, Self
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, field_validator, model_validator
-from pydantic.json_schema import SkipJsonSchema
-from posthog.schema import ErrorTrackingOrderBy, MetricsQuery, MetricsQueryClause, PropertyOperator
-
-from posthog.schema_migrations.upgrade import upgrade
+from posthog.schema import ErrorTrackingOrderBy, PropertyOperator
from products.conversations.backend.models.constants import Channel, Priority, Status
from products.dashboards.backend.constants import (
@@ -24,9 +21,6 @@ from products.dashboards.backend.constants import (
METRICS_TABLE_MAX_COLUMNS,
METRICS_TABLE_MAX_FILTERS,
METRICS_TABLE_UNSUPPORTED_DATE_FROM_VALUES,
- METRICS_WIDGET_MAX_CLAUSES,
- METRICS_WIDGET_MAX_QUERY_JSON_LENGTH,
- METRICS_WIDGET_MAX_QUERY_TEXT_LENGTH,
)
from products.dashboards.backend.widget_specs.common import (
ActivityWidgetLimit,
@@ -50,7 +44,6 @@ CONVERSATIONS_RECENT_TICKETS_WIDGET_TYPE = "conversations_recent_tickets"
NOTEBOOK_WIDGET_TYPE = "notebook_widget"
CANVAS_APP_WIDGET_TYPE = "canvas_app"
METRICS_TABLE_WIDGET_TYPE = "metrics_table"
-METRICS_WIDGET_TYPE = "metrics"
class CanvasAppWidgetConfig(BaseModel):
@@ -459,67 +452,3 @@ class MetricsTableWidgetConfig(WidgetDateRangeConfigBase):
if self.dateRange is not None and self.dateRange.date_from in METRICS_TABLE_UNSUPPORTED_DATE_FROM_VALUES:
raise ValueError("Metrics queries cover at most 30 days. Pick a shorter date range.")
return self
-
-
-class MetricsWidgetQuery(MetricsQuery):
- """A `MetricsQuery` as a metrics widget stores it.
-
- Response, modifier and tag fields are runtime state, so a stored config can't carry them.
- """
-
- clauses: list[MetricsQueryClause] = Field(
- default_factory=list,
- max_length=METRICS_WIDGET_MAX_CLAUSES,
- description="Builder series. Empty when `language` is `promql` or `sql`, or until a metric is picked.",
- )
- promql: str | None = Field(
- default=None,
- max_length=METRICS_WIDGET_MAX_QUERY_TEXT_LENGTH,
- description="PromQL expression, run as a range query. Used when `language` is `promql`.",
- )
- sql: str | None = Field(
- default=None,
- max_length=METRICS_WIDGET_MAX_QUERY_TEXT_LENGTH,
- description=(
- "HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` "
- "and a `value` column; every other column is a series label."
- ),
- )
- response: SkipJsonSchema[None] = None
- modifiers: SkipJsonSchema[None] = None
- tags: SkipJsonSchema[None] = None
- # Variable definitions hold their own SQL or PromQL, and widgets don't take dashboard variables yet.
- variables: SkipJsonSchema[None] = None
-
- @model_validator(mode="after")
- def cap_stored_size(self) -> Self:
- # Every dashboard read returns the config, so filters, formulas and display settings share one size cap.
- if len(self.model_dump_json(exclude_none=True)) > METRICS_WIDGET_MAX_QUERY_JSON_LENGTH:
- raise ValueError(f"The query is larger than {METRICS_WIDGET_MAX_QUERY_JSON_LENGTH} characters.")
- return self
-
-
-class MetricsWidgetConfig(BaseModel):
- model_config = ConfigDict(extra="forbid")
-
- query: MetricsWidgetQuery = Field(
- default_factory=MetricsWidgetQuery,
- description=(
- "Metrics query the tile runs and how it draws it (`display.type`: line, area, bar, stat, gauge, "
- "bargauge, table or heatmap). `dateRange` is the default window; the dashboard date filter overrides "
- "it. A config update replaces the whole query."
- ),
- )
-
- @field_validator("query", mode="before")
- @classmethod
- def upgrade_query(cls, value: Any) -> Any:
- # Saved insight queries migrate through the same upgrade on read, so stored widgets survive schema changes.
- # The migration walker keys on `kind`, so anything but the metrics kind goes straight to validation.
- if not (isinstance(value, dict) and value.get("kind") == "MetricsQuery"):
- return value
- try:
- return upgrade(value)
- except (TypeError, KeyError, AttributeError, ValueError) as error:
- # A malformed nested node must fail validation, not reach the client as a server error.
- raise ValueError("The query has a node that can't be read.") from error
diff --git a/products/dashboards/backend/widget_specs/openapi.py b/products/dashboards/backend/widget_specs/openapi.py
index d57b9f8ce5b2..1a07bb29e24e 100644
--- a/products/dashboards/backend/widget_specs/openapi.py
+++ b/products/dashboards/backend/widget_specs/openapi.py
@@ -88,7 +88,6 @@ class DashboardWidgetType(models.TextChoices):
EXPERIMENT_RESULTS = "experiment_results"
EXPERIMENTS_LIST = "experiments_list"
LOGS_LIST = "logs_list"
- METRICS = "metrics"
METRICS_TABLE = "metrics_table"
NOTEBOOK_WIDGET = "notebook_widget"
SESSION_REPLAY_LIST = "session_replay_list"
diff --git a/products/dashboards/backend/widget_specs/registry.py b/products/dashboards/backend/widget_specs/registry.py
index 78a7578bc480..65d9bdc86be5 100644
--- a/products/dashboards/backend/widget_specs/registry.py
+++ b/products/dashboards/backend/widget_specs/registry.py
@@ -7,8 +7,6 @@ from typing import Any, Literal, NotRequired, TypedDict
from pydantic import BaseModel, ValidationError
from rest_framework.exceptions import ValidationError as DRFValidationError
-from posthog.schema import DashboardFilter
-
from products.dashboards.backend.constants import DASHBOARD_GRID_COLUMN_COUNT
from products.dashboards.backend.widget_specs.configs import (
ACTIVITY_EVENTS_LIST_WIDGET_TYPE,
@@ -19,7 +17,6 @@ from products.dashboards.backend.widget_specs.configs import (
EXPERIMENTS_LIST_WIDGET_TYPE,
LOGS_LIST_WIDGET_TYPE,
METRICS_TABLE_WIDGET_TYPE,
- METRICS_WIDGET_TYPE,
NOTEBOOK_WIDGET_TYPE,
SESSION_REPLAY_LIST_WIDGET_TYPE,
SURVEY_RESULTS_WIDGET_TYPE,
@@ -31,7 +28,6 @@ from products.dashboards.backend.widget_specs.configs import (
ExperimentsListWidgetConfig,
LogsListWidgetConfig,
MetricsTableWidgetConfig,
- MetricsWidgetConfig,
NotebookWidgetConfig,
SessionReplayListWidgetConfig,
SurveyResultsWidgetConfig,
@@ -50,7 +46,6 @@ DashboardWidgetType = Literal[
"conversations_recent_tickets",
"canvas_app",
"metrics_table",
- "metrics",
]
__all__ = [
@@ -96,24 +91,8 @@ class WidgetSpec:
# Grid size of a new tile, in columns (of 12) and rows. The frontend catalog `defaultLayout` must match.
default_width: int = 6
default_height: int = 5
- # The DashboardFilter keys this widget follows, like an insight tile follows the dashboard filters. When set,
- # run_widgets passes `dashboard_id`, `dashboard_filters` (only these keys, saved filters merged with the viewer's
- # override) and `force_refresh` (a manual refresh) to `query_fn`. The frontend reads the keys from the manifest
- # and refetches the tile only when one of them changes.
- dashboard_filter_keys: tuple[str, ...] = ()
- # "shared": every run counts against the shared per-team widget query throttle. "per_viewer": a browser
- # session counts against a per-viewer chart throttle instead, so dashboards full of chart tiles don't use up
- # the team's quota for every other widget. API key and OAuth requests always use the shared throttle.
- session_throttle: Literal["shared", "per_viewer"] = "shared"
- # Config keys left out of the config that shared and public dashboards receive.
- public_config_exclude: tuple[str, ...] = ()
def __post_init__(self) -> None:
- unknown_filter_keys = set(self.dashboard_filter_keys) - set(DashboardFilter.model_fields)
- if unknown_filter_keys:
- raise ValueError(
- f"{self.widget_type}: dashboard_filter_keys not on DashboardFilter: {sorted(unknown_filter_keys)}"
- )
if self.is_live:
forbidden = [field for field in _LIVE_FORBIDDEN_CONFIG_FIELDS if field in self.config_model.model_fields]
if forbidden:
@@ -155,7 +134,6 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:
from products.dashboards.backend.widgets.experiment_results import run_experiment_results_widget # noqa: PLC0415
from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget # noqa: PLC0415
from products.dashboards.backend.widgets.logs_list import run_logs_list_widget # noqa: PLC0415
- from products.dashboards.backend.widgets.metrics import run_metrics_widget # noqa: PLC0415
from products.dashboards.backend.widgets.metrics_table import run_metrics_table_widget # noqa: PLC0415
from products.dashboards.backend.widgets.notebook_widget import run_notebook_widget # noqa: PLC0415
from products.dashboards.backend.widgets.session_replay_list import run_session_replay_list_widget # noqa: PLC0415
@@ -300,7 +278,6 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:
availability_requirements=("conversations_enabled",),
form_fields=("limit",),
filter_fields=("status", "priorities", "channel", "assignees", "search"),
- public_config_exclude=("search",),
),
CANVAS_APP_WIDGET_TYPE: WidgetSpec(
widget_type=CANVAS_APP_WIDGET_TYPE,
@@ -337,29 +314,6 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:
default_height=6,
creation_flag=METRICS_FEATURE_FLAG,
),
- METRICS_WIDGET_TYPE: WidgetSpec(
- widget_type=METRICS_WIDGET_TYPE,
- config_model=MetricsWidgetConfig,
- query_fn=run_metrics_widget,
- required_scopes=("metrics:read",),
- group_id="metrics",
- group_label="Metrics",
- label="Metric",
- description=(
- "A service metric as a time series, single stat, gauge, bar gauge, table or heatmap. "
- "Write the query with the builder, PromQL or SQL."
- ),
- required_product_access="metrics",
- product_access_denied_message="You do not have access to metrics.",
- availability_requirements=(),
- form_fields=("query",),
- filter_fields=(),
- creation_flag=METRICS_FEATURE_FLAG,
- dashboard_filter_keys=("date_from", "date_to"),
- session_throttle="per_viewer",
- # Shared dashboards show a placeholder for widget tiles, so the query text has no reason to leave.
- public_config_exclude=("query",),
- ),
}
diff --git a/products/dashboards/backend/widgets/errors.py b/products/dashboards/backend/widgets/errors.py
deleted file mode 100644
index 8e776116cc30..000000000000
--- a/products/dashboards/backend/widgets/errors.py
+++ /dev/null
@@ -1,12 +0,0 @@
-class WidgetQueryError(Exception):
- """A widget query failure whose message is safe to show on the tile.
-
- `run_widgets` returns the message as the tile error and does not log it as an exception. Set `operational`
- for failures on our side (a timeout, a memory limit, no free query slot): the delivery SLO counts those
- as failures, while a viewer without access or an invalid query is not a delivery failure.
- """
-
- def __init__(self, user_message: str, *, operational: bool = False) -> None:
- super().__init__(user_message)
- self.user_message = user_message
- self.operational = operational
diff --git a/products/dashboards/backend/widgets/metrics.py b/products/dashboards/backend/widgets/metrics.py
deleted file mode 100644
index 77925c98fb33..000000000000
--- a/products/dashboards/backend/widgets/metrics.py
+++ /dev/null
@@ -1,115 +0,0 @@
-from __future__ import annotations
-
-import time
-from collections.abc import Callable
-from typing import Any
-
-from rest_framework.exceptions import APIException
-
-from posthog.schema import DashboardFilter, MetricsDisplayType, MetricsQuery, MetricsQueryLanguage
-
-from posthog.hogql.errors import ExposedHogQLError
-
-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
-from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.errors import ExposedCHQueryError
-from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.models.team import Team
-from posthog.models.user import User
-
-from products.access_control.backend.facade.user_access_control import UserAccessControlError
-from products.dashboards.backend.widget_specs.configs import METRICS_WIDGET_TYPE
-from products.dashboards.backend.widget_specs.registry import validate_widget_config
-from products.dashboards.backend.widgets.errors import WidgetQueryError
-from products.metrics.backend.facade.api import metrics_histogram_query_for
-from products.metrics.backend.facade.contracts import MetricsHeatmapIneligibleError
-from products.metrics.backend.facade.queries import MetricsHistogramQueryRunner, MetricsQueryRunner
-
-# Debug and runtime fields the tile never reads.
-_DROPPED_RESPONSE_KEYS = ("hogql", "modifiers", "query_status", "timings")
-
-# A dashboard can hold more metric tiles than the per-org dashboard query limiter admits at once, and the
-# limiter does not wait. A tile that misses a slot tries again after these delays before it gives up.
-_CAPACITY_RETRY_DELAYS_SECONDS = (0.25, 0.5, 1.0, 2.0)
-
-
-def _needs_configuration(query: MetricsQuery) -> bool:
- if query.language == MetricsQueryLanguage.PROMQL:
- return not (query.promql or "").strip()
- if query.language == MetricsQueryLanguage.SQL:
- return not (query.sql or "").strip()
- return not query.clauses or not all(clause.metricName.strip() for clause in query.clauses)
-
-
-def _build_runner(team: Team, query: MetricsQuery) -> MetricsQueryRunner | MetricsHistogramQueryRunner:
- # The heatmap reads a different response shape, so it gets its own query node and cache entry rather
- # than a display branch inside the time-series runner (whose cache key ignores `display`).
- if query.display and query.display.type == MetricsDisplayType.HEATMAP:
- try:
- return MetricsHistogramQueryRunner(query=metrics_histogram_query_for(query), team=team)
- except MetricsHeatmapIneligibleError as error:
- raise WidgetQueryError(str(error)) from error
- return MetricsQueryRunner(query=query, team=team)
-
-
-def _run_with_capacity_retries(run: Callable[[], Any]) -> Any:
- for delay in _CAPACITY_RETRY_DELAYS_SECONDS:
- try:
- return run()
- except ConcurrencyLimitExceeded:
- time.sleep(delay)
- try:
- return run()
- except ConcurrencyLimitExceeded as error:
- raise WidgetQueryError(
- "Too many queries are running on this dashboard. Refresh the tile in a moment.", operational=True
- ) from error
-
-
-def run_metrics_widget(
- team: Team,
- config: dict[str, Any],
- user: User | None = None,
- *,
- include_total_count: bool = True,
- dashboard_id: int | None = None,
- dashboard_filters: DashboardFilter | None = None,
- force_refresh: bool = False,
-) -> dict[str, Any]:
- typed_config = validate_widget_config(METRICS_WIDGET_TYPE, config)
- query = MetricsQuery.model_validate(typed_config["query"])
- if _needs_configuration(query):
- return {"needsConfiguration": True}
- # The metrics runner enforces RBAC and the alpha flags per viewer. A run without a viewer would skip
- # those checks, so a widget never runs one.
- if user is None:
- raise WidgetQueryError("Sign in to PostHog to see this metric.")
-
- runner = _build_runner(team, query)
- if dashboard_filters is not None:
- runner.apply_dashboard_filters(dashboard_filters)
-
- # A refresh the viewer asks for skips the cache, as the refresh of an insight tile does.
- execution_mode = (
- ExecutionMode.CALCULATE_BLOCKING_ALWAYS
- if force_refresh
- else ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
- )
- try:
- with tags_context(product=Product.METRICS, feature=Feature.QUERY, team_id=team.pk):
- response = _run_with_capacity_retries(
- lambda: runner.run(execution_mode=execution_mode, user=user, dashboard_id=dashboard_id)
- )
- except UserAccessControlError as error:
- raise WidgetQueryError("You do not have access to metrics.") from error
- except (ExposedHogQLError, ExposedCHQueryError) as error:
- raise WidgetQueryError(str(error)) from error
- except APIException as error:
- # The runner's typed refusals (a timeout, a memory or size limit) explain themselves to the viewer.
- raise WidgetQueryError(str(error.detail), operational=True) from error
-
- # A gap point's `value` is required and null, so None stays in the payload.
- result = response.model_dump(mode="json")
- for key in _DROPPED_RESPONSE_KEYS:
- result.pop(key, None)
- return result
diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
index 7b7392c5d5aa..1ae3373f53da 100644
--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
@@ -82,9 +82,6 @@ type DashboardWidgetItemProps = {
onRemove?: () => void
onMoveToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
onCopyToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
- /** Opens the widget settings when the tile first renders, as right after the tile is added. */
- openEditorOnMount?: boolean
- onEditorClose?: () => void
/** Injected by react-grid-layout / react-resizable — must render inside the card root. */
children?: React.ReactNode
} & Pick<DashboardWidgetPlacementMenusProps, 'tileGroupMoveOptions' | 'onMoveToTileGroup'> &
@@ -92,13 +89,7 @@ type DashboardWidgetItemProps = {
type DashboardWidgetItemContentProps = Omit<
DashboardWidgetItemProps,
- | 'children'
- | 'className'
- | 'style'
- | 'showResizeHandles'
- | 'canEnterEditModeFromEdge'
- | 'onEnterEditModeFromEdge'
- | 'openEditorOnMount'
+ 'children' | 'className' | 'style' | 'showResizeHandles' | 'canEnterEditModeFromEdge' | 'onEnterEditModeFromEdge'
> & {
widget: NonNullable<DashboardTile['widget']>
definition: DashboardWidgetDefinition | undefined
@@ -178,11 +169,9 @@ function DashboardWidgetItemContent({
editOpen,
setEditOpen,
showBody,
- onEditorClose,
}: DashboardWidgetItemContentProps): JSX.Element {
const widgetTypeLabel = getDashboardWidgetGroupLabel(headerCatalogEntry.groupId)
- const defaultTitle =
- definition?.getDefaultTitle?.(widget.config) ?? headerCatalogEntry.headerTitle ?? widgetTypeLabel
+ const defaultTitle = headerCatalogEntry.headerTitle ?? widgetTypeLabel
const title = widget.name?.trim() || ''
const description = widget.description?.trim() || ''
const showDescription = tile.show_description !== false
@@ -197,7 +186,6 @@ function DashboardWidgetItemContent({
: undefined
const canUpdateWidgetTileConfig = !!onUpdateWidgetTile && !!canEditDashboard
- const EditModal = definition?.EditModal
const componentProps: DashboardWidgetComponentProps = {
tileId: tile.id,
@@ -220,11 +208,11 @@ function DashboardWidgetItemContent({
}
: undefined,
onConfigPublished: canUpdateWidgetTileConfig ? onConfigPublished : undefined,
- onEdit: showEditingControls && EditModal ? () => setEditOpen(true) : undefined,
}
const TileFilters = definition?.TileFilters
const { isAvailable: showTileFilters } = useWidgetAvailability(headerCatalogEntry.availability)
+ const EditModal = definition?.EditModal
const MenuItems = definition?.MenuItems
const hasDashboardSectionActions =
@@ -386,10 +374,7 @@ function DashboardWidgetItemContent({
<Suspense fallback={null}>
<EditModal
isOpen={editOpen}
- onClose={() => {
- setEditOpen(false)
- onEditorClose?.()
- }}
+ onClose={() => setEditOpen(false)}
config={widget.config}
name={title}
defaultTitle={defaultTitle}
@@ -434,8 +419,6 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid
onCopyToDashboard,
tileGroupMoveOptions,
onMoveToTileGroup,
- openEditorOnMount,
- onEditorClose,
children,
className,
style,
@@ -444,7 +427,7 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid
ref
): JSX.Element | null {
const widget = tile.widget
- const [editOpen, setEditOpen] = useState(!!openEditorOnMount && !!showEditingControls)
+ const [editOpen, setEditOpen] = useState(false)
const exportPlacement = placement === DashboardPlacement.Export
const { ref: visibilityRef, inView } = useInView({
rootMargin: '500px',
@@ -533,7 +516,6 @@ export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWid
editOpen={editOpen}
setEditOpen={setEditOpen}
showBody={showBody}
- onEditorClose={onEditorClose}
/>
</WidgetCard>
)
diff --git a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
index f80a00bd6b83..0f8349a9ddc0 100644
--- a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
+++ b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
@@ -4,7 +4,6 @@ import { activityEventsSampleEvents } from '../../widgets/activity/activityEvent
import type { ConversationsWidgetTicket } from '../../widgets/conversations/conversationsWidgetUtils'
import { logsWidgetSampleLogLines } from '../../widgets/logs/logsWidgetSampleData'
import { metricsTableWidgetSampleResult } from '../../widgets/metrics/metricsTableWidgetSampleData'
-import { METRICS_WIDGET_SAMPLE_RESPONSE, metricsWidgetSampleQuery } from '../../widgets/metrics/metricsWidgetSampleData'
export type WidgetOverviewDemoState = {
title?: string
@@ -560,15 +559,6 @@ export function getWidgetOverviewDemoState(catalogKey: DashboardWidgetCatalogKey
totalCount: 12,
},
}
- case 'metrics':
- return {
- title: 'http_server_requests',
- description: catalogEntry.description,
- showDescription: true,
- config: { query: metricsWidgetSampleQuery('time_series') },
- loading: false,
- result: METRICS_WIDGET_SAMPLE_RESPONSE,
- }
default: {
const exhaustiveCheck: never = catalogKey
return exhaustiveCheck
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 80c4368240b9..84d3f9f2f236 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -660,7 +660,6 @@ export const DashboardTileBadgeEnumApi = {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -676,7 +675,6 @@ export const DashboardWidgetTypeEnumApi = {
ExperimentResults: 'experiment_results',
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
- Metrics: 'metrics',
MetricsTable: 'metrics_table',
NotebookWidget: 'notebook_widget',
SessionReplayList: 'session_replay_list',
@@ -1243,270 +1241,6 @@ export interface MetricsTableWidgetConfigApi {
limit?: number
}
-export type MetricsAggregationApi = (typeof MetricsAggregationApi)[keyof typeof MetricsAggregationApi]
-
-export const MetricsAggregationApi = {
- Sum: 'sum',
- Avg: 'avg',
- Count: 'count',
- Min: 'min',
- Max: 'max',
- Quantile: 'quantile',
- Rate: 'rate',
- Increase: 'increase',
- HistogramQuantile: 'histogram_quantile',
-} as const
-
-export type MetricsFilterOpApi = (typeof MetricsFilterOpApi)[keyof typeof MetricsFilterOpApi]
-
-export const MetricsFilterOpApi = {
- Eq: 'eq',
- Neq: 'neq',
- Regex: 'regex',
- NotRegex: 'not_regex',
-} as const
-
-export type MetricsAttributeScopeApi = (typeof MetricsAttributeScopeApi)[keyof typeof MetricsAttributeScopeApi]
-
-export const MetricsAttributeScopeApi = {
- Resource: 'resource',
- Attribute: 'attribute',
- Auto: 'auto',
-} as const
-
-export interface MetricsQueryFilterApi {
- key: string
- op: MetricsFilterOpApi
- scope?: MetricsAttributeScopeApi | null
- value: string
-}
-
-export interface MetricsQueryGroupByApi {
- key: string
- scope?: MetricsAttributeScopeApi | null
-}
-
-export type MetricsOtelTypeApi = (typeof MetricsOtelTypeApi)[keyof typeof MetricsOtelTypeApi]
-
-export const MetricsOtelTypeApi = {
- Gauge: 'gauge',
- Sum: 'sum',
- Histogram: 'histogram',
- ExponentialHistogram: 'exponential_histogram',
- Summary: 'summary',
-} as const
-
-export type MetricsRangeFunctionApi = (typeof MetricsRangeFunctionApi)[keyof typeof MetricsRangeFunctionApi]
-
-export const MetricsRangeFunctionApi = {
- Rate: 'rate',
- Increase: 'increase',
-} as const
-
-export interface MetricsQueryClauseApi {
- /** Omit to get one line per series (at most 100), without combining them */
- aggregation?: MetricsAggregationApi | null
- filters?: MetricsQueryFilterApi[] | null
- groupBy?: MetricsQueryGroupByApi[] | null
- metricName: string
- /** Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series. */
- metricType?: MetricsOtelTypeApi | null
- /** Alias a formula refers to (e.g. "a"); must be unique within the query */
- name: string
- /** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
- quantile?: number | null
- /** Applied to each series before `aggregation`, like `rate()` in PromQL */
- rangeFunction?: MetricsRangeFunctionApi | null
-}
-
-export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]
-
-export const DaysOfWeekEnumApi = {
- Number1: 1,
- Number2: 2,
- Number3: 3,
- Number4: 4,
- Number5: 5,
- Number6: 6,
- Number7: 7,
-} as const
-
-export interface DateRangeApi {
- /** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
- * -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */
- date_from?: string | null
- /** End of the date range. Same format as date_from. Omit or null for "now". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set. */
- date_to?: string | null
- /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */
- daysOfWeek?: DaysOfWeekEnumApi[] | null
- /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */
- excludeIncompletePeriods?: boolean | null
- /** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */
- explicitDate?: boolean | null
-}
-
-export type CalculationApi = (typeof CalculationApi)[keyof typeof CalculationApi]
-
-export const CalculationApi = {
- Fixed: 'fixed',
- Mean: 'mean',
- Median: 'median',
- Min: 'min',
- Max: 'max',
-} as const
-
-export type PositionApi = (typeof PositionApi)[keyof typeof PositionApi]
-
-export const PositionApi = {
- Start: 'start',
- End: 'end',
-} as const
-
-export type ScopeApi = (typeof ScopeApi)[keyof typeof ScopeApi]
-
-export const ScopeApi = {
- All: 'all',
- Series: 'series',
-} as const
-
-export interface GoalLineApi {
- borderColor?: string | null
- /** Recalculate from returned chart marks. An absent calculation uses the fixed value. */
- calculation?: CalculationApi | null
- displayIfCrossed?: boolean | null
- displayLabel?: boolean | null
- label: string
- position?: PositionApi | null
- /** SQL chart calculations use the primary axis, across all series or separately per series. */
- scope?: ScopeApi | null
- value: number
-}
-
-export type MetricsReducerApi = (typeof MetricsReducerApi)[keyof typeof MetricsReducerApi]
-
-export const MetricsReducerApi = {
- Last: 'last',
- Mean: 'mean',
- Min: 'min',
- Max: 'max',
- Sum: 'sum',
- Delta: 'delta',
-} as const
-
-export type MetricsNullModeApi = (typeof MetricsNullModeApi)[keyof typeof MetricsNullModeApi]
-
-export const MetricsNullModeApi = {
- Gap: 'gap',
- Zero: 'zero',
- Connect: 'connect',
-} as const
-
-export type MetricsStatSummaryApi = (typeof MetricsStatSummaryApi)[keyof typeof MetricsStatSummaryApi]
-
-export const MetricsStatSummaryApi = {
- Latest: 'latest',
- Average: 'average',
- Total: 'total',
-} as const
-
-export interface MetricsThresholdApi {
- /** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
- color: string
- /** Lower bound of this band. The lowest step is the base color below every other step. */
- value: number
-}
-
-export type MetricsDisplayTypeApi = (typeof MetricsDisplayTypeApi)[keyof typeof MetricsDisplayTypeApi]
-
-export const MetricsDisplayTypeApi = {
- Line: 'line',
- Area: 'area',
- Bar: 'bar',
- Stat: 'stat',
- Gauge: 'gauge',
- Bargauge: 'bargauge',
- Table: 'table',
- Heatmap: 'heatmap',
-} as const
-
-export type MetricsAxisScaleApi = (typeof MetricsAxisScaleApi)[keyof typeof MetricsAxisScaleApi]
-
-export const MetricsAxisScaleApi = {
- Linear: 'linear',
- Log: 'log',
-} as const
-
-export interface MetricsYAxisSettingsApi {
- /** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot. */
- max?: number | null
- /** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
- min?: number | null
- scale?: MetricsAxisScaleApi | null
- /** When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero. */
- startAtZero?: boolean | null
-}
-
-export interface MetricsDisplaySettingsApi {
- goalLines?: GoalLineApi[] | null
- /** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
- legendCalcs?: MetricsReducerApi[] | null
- /** How a null bucket renders on a time-series chart. */
- nullMode?: MetricsNullModeApi | null
- /** How scalar panels and legend calcs collapse a series to one number. */
- reduce?: MetricsReducerApi | null
- /** `stat` display only: which summary the headline value shows. */
- statSummary?: MetricsStatSummaryApi | null
- /** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
- thresholds?: MetricsThresholdApi[] | null
- type?: MetricsDisplayTypeApi | null
- /** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
- unit?: string | null
- yAxis?: MetricsYAxisSettingsApi | null
-}
-
-export type MetricsQueryLanguageApi = (typeof MetricsQueryLanguageApi)[keyof typeof MetricsQueryLanguageApi]
-
-export const MetricsQueryLanguageApi = {
- Builder: 'builder',
- Promql: 'promql',
- Sql: 'sql',
-} as const
-
-/**
- * A `MetricsQuery` as a metrics widget stores it.
- *
- * Response, modifier and tag fields are runtime state, so a stored config can't carry them.
- */
-export interface MetricsWidgetQueryApi {
- /**
- * Builder series. Empty when `language` is `promql` or `sql`, or until a metric is picked.
- * @maxItems 10
- */
- clauses?: MetricsQueryClauseApi[]
- /** Defaults to the last 24 hours when omitted; dashboard date filters override it */
- dateRange?: DateRangeApi | null
- /** Chart presentation. A node without it renders as a line chart. */
- display?: MetricsDisplaySettingsApi | null
- /** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */
- formula?: string | null
- /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable. */
- interval?: string | null
- kind?: 'MetricsQuery'
- /** How the query is written; the builder when unset. */
- language?: MetricsQueryLanguageApi | null
- /** PromQL expression, run as a range query. Used when `language` is `promql`. */
- promql?: string | null
- /** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label. */
- sql?: string | null
- /** version of the node, used for schema migrations */
- version?: number | null
-}
-
-export interface MetricsWidgetConfigApi {
- /** Metrics query the tile runs and how it draws it (`display.type`: line, area, bar, stat, gauge, bargauge, table or heatmap). `dateRange` is the default window; the dashboard date filter overrides it. A config update replaces the whole query. */
- query?: MetricsWidgetQueryApi
-}
-
export type DashboardWidgetConfigApi =
| NotebookWidgetConfigApi
| ActivityEventsListWidgetConfigApi
@@ -1519,7 +1253,6 @@ export type DashboardWidgetConfigApi =
| ConversationsRecentTicketsWidgetConfigApi
| CanvasAppWidgetConfigApi
| MetricsTableWidgetConfigApi
- | MetricsWidgetConfigApi
export interface DashboardPatchWidgetOpenApiApi {
/** Existing widget row ID when updating a widget tile via dashboard PATCH. */
@@ -1533,7 +1266,6 @@ export interface DashboardPatchWidgetOpenApiApi {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -1862,6 +1594,32 @@ export interface CustomEventConversionGoalApi {
| null
}
+export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]
+
+export const DaysOfWeekEnumApi = {
+ Number1: 1,
+ Number2: 2,
+ Number3: 3,
+ Number4: 4,
+ Number5: 5,
+ Number6: 6,
+ Number7: 7,
+} as const
+
+export interface DateRangeApi {
+ /** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
+ * -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */
+ date_from?: string | null
+ /** End of the date range. Same format as date_from. Omit or null for "now". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set. */
+ date_to?: string | null
+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */
+ daysOfWeek?: DaysOfWeekEnumApi[] | null
+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */
+ excludeIncompletePeriods?: boolean | null
+ /** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */
+ explicitDate?: boolean | null
+}
+
export type IntervalTypeApi = (typeof IntervalTypeApi)[keyof typeof IntervalTypeApi]
export const IntervalTypeApi = {
@@ -3337,6 +3095,43 @@ export interface TrendsFormulaNodeApi {
formula: string
}
+export type CalculationApi = (typeof CalculationApi)[keyof typeof CalculationApi]
+
+export const CalculationApi = {
+ Fixed: 'fixed',
+ Mean: 'mean',
+ Median: 'median',
+ Min: 'min',
+ Max: 'max',
+} as const
+
+export type PositionApi = (typeof PositionApi)[keyof typeof PositionApi]
+
+export const PositionApi = {
+ Start: 'start',
+ End: 'end',
+} as const
+
+export type ScopeApi = (typeof ScopeApi)[keyof typeof ScopeApi]
+
+export const ScopeApi = {
+ All: 'all',
+ Series: 'series',
+} as const
+
+export interface GoalLineApi {
+ borderColor?: string | null
+ /** Recalculate from returned chart marks. An absent calculation uses the fixed value. */
+ calculation?: CalculationApi | null
+ displayIfCrossed?: boolean | null
+ displayLabel?: boolean | null
+ label: string
+ position?: PositionApi | null
+ /** SQL chart calculations use the primary axis, across all series or separately per series. */
+ scope?: ScopeApi | null
+ value: number
+}
+
export type LegendPositionApi = (typeof LegendPositionApi)[keyof typeof LegendPositionApi]
export const LegendPositionApi = {
@@ -10084,6 +9879,30 @@ export type _InsightQuerySchemaApi =
*/
export type _InsightResultWarningsApi = (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[]
+export type MetricsFilterOpApi = (typeof MetricsFilterOpApi)[keyof typeof MetricsFilterOpApi]
+
+export const MetricsFilterOpApi = {
+ Eq: 'eq',
+ Neq: 'neq',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+} as const
+
+export type MetricsAttributeScopeApi = (typeof MetricsAttributeScopeApi)[keyof typeof MetricsAttributeScopeApi]
+
+export const MetricsAttributeScopeApi = {
+ Resource: 'resource',
+ Attribute: 'attribute',
+ Auto: 'auto',
+} as const
+
+export interface MetricsQueryFilterApi {
+ key: string
+ op: MetricsFilterOpApi
+ scope?: MetricsAttributeScopeApi | null
+ value: string
+}
+
export interface MetricsDashboardVariableSelectionApi {
all?: boolean | null
/** The selected values. Empty when `all` is true: All stands for every option of the variable. */
@@ -10565,8 +10384,6 @@ export interface DashboardWidgetRunResultApi {
* @nullable
*/
error: string | null
- /** True when `error` explains the failure to the viewer (for example, no access or an invalid query) and can be shown as is. Other errors are generic. */
- error_is_user_facing?: boolean
}
export interface RunWidgetsResponseApi {
@@ -10649,7 +10466,6 @@ export interface AddDashboardWidgetRequestApi {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -10664,7 +10480,7 @@ export interface AddDashboardWidgetRequestApi {
*/
export interface AddDashboardWidgetsBatchRequestOpenApiApi {
/**
- * Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
+ * Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
* @minItems 1
* @maxItems 10
*/
@@ -10701,7 +10517,6 @@ export interface UpdateDashboardWidgetRequestApi {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -11032,27 +10847,6 @@ export interface MetricsTableWidgetCatalogEntryOpenApiApi {
live: boolean
}
-export type MetricsWidgetCatalogEntryOpenApiApiWidgetType =
- (typeof MetricsWidgetCatalogEntryOpenApiApiWidgetType)[keyof typeof MetricsWidgetCatalogEntryOpenApiApiWidgetType]
-
-export const MetricsWidgetCatalogEntryOpenApiApiWidgetType = {
- Metrics: 'metrics',
-} as const
-
-export interface MetricsWidgetCatalogEntryOpenApiApi {
- widget_type: MetricsWidgetCatalogEntryOpenApiApiWidgetType
- group_id: string
- group_label: string
- label: string
- description: string
- /** Config shape for this widget type. Build the config for the batch add and batch update tools from it, because their schemas do not list config keys. */
- readonly config_schema: MetricsWidgetConfigApi
- /** @nullable */
- required_product_access?: string | null
- /** Whether tiles of this type self-update in real time after load. Live tiles show a fixed real-time window and cannot apply test-account filtering to the stream, so their config takes neither dateRange nor filterTestAccounts. */
- live: boolean
-}
-
export type WidgetCatalogEntryApi =
| NotebookWidgetCatalogEntryOpenApiApi
| ActivityEventsListWidgetCatalogEntryOpenApiApi
@@ -11065,7 +10859,6 @@ export type WidgetCatalogEntryApi =
| ConversationsRecentTicketsWidgetCatalogEntryOpenApiApi
| CanvasAppWidgetCatalogEntryOpenApiApi
| MetricsTableWidgetCatalogEntryOpenApiApi
- | MetricsWidgetCatalogEntryOpenApiApi
export interface WidgetCatalogResponseApi {
/** Registered dashboard widget types. */
@@ -11201,15 +10994,6 @@ export const MetricsTableWidgetTypeEnumApi = {
MetricsTable: 'metrics_table',
} as const
-/**
- * * `metrics` - metrics
- */
-export type MetricsWidgetTypeEnumApi = (typeof MetricsWidgetTypeEnumApi)[keyof typeof MetricsWidgetTypeEnumApi]
-
-export const MetricsWidgetTypeEnumApi = {
- Metrics: 'metrics',
-} as const
-
export type DashboardTemplatesListParams = {
/**
* Omit for all templates. When set, filter by featured flag; parsed with str_to_bool (same as other API query booleans).
@@ -11524,15 +11308,7 @@ export const DashboardsRunInsightsRetrieveRefresh = {
} as const
export type DashboardsRunWidgetsRetrieveParams = {
- /**
- * Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.
- */
- filters_override?: string
format?: DashboardsRunWidgetsRetrieveFormat
- /**
- * Recompute widgets that follow dashboard filters (such as metrics) instead of serving their query cache, as a manual refresh of an insight tile does.
- */
- refresh?: boolean
/**
* Comma-separated dashboard tile IDs to run widgets for.
*/
@@ -11690,7 +11466,6 @@ export const DashboardsWidgetCatalogRetrieveWidgetTypeItem = {
ExperimentResults: 'experiment_results',
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
- Metrics: 'metrics',
MetricsTable: 'metrics_table',
NotebookWidget: 'notebook_widget',
SessionReplayList: 'session_replay_list',
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index a0c8114937fd..72c3e3c2d521 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -655,9 +655,1257 @@ export const DashboardsUpdateBody = /* @__PURE__ */ zod
})
.describe('Serializer mixin that handles tags for objects.')
+export const dashboardsPartialUpdateBodyNameMax = 400
+
+export const dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')
+export const dashboardsPartialUpdateBodyGroupsTitleMax = 200
+
+export const dashboardsPartialUpdateBodyGroupTitlesMaxOne = 200
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneXMin = 0
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneXMax = 11
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneYMin = 0
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneWMax = 12
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneXMin = 0
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneXMax = 11
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneYMin = 0
+
+export const dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneWMax = 12
+
+export const dashboardsPartialUpdateBodyTilesItemGroupKeyMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneNotebookShortIdOneMax = 128
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoLimitDefault = 25
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoLimitMax = 50
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemKeyMax = 400
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemLabelOneMax = 400
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueOneItemOneMax = 4000
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueOneMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueTwoMax = 4000
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneMax = 20
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitMax = 25
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderByDefault = `occurrences`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderDirectionDefault = `DESC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeStatusDefault = `active`
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax = 25
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault = `start_time`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault = `DESC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveLimitMax = 25
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveOrderByDefault = `created_at`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveOrderDirectionDefault = `DESC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveStatusDefault = `all`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax = 25
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightLimitDefault = 50
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightLimitMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightOrderByDefault = `latest`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightWrapLinesDefault = false
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightTimezoneDefault = `UTC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineLimitMax = 25
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineStatusDefault = `all`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineChannelDefault = `all`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineAssigneesMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSearchDefault = ``
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSearchMax = 200
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSavedViewIdOneMax = 12
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneGroupByOneMax = 200
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemLabelMax = 40
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemMetricNameMax = 200
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemQuantileOneExclusiveMin = 0
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemQuantileOneExclusiveMax = 1
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemKeyMax = 200
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemOpDefault = `eq`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemValueMax = 400
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersMax = 5
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsMax = 6
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderByColumnDefault = 0
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderByColumnMin = 0
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderDirectionDefault = `DESC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneLimitDefault = 25
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneLimitMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax = 400
+
+export const dashboardsPartialUpdateBodyDeleteInsightsDefault = false
+
export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
- .record(zod.string(), zod.unknown())
- .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+ .object({
+ name: zod.string().max(dashboardsPartialUpdateBodyNameMax).nullish(),
+ description: zod.string().optional(),
+ pinned: zod.boolean().optional(),
+ filters: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ "Dashboard-level start of the date range, e.g. '-30d', '-7d', or an ISO date. Applies to all tiles."
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe(
+ "Dashboard-level end of the date range, e.g. '-1d' or an ISO date. Null\/omitted means up to now."
+ ),
+ properties: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Dashboard-level property filters applied to every tile (PostHog property filter group).'
+ ),
+ })
+ .describe(
+ "OpenAPI-only shape for a dashboard's filters object (agents\/MCP).\n\nDocuments the dashboard-level filters that act as the single source of truth for the\ndashboard's tiles. Runtime persistence reads the raw ``filters`` dict from the request body, so\nextra keys are accepted, but these are the ones agents should set."
+ )
+ .optional()
+ .describe(
+ 'Dashboard-level filters (date range and properties) applied across all tiles as the source of truth.'
+ ),
+ breakdown_colors: zod
+ .array(
+ zod.object({
+ breakdownValue: zod
+ .string()
+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),
+ colorToken: zod
+ .string()
+ .regex(dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp)
+ .nullable()
+ .describe(
+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'
+ ),
+ breakdownType: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'
+ ),
+ breakdownProperty: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'
+ ),
+ source: zod
+ .union([
+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."
+ ),
+ data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),
+ tags: zod.array(zod.string()).optional(),
+ quick_filter_ids: zod
+ .array(zod.string())
+ .nullish()
+ .describe('List of quick filter IDs associated with this dashboard.'),
+ grid_spacing: zod
+ .enum(['tight', 'condensed', 'standard', 'relaxed', 'wide'])
+ .describe(
+ '\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
+ )
+ .optional()
+ .describe(
+ 'Named tile density preset. Use tight, condensed, standard, relaxed, or wide.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'
+ ),
+ layout_compaction: zod
+ .enum(['vertical', 'horizontal', 'stable'])
+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')
+ .optional()
+ .describe(
+ 'How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'
+ ),
+ group_display: zod
+ .enum(['sections', 'tabs'])
+ .describe('\* `sections` - sections\n\* `tabs` - tabs')
+ .optional()
+ .describe(
+ 'How tile groups show. sections shows each group as a band that opens and closes. tabs shows one group at a time, and tiles outside any group get their own first tab.\n\n\* `sections` - sections\n\* `tabs` - tabs'
+ ),
+ groups: zod
+ .record(
+ zod.string(),
+ zod.object({
+ title: zod
+ .string()
+ .max(dashboardsPartialUpdateBodyGroupsTitleMax)
+ .optional()
+ .describe(
+ 'Heading for the group. When it is blank or omitted, the heading shows the number of tiles.'
+ ),
+ collapsed: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it.'
+ ),
+ color: zod
+ .union([
+ zod
+ .enum(['blue', 'purple', 'green', 'yellow', 'orange', 'red'])
+ .describe(
+ '\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Color of a dot before the group heading. Null or omitted shows no dot.\n\n\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ "Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings."
+ ),
+ group_titles: zod
+ .record(zod.string(), zod.string().max(dashboardsPartialUpdateBodyGroupTitlesMaxOne))
+ .nullish()
+ .describe(
+ 'Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.'
+ ),
+ tiles: zod
+ .array(
+ zod.object({
+ id: zod.number().optional().describe('Dashboard tile ID to update.'),
+ layouts: zod
+ .object({
+ sm: zod
+ .object({
+ x: zod
+ .number()
+ .min(dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneXMin)
+ .max(dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneXMax)
+ .describe('Column position in the dashboard grid (0-indexed).'),
+ y: zod
+ .number()
+ .min(dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneYMin)
+ .describe('Row position in the dashboard grid (0-indexed).'),
+ w: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemLayoutsOneSmOneWMax)
+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),
+ h: zod.number().min(1).describe('Height in grid rows.'),
+ })
+ .describe(
+ "Layout for the standard (desktop) breakpoint. The grid is 12 columns wide. A write replaces the tile's whole layout and the dashboard reads desktop placement from this box, so send it whenever you send layouts."
+ ),
+ xs: zod
+ .object({
+ x: zod
+ .number()
+ .min(dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneXMin)
+ .max(dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneXMax)
+ .describe('Column position in the dashboard grid (0-indexed).'),
+ y: zod
+ .number()
+ .min(dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneYMin)
+ .describe('Row position in the dashboard grid (0-indexed).'),
+ w: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemLayoutsOneXsOneWMax)
+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),
+ h: zod.number().min(1).describe('Height in grid rows.'),
+ })
+ .optional()
+ .describe(
+ 'Layout for the small (mobile) breakpoint, on a 1-column grid. The dashboard derives this layout from the sm order and heights, so a stored xs box does not change what renders.'
+ ),
+ })
+ .optional()
+ .describe(
+ "Grid position and size per breakpoint. Works for every tile type, including insight tiles. A write replaces the tile's whole layout, so send a complete sm box rather than the one value you want to change. Boxes are stored as sent and overlaps are not resolved, so send sm boxes that do not overlap, and include every tile you move in the same request."
+ ),
+ show_description: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Whether to show the tile's description underneath its title on the dashboard. Works for every tile type. The description itself is unaffected and still comes from the tile's insight, text, or widget content — this only toggles whether it renders on the dashboard."
+ ),
+ group_key: zod
+ .string()
+ .max(dashboardsPartialUpdateBodyTilesItemGroupKeyMax)
+ .nullish()
+ .describe(
+ "Key that puts this tile in a group with the other tiles that have the same key on this dashboard. Set the group's title and style in the dashboard's groups. Null or an empty string removes the tile from its group."
+ ),
+ badge: zod
+ .union([
+ zod
+ .enum(['winner', 'cheeky-hog'])
+ .describe('\* `winner` - Winner\n\* `cheeky-hog` - Cheeky hog'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Badge on the tile. winner shows a crown in the top left corner, for example to mark the best tile in a group. cheeky-hog shows a hedgehog when a person hovers over the tile. Null removes the badge. More than one tile in a group can have the winner badge.\n\n\* `winner` - Winner\n\* `cheeky-hog` - Cheeky hog'
+ ),
+ widget: zod
+ .object({
+ id: zod
+ .uuid()
+ .optional()
+ .describe('Existing widget row ID when updating a widget tile via dashboard PATCH.'),
+ widget_type: zod
+ .enum([
+ 'activity_events_list',
+ 'canvas_app',
+ 'conversations_recent_tickets',
+ 'error_tracking_list',
+ 'experiment_results',
+ 'experiments_list',
+ 'logs_list',
+ 'metrics_table',
+ 'notebook_widget',
+ 'session_replay_list',
+ 'survey_results',
+ ])
+ .describe(
+ '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ )
+ .optional()
+ .describe(
+ 'Widget type identifier (cannot be changed on update).\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ ),
+ config: zod
+ .union([
+ zod.object({
+ notebookShortId: zod
+ .union([
+ zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneNotebookShortIdOneMax
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Source notebook short ID.'),
+ snapshotId: zod
+ .union([zod.uuid(), zod.null()])
+ .optional()
+ .describe(
+ "Immutable notebook widget snapshot. Add one from a notebook widget's menu."
+ ),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),
+ widgetFilters: zod
+ .union([
+ zod.record(
+ zod.string(),
+ zod.object({
+ filterId: zod.string().min(1),
+ propertyName: zod.string().min(1),
+ optionId: zod.string().min(1),
+ operator: zod.enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'is_set',
+ 'is_not_set',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'between',
+ 'not_between',
+ 'min',
+ 'max',
+ 'in',
+ 'not_in',
+ 'is_cleaned_path_exact',
+ 'is_cleaned_path_not_exact',
+ 'flag_evaluates_to',
+ 'semver_eq',
+ 'semver_neq',
+ 'semver_gt',
+ 'semver_gte',
+ 'semver_lt',
+ 'semver_lte',
+ 'semver_tilde',
+ 'semver_caret',
+ 'semver_wildcard',
+ 'icontains_multi',
+ 'not_icontains_multi',
+ ]),
+ value: zod
+ .union([zod.string(), zod.array(zod.string()), zod.null()])
+ .optional(),
+ })
+ ),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoLimitDefault
+ )
+ .describe('Maximum number of events to return.'),
+ eventName: zod
+ .union([zod.string().min(1), zod.null()])
+ .optional()
+ .describe(
+ 'Limit the feed to a single event name. Omit or null for all events.'
+ ),
+ properties: zod
+ .union([
+ zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemKeyMax
+ ),
+ label: zod
+ .union([
+ zod
+ .string()
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemLabelOneMax
+ ),
+ zod.null(),
+ ])
+ .optional(),
+ operator: zod.enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'is_set',
+ 'is_not_set',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'between',
+ 'not_between',
+ 'min',
+ 'max',
+ 'in',
+ 'not_in',
+ 'is_cleaned_path_exact',
+ 'is_cleaned_path_not_exact',
+ 'flag_evaluates_to',
+ 'semver_eq',
+ 'semver_neq',
+ 'semver_gt',
+ 'semver_gte',
+ 'semver_lt',
+ 'semver_lte',
+ 'semver_tilde',
+ 'semver_caret',
+ 'semver_wildcard',
+ 'icontains_multi',
+ 'not_icontains_multi',
+ ]),
+ type: zod.enum(['event', 'person']),
+ value: zod
+ .union([
+ zod
+ .array(
+ zod.union([
+ zod
+ .string()
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueOneItemOneMax
+ ),
+ zod.number(),
+ zod.boolean(),
+ ])
+ )
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueOneMax
+ ),
+ zod
+ .string()
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneItemValueTwoMax
+ ),
+ zod.number(),
+ zod.boolean(),
+ zod.null(),
+ ])
+ .optional(),
+ })
+ )
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoPropertiesOneMax
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Event and person property filters, matching Activity > Explore events.'
+ ),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),
+ widgetFilters: zod
+ .union([
+ zod.record(
+ zod.string(),
+ zod.object({
+ filterId: zod.string().min(1),
+ propertyName: zod.string().min(1),
+ optionId: zod.string().min(1),
+ operator: zod.enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'is_set',
+ 'is_not_set',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'between',
+ 'not_between',
+ 'min',
+ 'max',
+ 'in',
+ 'not_in',
+ 'is_cleaned_path_exact',
+ 'is_cleaned_path_not_exact',
+ 'flag_evaluates_to',
+ 'semver_eq',
+ 'semver_neq',
+ 'semver_gt',
+ 'semver_gte',
+ 'semver_lt',
+ 'semver_lte',
+ 'semver_tilde',
+ 'semver_caret',
+ 'semver_wildcard',
+ 'icontains_multi',
+ 'not_icontains_multi',
+ ]),
+ value: zod
+ .union([zod.string(), zod.array(zod.string()), zod.null()])
+ .optional(),
+ })
+ ),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitDefault
+ )
+ .describe('Maximum number of issues to return.'),
+ orderBy: zod
+ .enum([
+ 'last_seen',
+ 'first_seen',
+ 'occurrences',
+ 'users',
+ 'sessions',
+ 'severity',
+ ])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderByDefault
+ )
+ .describe('Issue ranking column.'),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderDirectionDefault
+ )
+ .describe('Sort direction for orderBy.'),
+ status: zod
+ .enum([
+ 'archived',
+ 'active',
+ 'resolved',
+ 'pending_release',
+ 'suppressed',
+ 'all',
+ ])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeStatusDefault
+ )
+ .describe('Issue status filter.'),
+ assignee: zod
+ .union([
+ zod.object({
+ id: zod.union([zod.string(), zod.number()]),
+ type: zod.enum(['user', 'role']),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Filter by assignee ({type: user|role, id}). Omit for any assignee.'
+ ),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ filterTestAccounts: zod.union([zod.boolean(), zod.null()]).optional(),
+ widgetFilters: zod
+ .union([
+ zod.record(
+ zod.string(),
+ zod.object({
+ filterId: zod.string().min(1),
+ propertyName: zod.string().min(1),
+ optionId: zod.string().min(1),
+ operator: zod.enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'is_set',
+ 'is_not_set',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'between',
+ 'not_between',
+ 'min',
+ 'max',
+ 'in',
+ 'not_in',
+ 'is_cleaned_path_exact',
+ 'is_cleaned_path_not_exact',
+ 'flag_evaluates_to',
+ 'semver_eq',
+ 'semver_neq',
+ 'semver_gt',
+ 'semver_gte',
+ 'semver_lt',
+ 'semver_lte',
+ 'semver_tilde',
+ 'semver_caret',
+ 'semver_wildcard',
+ 'icontains_multi',
+ 'not_icontains_multi',
+ ]),
+ value: zod
+ .union([zod.string(), zod.array(zod.string()), zod.null()])
+ .optional(),
+ })
+ ),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault
+ )
+ .describe('Maximum number of recordings to return.'),
+ orderBy: zod
+ .enum([
+ 'start_time',
+ 'activity_score',
+ 'recording_duration',
+ 'duration',
+ 'click_count',
+ 'console_error_count',
+ ])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault
+ )
+ .describe('Recording ranking column.'),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault
+ )
+ .describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to refine the recordings shown. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply. Combine with collectionId to filter within a collection.'
+ ),
+ collectionId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a session replay collection to scope the widget to its pinned recordings. Combine with savedFilterId or property filters to narrow within the collection; orderBy, orderDirection, and limit still apply.'
+ ),
+ }),
+ zod.object({
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveLimitDefault
+ )
+ .describe('Maximum number of experiments to return.'),
+ orderBy: zod
+ .enum(['created_at', 'name', 'start_date'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveOrderByDefault
+ )
+ .describe('Experiment list sort column.'),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveOrderDirectionDefault
+ )
+ .describe('Sort direction for orderBy.'),
+ status: zod
+ .enum(['draft', 'running', 'paused', 'exposure_frozen', 'stopped', 'all'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFiveStatusDefault
+ )
+ .describe('Experiment status filter.'),
+ createdBy: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Filter by creator (user id). Omit for any creator.'),
+ }),
+ zod.object({
+ experimentId: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe(
+ 'Experiment to show results for. Null until the user picks one in the widget settings.'
+ ),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault
+ )
+ .describe('Maximum number of recent responses to return.'),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightLimitDefault
+ )
+ .describe('Maximum number of log lines to return.'),
+ orderBy: zod
+ .enum(['latest', 'earliest'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightOrderByDefault
+ )
+ .describe('Sort by newest (latest) or oldest (earliest) first.'),
+ severityLevels: zod
+ .array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']))
+ .optional()
+ .describe(
+ 'Only show logs at these severity levels. Empty shows all levels.'
+ ),
+ serviceNames: zod
+ .array(zod.string())
+ .optional()
+ .describe('Only show logs from these services. Empty shows all services.'),
+ wrapLines: zod
+ .boolean()
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightWrapLinesDefault
+ )
+ .describe(
+ 'Wrap long log lines instead of truncating them to a single row.'
+ ),
+ timezone: zod
+ .enum(['UTC', 'local'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneEightTimezoneDefault
+ )
+ .describe(
+ "Render log timestamps in UTC or in each viewer's local timezone."
+ ),
+ savedViewId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved logs view to use as the source. When set, the saved view owns the date range, severity, service, and property filters; only orderBy and limit still apply.'
+ ),
+ }),
+ zod.object({
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineLimitDefault
+ )
+ .describe('Maximum number of tickets to return.'),
+ status: zod
+ .enum(['new', 'open', 'pending', 'on_hold', 'resolved', 'all'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineStatusDefault
+ )
+ .describe('Ticket status filter.'),
+ priorities: zod
+ .array(zod.enum(['low', 'medium', 'high', 'critical']))
+ .optional()
+ .describe(
+ 'Only show tickets with these priorities. Empty shows all priorities.'
+ ),
+ channel: zod
+ .enum(['widget', 'email', 'slack', 'teams', 'github', 'all'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineChannelDefault
+ )
+ .describe('Ticket channel filter.'),
+ assignees: zod
+ .array(
+ zod.union([
+ zod.enum(['me', 'unassigned']),
+ zod.object({
+ id: zod.union([zod.string(), zod.number()]),
+ type: zod.enum(['user', 'role']),
+ }),
+ ])
+ )
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineAssigneesMax)
+ .optional()
+ .describe(
+ "Only show tickets assigned to these users or roles. 'me' means the requesting user and 'unassigned' means tickets without an assignment. Empty shows all assignees."
+ ),
+ search: zod
+ .string()
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSearchMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSearchDefault
+ )
+ .describe(
+ 'Search requester name or email, ticket subject, message text, or ticket number.'
+ ),
+ savedViewId: zod
+ .union([
+ zod
+ .string()
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneNineSavedViewIdOneMax
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'short_id of a saved Support view to use as the source. When set, the saved view owns the ticket filters; the widget still sorts by most recently updated and applies its limit.'
+ ),
+ }),
+ zod.object({
+ canvasId: zod
+ .union([zod.uuid(), zod.null()])
+ .optional()
+ .describe(
+ 'Canvas to render in the tile. Null until the user picks one in the widget settings.'
+ ),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ groupBy: zod
+ .union([
+ zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneGroupByOneMax
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Label that makes one row per value, e.g. `http.route`. Null until the user sets it.'
+ ),
+ columns: zod
+ .array(
+ zod.object({
+ label: zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemLabelMax
+ )
+ .describe('Column header, e.g. `Requests\/s`.'),
+ metricName: zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemMetricNameMax
+ )
+ .describe('Name of the metric this column reads.'),
+ aggregation: zod
+ .enum([
+ 'rate',
+ 'increase',
+ 'sum',
+ 'avg',
+ 'min',
+ 'max',
+ 'histogram_quantile',
+ ])
+ .describe(
+ 'How each time bucket of a row is computed. `rate` and `increase` read counters.'
+ ),
+ quantile: zod
+ .union([
+ zod
+ .number()
+ .gt(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemQuantileOneExclusiveMin
+ )
+ .lt(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemQuantileOneExclusiveMax
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Required for `histogram_quantile`, e.g. 0.95 for p95.'
+ ),
+ filters: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemKeyMax
+ )
+ .describe(
+ 'Label key to filter on, e.g. `http.response.status_code`.'
+ ),
+ op: zod
+ .enum(['eq', 'neq', 'regex', 'not_regex'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemOpDefault
+ )
+ .describe('How the label value is compared.'),
+ value: zod
+ .string()
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersItemValueMax
+ )
+ .describe(
+ 'Label value, or a regular expression for `regex` and `not_regex`.'
+ ),
+ })
+ )
+ .max(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsItemFiltersMax
+ )
+ .optional()
+ .describe(
+ 'Label filters for this column only, e.g. 5xx status codes for an errors column.'
+ ),
+ })
+ )
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneColumnsMax)
+ .optional()
+ .describe(
+ "One metric per column. Each row shows the column's average over the date range and a sparkline."
+ ),
+ interval: zod
+ .union([
+ zod.enum(['minute', 'minute_5', 'minute_15', 'hour', 'day']),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Time between the points of the full charts that open from a row. Null picks one from the date range. The table sparklines always use at most 30 points.'
+ ),
+ orderByColumn: zod
+ .number()
+ .min(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderByColumnMin
+ )
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderByColumnDefault
+ )
+ .describe('Index of the column that sorts the rows.'),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneOrderDirectionDefault
+ )
+ .describe('Sort direction for orderByColumn.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneoneLimitDefault
+ )
+ .describe('Maximum number of rows to show.'),
+ }),
+ ])
+ .optional()
+ .describe("Widget-specific configuration. Shape depends on the tile's widget_type."),
+ name: zod
+ .string()
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax)
+ .nullish()
+ .describe('Optional custom display name for the widget tile.'),
+ description: zod
+ .string()
+ .optional()
+ .describe('Optional markdown description shown when show_description is enabled.'),
+ })
+ .optional()
+ .describe('Nested widget row updates.'),
+ })
+ )
+ .optional()
+ .describe(
+ 'Dashboard tiles to update, each identified by its tile id. Any tile type accepts `layouts` to set its grid position and size. Widget tiles also accept nested widget.config patches.'
+ ),
+ use_template: zod
+ .string()
+ .optional()
+ .describe('Template key to create the dashboard from a predefined template.'),
+ use_dashboard: zod.number().nullish().describe('ID of an existing dashboard to duplicate.'),
+ delete_insights: zod
+ .boolean()
+ .default(dashboardsPartialUpdateBodyDeleteInsightsDefault)
+ .describe('When deleting, also delete insights that are only on this dashboard.'),
+ })
+ .describe(
+ 'OpenAPI-only PATCH body for dashboards (agents\/MCP).\n\nMust be a superset of ``dashboard_patch_runtime_openapi_field_names()`` — ``extend_schema(request=...)``\nreplaces the inferred schema entirely. Contract: ``test_dashboard_openapi.py``.'
+ )
/**
* Place an existing insight on this dashboard as a new tile. Requires edit access to the dashboard and view access to the insight. Returns the tile. Adding an insight the dashboard already shows returns its tile unchanged, and adding one that was removed from the dashboard restores its tile with its old layout. To take an insight off a dashboard, use delete_tile.
@@ -934,17 +2182,16 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
'experiment_results',
'experiments_list',
'logs_list',
- 'metrics',
'metrics_table',
'notebook_widget',
'session_replay_list',
'survey_results',
])
.describe(
- '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
)
.describe(
- 'Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ 'Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
),
config: zod
.record(zod.string(), zod.unknown())
@@ -956,7 +2203,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsMax)
.describe(
- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'
+ 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'
),
})
.describe('OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.')
@@ -1002,18 +2249,17 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
'experiment_results',
'experiments_list',
'logs_list',
- 'metrics',
'metrics_table',
'notebook_widget',
'session_replay_list',
'survey_results',
])
.describe(
- '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
)
.optional()
.describe(
- "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results"
+ "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results"
),
config: zod
.record(zod.string(), zod.unknown())
diff --git a/products/dashboards/frontend/generated/widget-config-property-keys.json b/products/dashboards/frontend/generated/widget-config-property-keys.json
index 40316c29ad22..38337827801c 100644
--- a/products/dashboards/frontend/generated/widget-config-property-keys.json
+++ b/products/dashboards/frontend/generated/widget-config-property-keys.json
@@ -52,8 +52,7 @@
"status"
],
"canvas_app": ["canvasId"],
- "metrics_table": ["columns", "dateRange", "groupBy", "interval", "limit", "orderByColumn", "orderDirection"],
- "metrics": ["query"]
+ "metrics_table": ["columns", "dateRange", "groupBy", "interval", "limit", "orderByColumn", "orderDirection"]
},
"configPropertyTrees": {
"notebook_widget": {
@@ -532,182 +531,6 @@
"limit": {
"$type": "integer"
}
- },
- "metrics": {
- "query": {
- "clauses": {
- "$array": {
- "aggregation": {
- "$enum": [
- "avg",
- "count",
- "histogram_quantile",
- "increase",
- "max",
- "min",
- "quantile",
- "rate",
- "sum"
- ]
- },
- "filters": {
- "$array": {
- "key": {
- "$type": "string"
- },
- "op": {
- "$enum": ["eq", "neq", "not_regex", "regex"]
- },
- "scope": {
- "$enum": ["attribute", "auto", "resource"]
- },
- "value": {
- "$type": "string"
- }
- }
- },
- "groupBy": {
- "$array": {
- "key": {
- "$type": "string"
- },
- "scope": {
- "$enum": ["attribute", "auto", "resource"]
- }
- }
- },
- "metricName": {
- "$type": "string"
- },
- "metricType": {
- "$enum": ["exponential_histogram", "gauge", "histogram", "sum", "summary"]
- },
- "name": {
- "$type": "string"
- },
- "quantile": {
- "$type": "number"
- },
- "rangeFunction": {
- "$enum": ["increase", "rate"]
- }
- }
- },
- "dateRange": {
- "date_from": {
- "$type": "string"
- },
- "date_to": {
- "$type": "string"
- },
- "daysOfWeek": {
- "$array": {
- "$enum": [1, 2, 3, 4, 5, 6, 7]
- }
- },
- "excludeIncompletePeriods": {
- "$type": "boolean"
- },
- "explicitDate": {
- "$type": "boolean"
- }
- },
- "display": {
- "goalLines": {
- "$array": {
- "borderColor": {
- "$type": "string"
- },
- "calculation": {
- "$enum": ["fixed", "max", "mean", "median", "min"]
- },
- "displayIfCrossed": {
- "$type": "boolean"
- },
- "displayLabel": {
- "$type": "boolean"
- },
- "label": {
- "$type": "string"
- },
- "position": {
- "$enum": ["end", "start"]
- },
- "scope": {
- "$enum": ["all", "series"]
- },
- "value": {
- "$type": "number"
- }
- }
- },
- "legendCalcs": {
- "$array": {
- "$enum": ["delta", "last", "max", "mean", "min", "sum"]
- }
- },
- "nullMode": {
- "$enum": ["connect", "gap", "zero"]
- },
- "reduce": {
- "$enum": ["delta", "last", "max", "mean", "min", "sum"]
- },
- "statSummary": {
- "$enum": ["average", "latest", "total"]
- },
- "thresholds": {
- "$array": {
- "color": {
- "$type": "string"
- },
- "value": {
- "$type": "number"
- }
- }
- },
- "type": {
- "$enum": ["area", "bar", "bargauge", "gauge", "heatmap", "line", "stat", "table"]
- },
- "unit": {
- "$type": "string"
- },
- "yAxis": {
- "max": {
- "$type": "number"
- },
- "min": {
- "$type": "number"
- },
- "scale": {
- "$enum": ["linear", "log"]
- },
- "startAtZero": {
- "$type": "boolean"
- }
- }
- },
- "formula": {
- "$type": "string"
- },
- "interval": {
- "$type": "string"
- },
- "kind": {
- "$type": "string"
- },
- "language": {
- "$enum": ["builder", "promql", "sql"]
- },
- "promql": {
- "$type": "string"
- },
- "sql": {
- "$type": "string"
- },
- "version": {
- "$type": "number"
- }
- }
}
}
}
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/calculation.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/calculation.zod.ts
deleted file mode 100644
index e4b186eb05f5..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/calculation.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const Calculation = /* @__PURE__ */ zod.enum(['fixed', 'mean', 'median', 'min', 'max'])
-
-export type Calculation = zod.input<typeof Calculation>
-export type CalculationOutput = zod.output<typeof Calculation>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/dateRange.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/dateRange.zod.ts
deleted file mode 100644
index 8b22be2a13d5..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/dateRange.zod.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { DaysOfWeekEnum } from './daysOfWeekEnum.zod'
-
-export const dateRangeExcludeIncompletePeriodsDefault = false
-export const dateRangeExplicitDateDefault = false
-
-export const DateRange = /* @__PURE__ */ zod.object({
- date_from: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- 'Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),\n-1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year).'
- ),
- date_to: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- 'End of the date range. Same format as date_from. Omit or null for \"now\". A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment of that day in the project timezone, unless explicitDate is set.'
- ),
- daysOfWeek: zod
- .union([zod.array(DaysOfWeekEnum), zod.null()])
- .optional()
- .describe(
- 'Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries.'
- ),
- excludeIncompletePeriods: zod
- .union([zod.boolean(), zod.null()])
- .default(dateRangeExcludeIncompletePeriodsDefault)
- .describe(
- 'Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries.'
- ),
- explicitDate: zod
- .union([zod.boolean(), zod.null()])
- .default(dateRangeExplicitDateDefault)
- .describe(
- 'Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.'
- ),
-})
-
-export type DateRange = zod.input<typeof DateRange>
-export type DateRangeOutput = zod.output<typeof DateRange>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/daysOfWeekEnum.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/daysOfWeekEnum.zod.ts
deleted file mode 100644
index db9d43cd992a..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/daysOfWeekEnum.zod.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const DaysOfWeekEnum = /* @__PURE__ */ zod.union([
- zod.literal(1),
- zod.literal(2),
- zod.literal(3),
- zod.literal(4),
- zod.literal(5),
- zod.literal(6),
- zod.literal(7),
-])
-
-export type DaysOfWeekEnum = zod.input<typeof DaysOfWeekEnum>
-export type DaysOfWeekEnumOutput = zod.output<typeof DaysOfWeekEnum>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/goalLine.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/goalLine.zod.ts
deleted file mode 100644
index 90d54cdd7c88..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/goalLine.zod.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { Calculation } from './calculation.zod'
-import { Position } from './position.zod'
-import { Scope } from './scope.zod'
-
-export const GoalLine = /* @__PURE__ */ zod.object({
- borderColor: zod.union([zod.string(), zod.null()]).optional(),
- calculation: zod
- .union([Calculation, zod.null()])
- .optional()
- .describe('Recalculate from returned chart marks. An absent calculation uses the fixed value.'),
- displayIfCrossed: zod.union([zod.boolean(), zod.null()]).optional(),
- displayLabel: zod.union([zod.boolean(), zod.null()]).optional(),
- label: zod.string(),
- position: zod.union([Position, zod.null()]).optional(),
- scope: zod
- .union([Scope, zod.null()])
- .optional()
- .describe('SQL chart calculations use the primary axis, across all series or separately per series.'),
- value: zod.number(),
-})
-
-export type GoalLine = zod.input<typeof GoalLine>
-export type GoalLineOutput = zod.output<typeof GoalLine>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsAggregation.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsAggregation.zod.ts
deleted file mode 100644
index e5c7ff01ddff..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsAggregation.zod.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsAggregation = /* @__PURE__ */ zod.enum([
- 'sum',
- 'avg',
- 'count',
- 'min',
- 'max',
- 'quantile',
- 'rate',
- 'increase',
- 'histogram_quantile',
-])
-
-export type MetricsAggregation = zod.input<typeof MetricsAggregation>
-export type MetricsAggregationOutput = zod.output<typeof MetricsAggregation>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsAttributeScope.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsAttributeScope.zod.ts
deleted file mode 100644
index 733cdcac7484..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsAttributeScope.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsAttributeScope = /* @__PURE__ */ zod.enum(['resource', 'attribute', 'auto'])
-
-export type MetricsAttributeScope = zod.input<typeof MetricsAttributeScope>
-export type MetricsAttributeScopeOutput = zod.output<typeof MetricsAttributeScope>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsAxisScale.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsAxisScale.zod.ts
deleted file mode 100644
index e2fa81edb368..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsAxisScale.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsAxisScale = /* @__PURE__ */ zod.enum(['linear', 'log'])
-
-export type MetricsAxisScale = zod.input<typeof MetricsAxisScale>
-export type MetricsAxisScaleOutput = zod.output<typeof MetricsAxisScale>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplaySettings.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplaySettings.zod.ts
deleted file mode 100644
index 2d4893f27b76..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplaySettings.zod.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { GoalLine } from './goalLine.zod'
-import { MetricsDisplayType } from './metricsDisplayType.zod'
-import { MetricsNullMode } from './metricsNullMode.zod'
-import { MetricsReducer } from './metricsReducer.zod'
-import { MetricsStatSummary } from './metricsStatSummary.zod'
-import { MetricsThreshold } from './metricsThreshold.zod'
-import { MetricsYAxisSettings } from './metricsYAxisSettings.zod'
-
-export const metricsDisplaySettingsNullModeDefault = `gap`
-export const metricsDisplaySettingsReduceDefault = `last`
-export const metricsDisplaySettingsStatSummaryDefault = `latest`
-export const metricsDisplaySettingsTypeDefault = `line`
-
-export const MetricsDisplaySettings = /* @__PURE__ */ zod.object({
- goalLines: zod.union([zod.array(GoalLine), zod.null()]).optional(),
- legendCalcs: zod
- .union([zod.array(MetricsReducer), zod.null()])
- .optional()
- .describe('Time-series panels only: which reducers the legend table shows. Empty means no legend calcs.'),
- nullMode: zod
- .union([MetricsNullMode, zod.null()])
- .default(metricsDisplaySettingsNullModeDefault)
- .describe('How a null bucket renders on a time-series chart.'),
- reduce: zod
- .union([MetricsReducer, zod.null()])
- .default(metricsDisplaySettingsReduceDefault)
- .describe('How scalar panels and legend calcs collapse a series to one number.'),
- statSummary: zod
- .union([MetricsStatSummary, zod.null()])
- .default(metricsDisplaySettingsStatSummaryDefault)
- .describe('`stat` display only: which summary the headline value shows.'),
- thresholds: zod
- .union([zod.array(MetricsThreshold), zod.null()])
- .optional()
- .describe('Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter.'),
- type: zod.union([MetricsDisplayType, zod.null()]).default(metricsDisplaySettingsTypeDefault),
- unit: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe('UCUM unit string as OTel writes it, e.g. \"By\", \"ms\", \"%\". Defaults from the response unit.'),
- yAxis: zod.union([MetricsYAxisSettings, zod.null()]).optional(),
-})
-
-export type MetricsDisplaySettings = zod.input<typeof MetricsDisplaySettings>
-export type MetricsDisplaySettingsOutput = zod.output<typeof MetricsDisplaySettings>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplayType.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplayType.zod.ts
deleted file mode 100644
index 86e33c3396f8..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsDisplayType.zod.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsDisplayType = /* @__PURE__ */ zod.enum([
- 'line',
- 'area',
- 'bar',
- 'stat',
- 'gauge',
- 'bargauge',
- 'table',
- 'heatmap',
-])
-
-export type MetricsDisplayType = zod.input<typeof MetricsDisplayType>
-export type MetricsDisplayTypeOutput = zod.output<typeof MetricsDisplayType>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsFilterOp.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsFilterOp.zod.ts
deleted file mode 100644
index ac1dd8dd40fe..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsFilterOp.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsFilterOp = /* @__PURE__ */ zod.enum(['eq', 'neq', 'regex', 'not_regex'])
-
-export type MetricsFilterOp = zod.input<typeof MetricsFilterOp>
-export type MetricsFilterOpOutput = zod.output<typeof MetricsFilterOp>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsNullMode.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsNullMode.zod.ts
deleted file mode 100644
index 6cde220adaad..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsNullMode.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsNullMode = /* @__PURE__ */ zod.enum(['gap', 'zero', 'connect'])
-
-export type MetricsNullMode = zod.input<typeof MetricsNullMode>
-export type MetricsNullModeOutput = zod.output<typeof MetricsNullMode>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsOtelType.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsOtelType.zod.ts
deleted file mode 100644
index 7fa5c34694ca..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsOtelType.zod.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsOtelType = /* @__PURE__ */ zod.enum([
- 'gauge',
- 'sum',
- 'histogram',
- 'exponential_histogram',
- 'summary',
-])
-
-export type MetricsOtelType = zod.input<typeof MetricsOtelType>
-export type MetricsOtelTypeOutput = zod.output<typeof MetricsOtelType>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryClause.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryClause.zod.ts
deleted file mode 100644
index d1df174bc3b0..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryClause.zod.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { MetricsAggregation } from './metricsAggregation.zod'
-import { MetricsOtelType } from './metricsOtelType.zod'
-import { MetricsQueryFilter } from './metricsQueryFilter.zod'
-import { MetricsQueryGroupBy } from './metricsQueryGroupBy.zod'
-import { MetricsRangeFunction } from './metricsRangeFunction.zod'
-
-export const MetricsQueryClause = /* @__PURE__ */ zod.object({
- aggregation: zod
- .union([MetricsAggregation, zod.null()])
- .optional()
- .describe('Omit to get one line per series (at most 100), without combining them'),
- filters: zod.union([zod.array(MetricsQueryFilter), zod.null()]).optional(),
- groupBy: zod.union([zod.array(MetricsQueryGroupBy), zod.null()]).optional(),
- metricName: zod.string(),
- metricType: zod
- .union([MetricsOtelType, zod.null()])
- .optional()
- .describe(
- 'Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series.'
- ),
- name: zod.string().describe('Alias a formula refers to (e.g. \"a\"); must be unique within the query'),
- quantile: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('In (0, 1); required for `quantile` \/ `histogram_quantile` aggregations'),
- rangeFunction: zod
- .union([MetricsRangeFunction, zod.null()])
- .optional()
- .describe('Applied to each series before `aggregation`, like `rate()` in PromQL'),
-})
-
-export type MetricsQueryClause = zod.input<typeof MetricsQueryClause>
-export type MetricsQueryClauseOutput = zod.output<typeof MetricsQueryClause>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryFilter.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryFilter.zod.ts
deleted file mode 100644
index 774ee611c232..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryFilter.zod.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { MetricsAttributeScope } from './metricsAttributeScope.zod'
-import { MetricsFilterOp } from './metricsFilterOp.zod'
-
-export const MetricsQueryFilter = /* @__PURE__ */ zod.object({
- key: zod.string(),
- op: MetricsFilterOp,
- scope: zod.union([MetricsAttributeScope, zod.null()]).optional(),
- value: zod.string(),
-})
-
-export type MetricsQueryFilter = zod.input<typeof MetricsQueryFilter>
-export type MetricsQueryFilterOutput = zod.output<typeof MetricsQueryFilter>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryGroupBy.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryGroupBy.zod.ts
deleted file mode 100644
index 4ca70de449f9..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryGroupBy.zod.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { MetricsAttributeScope } from './metricsAttributeScope.zod'
-
-export const MetricsQueryGroupBy = /* @__PURE__ */ zod.object({
- key: zod.string(),
- scope: zod.union([MetricsAttributeScope, zod.null()]).optional(),
-})
-
-export type MetricsQueryGroupBy = zod.input<typeof MetricsQueryGroupBy>
-export type MetricsQueryGroupByOutput = zod.output<typeof MetricsQueryGroupBy>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryLanguage.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryLanguage.zod.ts
deleted file mode 100644
index 998b6d9f18cb..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsQueryLanguage.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsQueryLanguage = /* @__PURE__ */ zod.enum(['builder', 'promql', 'sql'])
-
-export type MetricsQueryLanguage = zod.input<typeof MetricsQueryLanguage>
-export type MetricsQueryLanguageOutput = zod.output<typeof MetricsQueryLanguage>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsRangeFunction.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsRangeFunction.zod.ts
deleted file mode 100644
index 0812ca12fec1..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsRangeFunction.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsRangeFunction = /* @__PURE__ */ zod.enum(['rate', 'increase'])
-
-export type MetricsRangeFunction = zod.input<typeof MetricsRangeFunction>
-export type MetricsRangeFunctionOutput = zod.output<typeof MetricsRangeFunction>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsReducer.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsReducer.zod.ts
deleted file mode 100644
index 78360d25656f..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsReducer.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsReducer = /* @__PURE__ */ zod.enum(['last', 'mean', 'min', 'max', 'sum', 'delta'])
-
-export type MetricsReducer = zod.input<typeof MetricsReducer>
-export type MetricsReducerOutput = zod.output<typeof MetricsReducer>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsStatSummary.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsStatSummary.zod.ts
deleted file mode 100644
index 8295c0604bac..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsStatSummary.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsStatSummary = /* @__PURE__ */ zod.enum(['latest', 'average', 'total'])
-
-export type MetricsStatSummary = zod.input<typeof MetricsStatSummary>
-export type MetricsStatSummaryOutput = zod.output<typeof MetricsStatSummary>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsThreshold.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsThreshold.zod.ts
deleted file mode 100644
index 4e6ae0feac3f..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsThreshold.zod.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const MetricsThreshold = /* @__PURE__ */ zod.object({
- color: zod
- .string()
- .describe('A named color token (e.g. \"green\", \"red\"), never raw hex, so light and dark themes both work.'),
- value: zod.number().describe('Lower bound of this band. The lowest step is the base color below every other step.'),
-})
-
-export type MetricsThreshold = zod.input<typeof MetricsThreshold>
-export type MetricsThresholdOutput = zod.output<typeof MetricsThreshold>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetConfig.zod.ts
deleted file mode 100644
index eb46ca084b90..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetConfig.zod.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { MetricsWidgetQuery } from './metricsWidgetQuery.zod'
-
-export const MetricsWidgetConfig = /* @__PURE__ */ zod.object({
- query: MetricsWidgetQuery.optional().describe(
- 'Metrics query the tile runs and how it draws it (`display.type`: line, area, bar, stat, gauge, bargauge, table or heatmap). `dateRange` is the default window; the dashboard date filter overrides it. A config update replaces the whole query.'
- ),
-})
-
-export type MetricsWidgetConfig = zod.input<typeof MetricsWidgetConfig>
-export type MetricsWidgetConfigOutput = zod.output<typeof MetricsWidgetConfig>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetQuery.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetQuery.zod.ts
deleted file mode 100644
index b432e2ba8e0a..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsWidgetQuery.zod.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { DateRange } from './dateRange.zod'
-import { MetricsDisplaySettings } from './metricsDisplaySettings.zod'
-import { MetricsQueryClause } from './metricsQueryClause.zod'
-import { MetricsQueryLanguage } from './metricsQueryLanguage.zod'
-
-export const metricsWidgetQueryClausesMax = 10
-
-export const metricsWidgetQueryKindDefault = `MetricsQuery`
-export const metricsWidgetQueryPromqlOneMax = 10000
-
-export const metricsWidgetQuerySqlOneMax = 10000
-
-export const MetricsWidgetQuery = /* @__PURE__ */ zod
- .object({
- clauses: zod
- .array(MetricsQueryClause)
- .max(metricsWidgetQueryClausesMax)
- .optional()
- .describe('Builder series. Empty when `language` is `promql` or `sql`, or until a metric is picked.'),
- dateRange: zod
- .union([DateRange, zod.null()])
- .optional()
- .describe('Defaults to the last 24 hours when omitted; dashboard date filters override it'),
- display: zod
- .union([MetricsDisplaySettings, zod.null()])
- .optional()
- .describe('Chart presentation. A node without it renders as a line chart.'),
- formula: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- 'Arithmetic over clause aliases (e.g. \"a \/ b\"); when set, only the formula series are returned'
- ),
- interval: zod
- .union([zod.string(), zod.null()])
- .optional()
- .describe(
- 'Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable.'
- ),
- kind: zod.literal('MetricsQuery').default(metricsWidgetQueryKindDefault),
- language: zod
- .union([MetricsQueryLanguage, zod.null()])
- .optional()
- .describe('How the query is written; the builder when unset.'),
- promql: zod
- .union([zod.string().max(metricsWidgetQueryPromqlOneMax), zod.null()])
- .optional()
- .describe('PromQL expression, run as a range query. Used when `language` is `promql`.'),
- sql: zod
- .union([zod.string().max(metricsWidgetQuerySqlOneMax), zod.null()])
- .optional()
- .describe(
- 'HogQL SELECT over the posthog.metric\* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label.'
- ),
- version: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('version of the node, used for schema migrations'),
- })
- .describe(
- "A `MetricsQuery` as a metrics widget stores it.\n\nResponse, modifier and tag fields are runtime state, so a stored config can't carry them."
- )
-
-export type MetricsWidgetQuery = zod.input<typeof MetricsWidgetQuery>
-export type MetricsWidgetQueryOutput = zod.output<typeof MetricsWidgetQuery>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/metricsYAxisSettings.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/metricsYAxisSettings.zod.ts
deleted file mode 100644
index a7c794fa4ef0..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/metricsYAxisSettings.zod.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-import { MetricsAxisScale } from './metricsAxisScale.zod'
-
-export const metricsYAxisSettingsScaleDefault = `linear`
-export const metricsYAxisSettingsStartAtZeroDefault = true
-
-export const MetricsYAxisSettings = /* @__PURE__ */ zod.object({
- max: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe(
- 'Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot.'
- ),
- min: zod
- .union([zod.number(), zod.null()])
- .optional()
- .describe('Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on.'),
- scale: zod.union([MetricsAxisScale, zod.null()]).default(metricsYAxisSettingsScaleDefault),
- startAtZero: zod
- .union([zod.boolean(), zod.null()])
- .default(metricsYAxisSettingsStartAtZeroDefault)
- .describe(
- "When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero."
- ),
-})
-
-export type MetricsYAxisSettings = zod.input<typeof MetricsYAxisSettings>
-export type MetricsYAxisSettingsOutput = zod.output<typeof MetricsYAxisSettings>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/position.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/position.zod.ts
deleted file mode 100644
index 3089664a13ce..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/position.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const Position = /* @__PURE__ */ zod.enum(['start', 'end'])
-
-export type Position = zod.input<typeof Position>
-export type PositionOutput = zod.output<typeof Position>
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/scope.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/scope.zod.ts
deleted file mode 100644
index 46948ab251c0..000000000000
--- a/products/dashboards/frontend/generated/widget-config-schemas/scope.zod.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v8.14.0 🍺
- * Do not edit manually.
- * PostHog API - 1 ops
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const Scope = /* @__PURE__ */ zod.enum(['all', 'series'])
-
-export type Scope = zod.input<typeof Scope>
-export type ScopeOutput = zod.output<typeof Scope>
diff --git a/products/dashboards/frontend/generated/widget-configs.zod.ts b/products/dashboards/frontend/generated/widget-configs.zod.ts
index b7238001e0de..3d8fb067e083 100644
--- a/products/dashboards/frontend/generated/widget-configs.zod.ts
+++ b/products/dashboards/frontend/generated/widget-configs.zod.ts
@@ -11,7 +11,6 @@ import { ExperimentResultsWidgetConfig as ExperimentResultsWidgetConfigComponent
import { ExperimentsListWidgetConfig } from './widget-config-schemas/experimentsListWidgetConfig.zod'
import { LogsListWidgetConfig } from './widget-config-schemas/logsListWidgetConfig.zod'
import { MetricsTableWidgetConfig as MetricsTableWidgetConfigComponent } from './widget-config-schemas/metricsTableWidgetConfig.zod'
-import { MetricsWidgetConfig as MetricsWidgetConfigComponent } from './widget-config-schemas/metricsWidgetConfig.zod'
import { NotebookWidgetConfig as NotebookWidgetConfigComponent } from './widget-config-schemas/notebookWidgetConfig.zod'
import { SessionReplayListWidgetConfig } from './widget-config-schemas/sessionReplayListWidgetConfig.zod'
import { SurveyResultsWidgetConfig as SurveyResultsWidgetConfigComponent } from './widget-config-schemas/surveyResultsWidgetConfig.zod'
@@ -26,7 +25,6 @@ export const experimentResultsWidgetConfigSchema = /* @__PURE__ */ ExperimentRes
export const experimentsWidgetConfigSchema = /* @__PURE__ */ ExperimentsListWidgetConfig
export const logsWidgetConfigSchema = /* @__PURE__ */ LogsListWidgetConfig
export const metricsTableWidgetConfigSchema = /* @__PURE__ */ MetricsTableWidgetConfigComponent
-export const metricsWidgetConfigSchema = /* @__PURE__ */ MetricsWidgetConfigComponent
export const notebookWidgetConfigSchema = /* @__PURE__ */ NotebookWidgetConfigComponent
export const sessionReplayWidgetConfigSchema = /* @__PURE__ */ SessionReplayListWidgetConfig
export const surveyResultsWidgetConfigSchema = /* @__PURE__ */ SurveyResultsWidgetConfigComponent
@@ -40,7 +38,6 @@ export type ExperimentResultsWidgetConfig = zod.infer<typeof experimentResultsWi
export type ExperimentsWidgetConfig = zod.infer<typeof experimentsWidgetConfigSchema>
export type LogsWidgetConfig = zod.infer<typeof logsWidgetConfigSchema>
export type MetricsTableWidgetConfig = zod.infer<typeof metricsTableWidgetConfigSchema>
-export type MetricsWidgetConfig = zod.infer<typeof metricsWidgetConfigSchema>
export type NotebookWidgetConfig = zod.infer<typeof notebookWidgetConfigSchema>
export type SessionReplayWidgetConfig = zod.infer<typeof sessionReplayWidgetConfigSchema>
export type SurveyResultsWidgetConfig = zod.infer<typeof surveyResultsWidgetConfigSchema>
@@ -92,10 +89,6 @@ export const logsWidgetFormSchema = logsWidgetConfigSchema.pick({
timezone: true,
})
-export const metricsWidgetFormSchema = metricsWidgetConfigSchema.pick({
- query: true,
-})
-
export const metricsTableWidgetFormSchema = metricsTableWidgetConfigSchema.pick({
limit: true,
dateRange: true,
diff --git a/products/dashboards/frontend/generated/widget-form-fields.json b/products/dashboards/frontend/generated/widget-form-fields.json
index f7f146f44d2f..164fe83e2251 100644
--- a/products/dashboards/frontend/generated/widget-form-fields.json
+++ b/products/dashboards/frontend/generated/widget-form-fields.json
@@ -5,108 +5,77 @@
"configTypeExport": "ActivityEventsWidgetConfig",
"formSchemaExport": "activityEventsWidgetFormSchema",
"formFields": ["limit", "dateRange", "filterTestAccounts"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"canvas_app": {
"configSchemaExport": "canvasAppWidgetConfigSchema",
"configTypeExport": "CanvasAppWidgetConfig",
"formSchemaExport": "canvasAppWidgetFormSchema",
"formFields": ["canvasId"],
- "live": false,
- "creationFlag": "small-software-apps",
- "dashboardFilterKeys": []
+ "live": false
},
"conversations_recent_tickets": {
"configSchemaExport": "conversationsRecentTicketsWidgetConfigSchema",
"configTypeExport": "ConversationsRecentTicketsWidgetConfig",
"formSchemaExport": "conversationsRecentTicketsWidgetFormSchema",
"formFields": ["limit"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"error_tracking_list": {
"configSchemaExport": "errorTrackingWidgetConfigSchema",
"configTypeExport": "ErrorTrackingWidgetConfig",
"formSchemaExport": "errorTrackingWidgetFormSchema",
"formFields": ["limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts", "status"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"experiment_results": {
"configSchemaExport": "experimentResultsWidgetConfigSchema",
"configTypeExport": "ExperimentResultsWidgetConfig",
"formSchemaExport": "experimentResultsWidgetFormSchema",
"formFields": ["experimentId"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"experiments_list": {
"configSchemaExport": "experimentsWidgetConfigSchema",
"configTypeExport": "ExperimentsWidgetConfig",
"formSchemaExport": "experimentsWidgetFormSchema",
"formFields": ["limit", "orderBy", "orderDirection", "status", "createdBy"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"logs_list": {
"configSchemaExport": "logsWidgetConfigSchema",
"configTypeExport": "LogsWidgetConfig",
"formSchemaExport": "logsWidgetFormSchema",
"formFields": ["limit", "dateRange", "wrapLines", "timezone"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
- },
- "metrics": {
- "configSchemaExport": "metricsWidgetConfigSchema",
- "configTypeExport": "MetricsWidgetConfig",
- "formSchemaExport": "metricsWidgetFormSchema",
- "formFields": ["query"],
- "live": false,
- "creationFlag": "metrics",
- "dashboardFilterKeys": ["date_from", "date_to"]
+ "live": false
},
"metrics_table": {
"configSchemaExport": "metricsTableWidgetConfigSchema",
"configTypeExport": "MetricsTableWidgetConfig",
"formSchemaExport": "metricsTableWidgetFormSchema",
"formFields": ["limit", "dateRange"],
- "live": false,
- "creationFlag": "metrics",
- "dashboardFilterKeys": []
+ "live": false
},
"notebook_widget": {
"configSchemaExport": "notebookWidgetConfigSchema",
"configTypeExport": "NotebookWidgetConfig",
"formSchemaExport": "notebookWidgetFormSchema",
"formFields": [],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"session_replay_list": {
"configSchemaExport": "sessionReplayWidgetConfigSchema",
"configTypeExport": "SessionReplayWidgetConfig",
"formSchemaExport": "sessionReplayWidgetFormSchema",
"formFields": ["limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
},
"survey_results": {
"configSchemaExport": "surveyResultsWidgetConfigSchema",
"configTypeExport": "SurveyResultsWidgetConfig",
"formSchemaExport": "surveyResultsWidgetFormSchema",
"formFields": ["surveyId", "limit", "dateRange"],
- "live": false,
- "creationFlag": null,
- "dashboardFilterKeys": []
+ "live": false
}
}
}
diff --git a/products/dashboards/frontend/widget_types/catalog.ts b/products/dashboards/frontend/widget_types/catalog.ts
index 990f05c9f846..edf8e4ff0417 100644
--- a/products/dashboards/frontend/widget_types/catalog.ts
+++ b/products/dashboards/frontend/widget_types/catalog.ts
@@ -13,7 +13,6 @@ import {
} from '@posthog/icons'
import { FEATURE_FLAGS, type FeatureFlagKey } from 'lib/constants'
-import type { DashboardControl } from 'scenes/dashboard/dashboardControls'
import { urls } from 'scenes/urls'
import { ProductKey, QuickFilterContext } from '~/queries/schema/schema-general'
@@ -33,13 +32,7 @@ import {
} from '../generated/widget-configs.zod'
import type { DashboardWidgetProductAccess } from '../types'
import { isLiveDashboardWidgetType } from '../widgets/live/liveWidgetTypes'
-import {
- METRICS_WIDGET_PRESETS,
- metricsWidgetDashboardControls,
- metricsWidgetDefaultConfig,
-} from '../widgets/metrics/metricsWidgetConfig'
import type { WidgetAvailabilityConfig, WidgetAvailabilityRequirementId } from './widgetAvailability'
-import { getDashboardWidgetCreationFlag } from './widgetManifest'
export const DASHBOARD_WIDGET_HEADER_LAYOUTS = ['simple', 'dashboard_tile'] as const
@@ -195,22 +188,6 @@ export type DashboardWidgetCatalogEntry = {
availability?: WidgetAvailabilityConfig
/** Quick filter context + property allowlist for on-tile filter bars. */
tileFilters?: DashboardWidgetTileFiltersCatalogConfig
- /** A feature flag the picker also needs before it offers this type, on top of the backend `creation_flag`. */
- pickerFlag?: string
- /** Extra picker cards for this one widget type, each with its own label and default config. */
- pickerPresets?: readonly DashboardWidgetPickerPreset[]
- /** Open the widget settings right after the tile is added, when the default config shows nothing yet. */
- openEditorOnAdd?: boolean
- /** Dashboard filter controls that reach this widget (see `WidgetSpec.dashboard_filter_keys`). */
- dashboardControls?: (config: Record<string, unknown>) => DashboardControl[]
-}
-
-export type DashboardWidgetPickerPreset = {
- /** Unique within the widget type. Picker selection keys are `<widget type>:<preset id>`. */
- id: string
- label: string
- description: string
- defaultConfig: Record<string, unknown>
}
/** New widget types: add here. See products/dashboards/CONTRIBUTING.md. */
@@ -361,30 +338,6 @@ export const DASHBOARD_WIDGET_CATALOG = {
message: 'Log in to PostHog to explore the latest events from this dashboard.',
},
},
- metrics: {
- groupId: 'metrics',
- label: 'Metric',
- description: 'A service metric, charted the way you choose.',
- defaultConfig: metricsWidgetDefaultConfig('line'),
- defaultLayout: { w: 6, h: 5, minW: 3, minH: 3 },
- productAccess: 'metrics',
- titleHref: urls.metrics(),
- headerMeta: { showDateRange: false },
- // Metric widgets reach the same audience as the metrics insight builder.
- pickerFlag: FEATURE_FLAGS.METRICS_INSIGHT_BUILDER,
- pickerPresets: METRICS_WIDGET_PRESETS.map((preset) => ({
- id: preset.id,
- label: preset.label,
- description: preset.description,
- defaultConfig: metricsWidgetDefaultConfig(preset.display),
- })),
- openEditorOnAdd: true,
- dashboardControls: metricsWidgetDashboardControls,
- sharedPlaceholder: {
- title: 'Metric',
- message: 'Log in to PostHog to see this metric.',
- },
- },
logs_list: {
groupId: 'logs',
label: 'Recent logs',
@@ -487,43 +440,13 @@ export function getUnknownDashboardWidgetCatalogFallback(widgetType: string): Re
})
}
-/** One card in the Add widget picker: a widget type, or one of its picker presets. */
-export type DashboardWidgetPickerItem = {
- /** Selection key: the widget type, or `<widget type>:<preset id>` for a preset card. */
- key: string
- widgetType: DashboardWidgetCatalogKey
- presetId?: string
- entry: ResolvedDashboardWidgetCatalogEntry
- defaultConfig: Record<string, unknown>
- /** Feature flags the user needs before the picker offers this widget type (`WidgetSpec.creation_flag` and the
- * catalog `pickerFlag` and `featureFlag`). */
- requiredFlags: string[]
-}
-
export type DashboardWidgetCatalogGroup = {
groupId: string
groupLabel: string
- widgets: DashboardWidgetPickerItem[]
-}
-
-function getDashboardWidgetPickerItems(
- widgetType: DashboardWidgetCatalogKey,
- entry: ResolvedDashboardWidgetCatalogEntry
-): DashboardWidgetPickerItem[] {
- const requiredFlags = [getDashboardWidgetCreationFlag(widgetType), entry.pickerFlag, entry.featureFlag].filter(
- (flag): flag is string => !!flag
- )
- if (!entry.pickerPresets?.length) {
- return [{ key: widgetType, widgetType, entry, defaultConfig: entry.defaultConfig, requiredFlags }]
- }
- return entry.pickerPresets.map((preset) => ({
- key: `${widgetType}:${preset.id}`,
- widgetType,
- presetId: preset.id,
- entry: { ...entry, label: preset.label, description: preset.description },
- defaultConfig: preset.defaultConfig,
- requiredFlags,
- }))
+ widgets: Array<{
+ widgetType: DashboardWidgetCatalogKey
+ entry: ResolvedDashboardWidgetCatalogEntry
+ }>
}
function getDashboardWidgetCatalogGroups(): DashboardWidgetCatalogGroup[] {
@@ -544,23 +467,13 @@ function getDashboardWidgetCatalogGroups(): DashboardWidgetCatalogGroup[] {
groupsById.set(entry.groupId, group)
}
- group.widgets.push(
- ...getDashboardWidgetPickerItems(
- widgetType as DashboardWidgetCatalogKey,
- resolveDashboardWidgetCatalogEntry(widgetType, entry)
- )
- )
+ group.widgets.push({
+ widgetType: widgetType as DashboardWidgetCatalogKey,
+ entry: resolveDashboardWidgetCatalogEntry(widgetType, entry),
+ })
}
- const groupDisplayOrder = [
- 'session_replay',
- 'error_tracking',
- 'activity',
- 'logs',
- 'metrics',
- 'experiments',
- 'surveys',
- ]
+ const groupDisplayOrder = ['session_replay', 'error_tracking', 'activity', 'logs', 'experiments', 'surveys']
return [...groupsById.values()].sort((a, b) => {
const aIndex = groupDisplayOrder.indexOf(a.groupId)
@@ -570,21 +483,3 @@ function getDashboardWidgetCatalogGroups(): DashboardWidgetCatalogGroup[] {
}
export const DASHBOARD_WIDGET_CATALOG_GROUPS = getDashboardWidgetCatalogGroups()
-
-const DASHBOARD_WIDGET_PICKER_ITEMS_BY_KEY = new Map(
- DASHBOARD_WIDGET_CATALOG_GROUPS.flatMap((group) => group.widgets).map((item) => [item.key, item])
-)
-
-export function getDashboardWidgetPickerItem(key: string): DashboardWidgetPickerItem | undefined {
- return DASHBOARD_WIDGET_PICKER_ITEMS_BY_KEY.get(key)
-}
-
-/** Picker groups without the widget types whose required flags are off for this user. */
-export function getAvailableDashboardWidgetCatalogGroups(
- isFlagEnabled: (flag: string) => boolean
-): DashboardWidgetCatalogGroup[] {
- return DASHBOARD_WIDGET_CATALOG_GROUPS.map((group) => ({
- ...group,
- widgets: group.widgets.filter((item) => item.requiredFlags.every(isFlagEnabled)),
- })).filter((group) => group.widgets.length > 0)
-}
diff --git a/products/dashboards/frontend/widget_types/widgetManifest.ts b/products/dashboards/frontend/widget_types/widgetManifest.ts
deleted file mode 100644
index ccb46392b328..000000000000
--- a/products/dashboards/frontend/widget_types/widgetManifest.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import widgetFormFields from '../generated/widget-form-fields.json'
-
-const WIDGET_MANIFEST = widgetFormFields.widgets as Record<
- string,
- { creationFlag?: string | null; dashboardFilterKeys?: string[] }
->
-
-/** The feature flag a user needs to add this widget type, or null. SSOT is `WidgetSpec.creation_flag` on the
- * backend, flowed through `hogli build:widget-types`. */
-export function getDashboardWidgetCreationFlag(widgetType: string): string | null {
- return WIDGET_MANIFEST[widgetType]?.creationFlag ?? null
-}
-
-/** The dashboard filter keys this widget type follows, empty when it ignores dashboard filters. SSOT is
- * `WidgetSpec.dashboard_filter_keys` on the backend, flowed through `hogli build:widget-types`. */
-export function getDashboardWidgetFilterKeys(widgetType: string): readonly string[] {
- return WIDGET_MANIFEST[widgetType]?.dashboardFilterKeys ?? []
-}
diff --git a/products/dashboards/frontend/widgets/AddWidgetModal.test.tsx b/products/dashboards/frontend/widgets/AddWidgetModal.test.tsx
index 41965bd6ecc5..add3adb34a69 100644
--- a/products/dashboards/frontend/widgets/AddWidgetModal.test.tsx
+++ b/products/dashboards/frontend/widgets/AddWidgetModal.test.tsx
@@ -131,39 +131,6 @@ describe('AddWidgetModal', () => {
expect(topIssuesCard).toHaveAttribute('aria-checked', 'false')
})
- it('offers metric presets only with the metrics and insight builder flags, and adds the picked preset as a metrics widget', async () => {
- const onAdd = jest.fn().mockResolvedValue(undefined)
- renderAddWidgetModal({ onAdd })
- expect(screen.queryByLabelText('Single stat')).not.toBeInTheDocument()
- cleanup()
-
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS]: true })
- renderAddWidgetModal({ onAdd })
- expect(screen.queryByLabelText('Single stat')).not.toBeInTheDocument()
- cleanup()
-
- featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.METRICS]: true,
- [FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]: true,
- })
- renderAddWidgetModal({ onAdd })
- expect(['Time series', 'Single stat', 'Heatmap'].map((label) => !!screen.queryByLabelText(label))).toEqual([
- true,
- true,
- true,
- ])
-
- await userEvent.click(screen.getByLabelText('Single stat'))
- await userEvent.click(screen.getByTestId('add-widget-submit'))
-
- expect(onAdd).toHaveBeenCalledWith([
- {
- widgetType: 'metrics',
- config: { query: expect.objectContaining({ kind: 'MetricsQuery', display: { type: 'stat' } }) },
- },
- ])
- })
-
it('submits all selected widget types', async () => {
const onAdd = jest.fn().mockResolvedValue(undefined)
const onClose = jest.fn()
diff --git a/products/dashboards/frontend/widgets/AddWidgetModal.tsx b/products/dashboards/frontend/widgets/AddWidgetModal.tsx
index 801433fdb3e5..4cddeefaac72 100644
--- a/products/dashboards/frontend/widgets/AddWidgetModal.tsx
+++ b/products/dashboards/frontend/widgets/AddWidgetModal.tsx
@@ -17,8 +17,9 @@ import { teamLogic } from 'scenes/teamLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import {
- type DashboardWidgetPickerItem,
- getAvailableDashboardWidgetCatalogGroups,
+ DASHBOARD_WIDGET_CATALOG_GROUPS,
+ type ResolvedDashboardWidgetCatalogEntry,
+ type DashboardWidgetCatalogKey,
getDashboardWidgetGroupIcon,
getDashboardWidgetGroupProductIntro,
} from '../widget_types/catalog'
@@ -42,17 +43,22 @@ type AddWidgetModalProps = {
}
type AddWidgetCatalogPickerProps = {
- item: DashboardWidgetPickerItem
+ widgetType: DashboardWidgetCatalogKey
+ entry: ResolvedDashboardWidgetCatalogEntry
selected: boolean
- onToggleWidgetType: (key: string) => void
+ onToggleWidgetType: (widgetType: string) => void
}
-function AddWidgetCatalogPicker({ item, selected, onToggleWidgetType }: AddWidgetCatalogPickerProps): JSX.Element {
- const { entry } = item
- const WidgetPreview = DASHBOARD_WIDGET_PREVIEWS[item.widgetType]
+function AddWidgetCatalogPicker({
+ widgetType,
+ entry,
+ selected,
+ onToggleWidgetType,
+}: AddWidgetCatalogPickerProps): JSX.Element {
+ const WidgetPreview = DASHBOARD_WIDGET_PREVIEWS[widgetType]
function handleSelect(): void {
- onToggleWidgetType(item.key)
+ onToggleWidgetType(widgetType)
}
return (
@@ -62,7 +68,7 @@ function AddWidgetCatalogPicker({ item, selected, onToggleWidgetType }: AddWidge
description={entry.description}
selected={selected}
live={entry.live}
- preview={WidgetPreview ? <WidgetPreview presetId={item.presetId} /> : <div />}
+ preview={WidgetPreview ? <WidgetPreview /> : <div />}
onSelect={handleSelect}
/>
)
@@ -74,15 +80,15 @@ export function AddWidgetModal({ isOpen, onClose, loading, onAdd }: AddWidgetMod
useActions(dashboardLogic)
const { currentTeam } = useValues(teamLogic)
const { featureFlags } = useValues(featureFlagLogic)
- // Creation flags come from the backend widget manifest, so they are plain strings rather than flag keys.
- const catalogGroups = getAvailableDashboardWidgetCatalogGroups(
- (flag) => !!(featureFlags as Record<string, boolean | string | undefined>)[flag]
- )
+ const pickerGroups = DASHBOARD_WIDGET_CATALOG_GROUPS.map((group) => ({
+ ...group,
+ widgets: group.widgets.filter(({ entry }) => !entry.featureFlag || !!featureFlags[entry.featureFlag]),
+ })).filter((group) => group.widgets.length > 0)
const selectedTypes = new Set(addWidgetSelectedTypes)
const collapsedGroups = new Set(addWidgetCollapsedGroups)
const filteredGroups = new Set(addWidgetFilteredGroups)
const visibleGroups =
- filteredGroups.size > 0 ? catalogGroups.filter((group) => filteredGroups.has(group.groupId)) : catalogGroups
+ filteredGroups.size > 0 ? pickerGroups.filter((group) => filteredGroups.has(group.groupId)) : pickerGroups
const selectedCount = selectedTypes.size
@@ -112,7 +118,7 @@ export function AddWidgetModal({ isOpen, onClose, loading, onAdd }: AddWidgetMod
<>
<span>Bring context from your different PostHog products into one dashboard.</span>
<span className="mt-2 flex flex-wrap gap-2" data-attr="dashboard-widget-product-badges">
- {[...catalogGroups]
+ {[...pickerGroups]
.sort((a, b) => a.groupLabel.localeCompare(b.groupLabel))
.map((group) => {
const GroupIcon = getDashboardWidgetGroupIcon(group.groupId)
@@ -231,11 +237,12 @@ export function AddWidgetModal({ isOpen, onClose, loading, onAdd }: AddWidgetMod
) : null}
</div>
{!isCollapsed &&
- group.widgets.map((item) => (
+ group.widgets.map(({ widgetType, entry }) => (
<AddWidgetCatalogPicker
- key={item.key}
- item={item}
- selected={selectedTypes.has(item.key)}
+ key={widgetType}
+ widgetType={widgetType}
+ entry={entry}
+ selected={selectedTypes.has(widgetType)}
onToggleWidgetType={handleToggleWidgetType}
/>
))}
diff --git a/products/dashboards/frontend/widgets/addWidgetModalUtils.ts b/products/dashboards/frontend/widgets/addWidgetModalUtils.ts
index a43efad26359..62cd932ae007 100644
--- a/products/dashboards/frontend/widgets/addWidgetModalUtils.ts
+++ b/products/dashboards/frontend/widgets/addWidgetModalUtils.ts
@@ -1,4 +1,4 @@
-import { getDashboardWidgetPickerItem } from '../widget_types/catalog'
+import { DASHBOARD_WIDGET_CATALOG, type DashboardWidgetCatalogKey } from '../widget_types/catalog'
export type AddWidgetPayload = {
widgetType: string
@@ -22,16 +22,15 @@ export function getAddWidgetDisabledReason(loading: boolean | undefined, selecte
return undefined
}
-/** Builds one tile per selected picker key: a widget type, or `<widget type>:<preset id>` for a preset card. */
-export function buildAddWidgetPayloads(selectedKeys: Iterable<string>): AddWidgetPayload[] {
+export function buildAddWidgetPayloads(selectedTypes: Iterable<string>): AddWidgetPayload[] {
const payloads: AddWidgetPayload[] = []
- for (const key of selectedKeys) {
- const item = getDashboardWidgetPickerItem(key)
- if (!item) {
+ for (const widgetType of selectedTypes) {
+ const catalogEntry = DASHBOARD_WIDGET_CATALOG[widgetType as DashboardWidgetCatalogKey]
+ if (!catalogEntry || ('hideFromPicker' in catalogEntry && catalogEntry.hideFromPicker)) {
continue
}
- payloads.push({ widgetType: item.widgetType, config: item.defaultConfig })
+ payloads.push({ widgetType, config: catalogEntry.defaultConfig })
}
return payloads
diff --git a/products/dashboards/frontend/widgets/constants.ts b/products/dashboards/frontend/widgets/constants.ts
index 877530445acc..c6d0a92a9f34 100644
--- a/products/dashboards/frontend/widgets/constants.ts
+++ b/products/dashboards/frontend/widgets/constants.ts
@@ -19,16 +19,12 @@ const WIDGET_FETCH_ERROR_PASSTHROUGH_PREFIXES = [
'Unknown widget type:',
] as const
-/** `isUserFacing` comes from the run result's `error_is_user_facing`: the backend wrote the message for the viewer. */
-export function getDashboardWidgetFetchDisplayError(
- error: string | null | undefined,
- isUserFacing?: boolean | null
-): string | null {
+export function getDashboardWidgetFetchDisplayError(error: string | null | undefined): string | null {
if (!error) {
return null
}
- if (isUserFacing || WIDGET_FETCH_ERROR_PASSTHROUGH_PREFIXES.some((prefix) => error.startsWith(prefix))) {
+ if (WIDGET_FETCH_ERROR_PASSTHROUGH_PREFIXES.some((prefix) => error.startsWith(prefix))) {
return error
}
diff --git a/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.stories.tsx b/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.stories.tsx
deleted file mode 100644
index 75369fcc042b..000000000000
--- a/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.stories.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-
-import { mswDecorator } from '~/mocks/browser'
-
-import { widgetStorybookParameters } from '../../components/WidgetCard/widgetCardStoryFixtures'
-import type { DashboardWidgetEditModalProps } from '../registry'
-import { EditMetricsWidgetModal } from './EditMetricsWidgetModal'
-import { metricsWidgetDefaultConfig } from './metricsWidgetConfig'
-import { METRICS_WIDGET_SAMPLE_RESPONSE, metricsWidgetSampleQuery } from './metricsWidgetSampleData'
-
-const METRIC_NAMES = {
- results: [
- { name: 'http_server_requests', metric_type: 'sum' },
- { name: 'http_server_request_duration', metric_type: 'histogram' },
- { name: 'process_cpu_utilization', metric_type: 'gauge' },
- ],
-}
-
-const metricsApiMock = mswDecorator({
- get: {
- '/api/projects/:team_id/metrics/names/': () => [200, METRIC_NAMES],
- '/api/environments/:team_id/metrics/names/': () => [200, METRIC_NAMES],
- },
- post: {
- '/api/environments/:team_id/query/:kind/': () => [200, METRICS_WIDGET_SAMPLE_RESPONSE],
- '/api/projects/:team_id/query/:kind/': () => [200, METRICS_WIDGET_SAMPLE_RESPONSE],
- },
-})
-
-type EditMetricsWidgetModalStoryProps = Partial<DashboardWidgetEditModalProps>
-
-function EditMetricsWidgetModalStory({
- isOpen = true,
- onClose = () => undefined,
- onSave = () => Promise.resolve(),
- config = metricsWidgetDefaultConfig('line'),
- name = '',
- defaultTitle = 'Metric',
- description = '',
- ...props
-}: EditMetricsWidgetModalStoryProps): JSX.Element {
- return (
- <EditMetricsWidgetModal
- isOpen={isOpen}
- onClose={onClose}
- config={config}
- onSave={onSave}
- name={name}
- defaultTitle={defaultTitle}
- description={description}
- {...props}
- />
- )
-}
-
-// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.
-const meta: Meta<typeof EditMetricsWidgetModalStory> = {
- title: 'Products/Dashboards/Dashboard Widgets/Widget types/Metrics/Metric/Widget settings',
- component: EditMetricsWidgetModalStory,
- parameters: {
- layout: 'fullscreen',
- ...widgetStorybookParameters,
- featureFlags: [
- FEATURE_FLAGS.METRICS,
- FEATURE_FLAGS.METRICS_INSIGHT_BUILDER,
- FEATURE_FLAGS.METRICS_QUERY_LANGUAGES,
- ],
- },
- decorators: [metricsApiMock],
-}
-
-export default meta
-
-type Story = StoryObj<typeof EditMetricsWidgetModalStory>
-
-export const NewWidget: Story = {}
-
-export const WithMetric: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('time_series') },
- name: 'Requests by service',
- description: 'Request rate per service over the last hour.',
- },
-}
diff --git a/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.tsx b/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.tsx
deleted file mode 100644
index c88337b573a8..000000000000
--- a/products/dashboards/frontend/widgets/metrics/EditMetricsWidgetModal.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { LemonModal } from 'lib/lemon-ui/LemonModal'
-
-import { MetricsWidgetQueryEditor } from 'products/metrics/frontend/widgets/MetricsWidgetQueryEditor'
-
-import { getDashboardWidgetGroupLabel } from '../../widget_types/catalog'
-import { EditWidgetModalTileDetailsSection } from '../EditWidgetModalTileDetailsSection'
-import type { DashboardWidgetEditModalProps } from '../registry'
-import { editMetricsWidgetModalLogic } from './editMetricsWidgetModalLogic'
-import { metricsWidgetDefaultTitle } from './metricsWidgetConfig'
-
-function EditMetricsWidgetModalContents(): JSX.Element {
- const {
- tileName,
- tileDescription,
- query,
- saving,
- saveDisabledReason,
- fieldErrors,
- defaultTitle,
- hasUnsavedChanges,
- } = useValues(editMetricsWidgetModalLogic)
- const { setTileName, setTileDescription, setQuery, setHasUnrunQueryText, submit, requestClose } =
- useActions(editMetricsWidgetModalLogic)
- const languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')
-
- return (
- <LemonModal
- isOpen
- onClose={requestClose}
- hasUnsavedInput={hasUnsavedChanges}
- title="Metric widget"
- description={
- languagesEnabled
- ? 'Pick a metric, or write a PromQL or SQL query, and choose how to chart it.'
- : 'Pick a metric and choose how to chart it.'
- }
- width={1100}
- footer={
- <>
- <div className="flex-1" />
- <LemonButton type="secondary" onClick={requestClose} disabled={saving}>
- Cancel
- </LemonButton>
- <LemonButton
- type="primary"
- loading={saving}
- disabledReason={saveDisabledReason}
- onClick={() => submit()}
- data-attr="metrics-widget-save"
- >
- Save
- </LemonButton>
- </>
- }
- >
- <div className="flex flex-col gap-4">
- <section className="flex flex-col gap-3">
- <h5 className="text-sm font-semibold m-0">{getDashboardWidgetGroupLabel('metrics')}</h5>
- {fieldErrors.query ? <LemonBanner type="error">{fieldErrors.query}</LemonBanner> : null}
- <MetricsWidgetQueryEditor
- query={query}
- setQuery={setQuery}
- onUnrunTextChange={setHasUnrunQueryText}
- />
- <p className="text-xs text-secondary m-0">
- When the dashboard has a date range, the tile uses it instead of the range set here.
- </p>
- </section>
- <LemonDivider className="my-0" />
- <EditWidgetModalTileDetailsSection
- tileName={tileName}
- tileDescription={tileDescription}
- defaultTitle={metricsWidgetDefaultTitle({ query }) ?? defaultTitle}
- saving={saving}
- setTileName={setTileName}
- setTileDescription={setTileDescription}
- />
- </div>
- </LemonModal>
- )
-}
-
-export function EditMetricsWidgetModal({
- isOpen,
- onClose,
- config,
- onSave,
- name,
- defaultTitle,
- description,
-}: DashboardWidgetEditModalProps): JSX.Element | null {
- if (!isOpen) {
- return null
- }
-
- return (
- <BindLogic
- logic={editMetricsWidgetModalLogic}
- props={{ onClose, config, onSave, name, defaultTitle, description }}
- >
- <EditMetricsWidgetModalContents />
- </BindLogic>
- )
-}
diff --git a/products/dashboards/frontend/widgets/metrics/MetricsWidget.stories.tsx b/products/dashboards/frontend/widgets/metrics/MetricsWidget.stories.tsx
deleted file mode 100644
index 5c171ea882f0..000000000000
--- a/products/dashboards/frontend/widgets/metrics/MetricsWidget.stories.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-
-import { DashboardPlacement } from '~/types'
-
-import { WidgetCard } from '../../components/WidgetCard/WidgetCard'
-import { WidgetCardBody } from '../../components/WidgetCard/WidgetCardBody'
-import { WidgetCardHeader, widgetCardShouldHideMoreButton } from '../../components/WidgetCard/WidgetCardHeader'
-import {
- mockMoreOverlay,
- widgetStorybookParameters,
- widgetTileFrameDecorator,
-} from '../../components/WidgetCard/widgetCardStoryFixtures'
-import { getDashboardWidgetCatalogEntry, getDashboardWidgetGroupLabel } from '../../widget_types/catalog'
-import type { DashboardWidgetComponentProps } from '../registry'
-import { MetricsWidget } from './MetricsWidget'
-import { metricsWidgetDefaultConfig, metricsWidgetDefaultTitle } from './metricsWidgetConfig'
-import { metricsWidgetSampleQuery, metricsWidgetSampleResponse } from './metricsWidgetSampleData'
-
-const METRICS_CATALOG = getDashboardWidgetCatalogEntry('metrics')
-
-type MetricsWidgetTileStoryProps = DashboardWidgetComponentProps & {
- title?: string
-}
-
-function MetricsWidgetTileStory({ title = '', ...widgetProps }: MetricsWidgetTileStoryProps): JSX.Element {
- return (
- <WidgetCard className="h-full">
- <WidgetCardHeader
- layout={METRICS_CATALOG.headerLayout}
- title={title}
- defaultTitle={metricsWidgetDefaultTitle(widgetProps.config) ?? METRICS_CATALOG.label}
- titleHref={METRICS_CATALOG.titleHref}
- widgetTypeLabel={getDashboardWidgetGroupLabel(METRICS_CATALOG.groupId)}
- config={widgetProps.config}
- headerMeta={METRICS_CATALOG.headerMeta}
- loading={widgetProps.loading}
- shouldHideMoreButton={widgetCardShouldHideMoreButton(DashboardPlacement.Dashboard, false)}
- moreButtonOverlay={mockMoreOverlay}
- />
- <WidgetCardBody error={widgetProps.error} onRefresh={widgetProps.onRefresh}>
- <MetricsWidget {...widgetProps} />
- </WidgetCardBody>
- </WidgetCard>
- )
-}
-
-// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.
-const meta: Meta<typeof MetricsWidgetTileStory> = {
- title: 'Products/Dashboards/Dashboard Widgets/Widget types/Metrics/Metric',
- component: MetricsWidgetTileStory,
- parameters: {
- layout: 'padded',
- ...widgetStorybookParameters,
- featureFlags: [FEATURE_FLAGS.METRICS_INSIGHT_BUILDER],
- },
- decorators: [...widgetTileFrameDecorator],
- args: {
- tileId: 1,
- loading: false,
- onRefresh: () => undefined,
- onEdit: () => undefined,
- },
-}
-
-export default meta
-
-type Story = StoryObj<typeof MetricsWidgetTileStory>
-
-export const TimeSeries: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('time_series') },
- result: metricsWidgetSampleResponse('time_series'),
- },
-}
-
-export const SingleStat: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('stat') },
- result: metricsWidgetSampleResponse('stat'),
- },
-}
-
-export const Heatmap: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('heatmap') },
- result: metricsWidgetSampleResponse('heatmap'),
- },
-}
-
-export const NeedsConfiguration: Story = {
- args: {
- config: metricsWidgetDefaultConfig('stat'),
- result: { needsConfiguration: true },
- },
-}
-
-export const Loading: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('time_series') },
- result: null,
- loading: true,
- },
- parameters: {
- testOptions: { waitForLoadersToDisappear: false },
- },
-}
-
-export const Empty: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('time_series') },
- result: { results: [] },
- },
-}
-
-export const QueryError: Story = {
- args: {
- config: { query: metricsWidgetSampleQuery('heatmap') },
- result: null,
- error: 'A heatmap needs a histogram metric.',
- },
-}
diff --git a/products/dashboards/frontend/widgets/metrics/MetricsWidget.tsx b/products/dashboards/frontend/widgets/metrics/MetricsWidget.tsx
deleted file mode 100644
index 88f8980bb6f8..000000000000
--- a/products/dashboards/frontend/widgets/metrics/MetricsWidget.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
-
-import { MetricsWidgetChart } from 'products/metrics/frontend/widgets/MetricsWidgetChart'
-
-import { WidgetCardBodyMessage, WidgetCardContent, WidgetLoadingState } from '../../components/WidgetCard'
-import type { DashboardWidgetComponentProps } from '../registry'
-import { metricsWidgetNeedsConfiguration, metricsWidgetQuery } from './metricsWidgetConfig'
-
-function isRunResult(result: unknown): boolean {
- return typeof result === 'object' && result !== null && !('needsConfiguration' in result)
-}
-
-export function MetricsWidget({ config, result, onEdit }: DashboardWidgetComponentProps): JSX.Element {
- const builderEnabled = useFeatureFlag('METRICS_INSIGHT_BUILDER')
-
- // The config decides this state, so a tile saved a moment ago never shows the last run's result.
- if (metricsWidgetNeedsConfiguration(config)) {
- return (
- <WidgetCardBodyMessage>
- <div className="flex flex-col items-center gap-2">
- <span>Choose a metric to chart on this tile.</span>
- {onEdit && builderEnabled ? (
- <LemonButton type="primary" size="small" onClick={onEdit} data-attr="metrics-widget-configure">
- Choose a metric
- </LemonButton>
- ) : null}
- </div>
- </WidgetCardBodyMessage>
- )
- }
-
- // A saved query waits here for its first run: a fetch error replaces the body, so no other state applies.
- if (!isRunResult(result)) {
- return <WidgetLoadingState />
- }
-
- return (
- <WidgetCardContent className="flex flex-col overflow-hidden p-2">
- <MetricsWidgetChart query={metricsWidgetQuery(config)} response={result} />
- </WidgetCardContent>
- )
-}
diff --git a/products/dashboards/frontend/widgets/metrics/editMetricsWidgetModalLogic.ts b/products/dashboards/frontend/widgets/metrics/editMetricsWidgetModalLogic.ts
deleted file mode 100644
index 479b3e03a50c..000000000000
--- a/products/dashboards/frontend/widgets/metrics/editMetricsWidgetModalLogic.ts
+++ /dev/null
@@ -1,253 +0,0 @@
-import { MakeLogicType, actions, defaults, kea, listeners, path, props, reducers, selectors } from 'kea'
-import posthog from 'posthog-js'
-
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-import { objectsEqual } from 'lib/utils/objects'
-
-import { MetricsQuery, NodeKind } from '~/queries/schema/schema-general'
-
-import {
- isMetricsHeatmapQuery,
- metricsHeatmapIneligibleReason,
-} from 'products/metrics/frontend/widgets/metricsHeatmapQuery'
-
-import { isWidgetConfigValidationError } from '../../utils'
-import {
- buildWidgetTileMetadataPatch,
- getWidgetEditModalTileDefaults,
- widgetEditModalPropSelectors,
- widgetEditModalTileActions,
-} from '../editWidgetModalBuilders'
-import type { DashboardWidgetEditModalProps } from '../registry'
-import { metricsWidgetNeedsConfiguration, metricsWidgetQuery } from './metricsWidgetConfig'
-import type { MetricsWidgetFieldErrors } from './metricsWidgetConfigValidation'
-
-export type EditMetricsWidgetModalLogicProps = Omit<DashboardWidgetEditModalProps, 'isOpen'>
-
-// The editor pins each clause's OTel type once the metric list loads, which is no edit by the user.
-function withoutPinnedMetricTypes(query: MetricsQuery): MetricsQuery {
- return { ...query, clauses: query.clauses.map(({ metricType: _metricType, ...clause }) => clause) }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface editMetricsWidgetModalLogicValues {
- defaultTitle: string
- fieldErrors: MetricsWidgetFieldErrors
- hasUnrunQueryText: boolean
- hasUnsavedChanges: boolean
- onClose: () => void
- query: MetricsQuery
- saveDisabledReason: string | undefined
- saving: boolean
- tileDescription: string
- tileName: string
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface editMetricsWidgetModalLogicActions {
- requestClose: () => {
- value: true
- }
- setFieldErrors: (fieldErrors: MetricsWidgetFieldErrors) => {
- fieldErrors: Partial<Record<'query', string>>
- }
- setHasUnrunQueryText: (hasUnrunQueryText: boolean) => {
- hasUnrunQueryText: boolean
- }
- setQuery: (query: MetricsQuery) => {
- query: MetricsQuery
- }
- setTileDescription: (tileDescription: string) => {
- tileDescription: string
- }
- setTileName: (tileName: string) => {
- tileName: string
- }
- submit: () => {
- value: true
- }
- submitFailure: () => {
- value: true
- }
- submitSuccess: () => {
- value: true
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface editMetricsWidgetModalLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- hasUnsavedChanges: (
- query: MetricsQuery,
- hasUnrunQueryText: boolean,
- tileName: string,
- tileDescription: string,
- arg: any
- ) => boolean
- saveDisabledReason: (saving: boolean, query: MetricsQuery, hasUnrunQueryText: boolean) => string | undefined
- }
-}
-
-export type editMetricsWidgetModalLogicType = MakeLogicType<
- editMetricsWidgetModalLogicValues,
- editMetricsWidgetModalLogicActions,
- EditMetricsWidgetModalLogicProps,
- editMetricsWidgetModalLogicMeta
->
-
-export const editMetricsWidgetModalLogic = kea<editMetricsWidgetModalLogicType>([
- path(['products', 'dashboards', 'widgets', 'metrics', 'editMetricsWidgetModalLogic']),
-
- props({
- config: {},
- onSave: async () => {},
- onClose: () => {},
- name: '',
- defaultTitle: 'Untitled',
- description: '',
- } as EditMetricsWidgetModalLogicProps),
-
- actions({
- ...widgetEditModalTileActions,
- setQuery: (query: MetricsQuery) => ({ query }),
- setHasUnrunQueryText: (hasUnrunQueryText: boolean) => ({ hasUnrunQueryText }),
- setFieldErrors: (fieldErrors: MetricsWidgetFieldErrors) => ({ fieldErrors }),
- /** Escape, the close button and the overlay land here, so a dropdown's Escape can't drop an edited query. */
- requestClose: true,
- submit: true,
- submitSuccess: true,
- submitFailure: true,
- }),
-
- reducers({
- tileName: [
- '',
- {
- setTileName: (_: string, { tileName }: { tileName: string }) => tileName,
- },
- ],
- tileDescription: [
- '',
- {
- setTileDescription: (_: string, { tileDescription }: { tileDescription: string }) => tileDescription,
- },
- ],
- query: [
- { kind: NodeKind.MetricsQuery, clauses: [] } as MetricsQuery,
- {
- setQuery: (_: MetricsQuery, { query }: { query: MetricsQuery }) => query,
- },
- ],
- // PromQL or SQL typed into the editor but not run yet; it is not in `query` until it runs.
- hasUnrunQueryText: [
- false,
- {
- setHasUnrunQueryText: (_: boolean, { hasUnrunQueryText }: { hasUnrunQueryText: boolean }) =>
- hasUnrunQueryText,
- },
- ],
- fieldErrors: [
- {} as MetricsWidgetFieldErrors,
- {
- setFieldErrors: (
- _: MetricsWidgetFieldErrors,
- { fieldErrors }: { fieldErrors: MetricsWidgetFieldErrors }
- ) => fieldErrors,
- setQuery: () => ({}),
- },
- ],
- saving: [
- false,
- {
- submit: () => true,
- submitSuccess: () => false,
- submitFailure: () => false,
- },
- ],
- }),
-
- selectors({
- ...widgetEditModalPropSelectors,
- hasUnsavedChanges: [
- (s) => [s.query, s.hasUnrunQueryText, s.tileName, s.tileDescription, (_, props) => props],
- (
- query: MetricsQuery,
- hasUnrunQueryText: boolean,
- tileName: string,
- tileDescription: string,
- props: EditMetricsWidgetModalLogicProps
- ): boolean =>
- hasUnrunQueryText ||
- !objectsEqual(
- withoutPinnedMetricTypes(query),
- withoutPinnedMetricTypes(metricsWidgetQuery(props.config))
- ) ||
- tileName !== (props.name ?? '') ||
- tileDescription !== (props.description ?? ''),
- ],
- saveDisabledReason: [
- (s) => [s.saving, s.query, s.hasUnrunQueryText],
- (saving: boolean, query: MetricsQuery, hasUnrunQueryText: boolean): string | undefined => {
- if (saving) {
- return 'Saving…'
- }
- if (hasUnrunQueryText) {
- return 'Run the query to save it'
- }
- if (metricsWidgetNeedsConfiguration({ query })) {
- return query.language === 'promql' || query.language === 'sql'
- ? 'Write and run a query first'
- : 'Pick a metric first'
- }
- if (isMetricsHeatmapQuery(query)) {
- return metricsHeatmapIneligibleReason(query) ?? undefined
- }
- return undefined
- },
- ],
- }),
-
- defaults(({ props }) => ({
- ...getWidgetEditModalTileDefaults(props),
- query: metricsWidgetQuery(props.config),
- fieldErrors: {},
- saving: false,
- })),
-
- listeners(({ actions, props, values }) => ({
- requestClose: () => {
- if (!values.hasUnsavedChanges) {
- props.onClose()
- return
- }
- LemonDialog.open({
- title: 'Discard your changes?',
- description: 'The metric widget keeps its saved query.',
- primaryButton: { children: 'Discard changes', status: 'danger', onClick: () => props.onClose() },
- secondaryButton: { children: 'Keep editing' },
- })
- },
- submit: async () => {
- try {
- await props.onSave(
- { query: values.query },
- buildWidgetTileMetadataPatch(props, values.tileName, values.tileDescription)
- )
- posthog.capture('dashboard metrics widget saved', {
- display_type: values.query.display?.type ?? 'line',
- language: values.query.language ?? 'builder',
- })
- actions.setFieldErrors({})
- props.onClose()
- actions.submitSuccess()
- } catch (error) {
- actions.submitFailure()
- if (isWidgetConfigValidationError(error)) {
- actions.setFieldErrors(error.fieldErrors as MetricsWidgetFieldErrors)
- return
- }
- throw error
- }
- },
- })),
-])
diff --git a/products/dashboards/frontend/widgets/metrics/metricsWidgetConfig.ts b/products/dashboards/frontend/widgets/metrics/metricsWidgetConfig.ts
deleted file mode 100644
index 1b91f2771992..000000000000
--- a/products/dashboards/frontend/widgets/metrics/metricsWidgetConfig.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import type { DashboardControl } from 'scenes/dashboard/dashboardControls'
-
-import { MetricsDisplayType, MetricsQuery, NodeKind } from '~/queries/schema/schema-general'
-
-const METRICS_WIDGET_DEFAULT_DATE_FROM = '-1h'
-
-export type MetricsWidgetPresetId = 'time_series' | 'stat' | 'heatmap'
-
-export type MetricsWidgetPreset = {
- id: MetricsWidgetPresetId
- label: string
- description: string
- display: MetricsDisplayType
-}
-
-/** Picker cards for the one `metrics` widget type. A preset only picks the first chart type, which the editor can change. */
-export const METRICS_WIDGET_PRESETS: readonly MetricsWidgetPreset[] = [
- {
- id: 'time_series',
- label: 'Time series',
- description: 'A metric over time as a line, area or bar chart.',
- display: 'line',
- },
- {
- id: 'stat',
- label: 'Single stat',
- description: 'One big number, such as the latest value or the average.',
- display: 'stat',
- },
- {
- id: 'heatmap',
- label: 'Heatmap',
- description: 'How a histogram metric, such as latency, is spread over time.',
- display: 'heatmap',
- },
-]
-
-export function metricsWidgetDefaultConfig(display: MetricsDisplayType): Record<string, unknown> {
- const query: MetricsQuery = {
- kind: NodeKind.MetricsQuery,
- clauses: [],
- dateRange: { date_from: METRICS_WIDGET_DEFAULT_DATE_FROM },
- ...(display !== 'line' ? { display: { type: display } } : {}),
- }
- return { query }
-}
-
-export function metricsWidgetQuery(config: Record<string, unknown>): MetricsQuery {
- const query = config.query as Partial<MetricsQuery> | undefined
- if (query?.kind !== NodeKind.MetricsQuery) {
- return { kind: NodeKind.MetricsQuery, clauses: [] }
- }
- return { ...query, kind: NodeKind.MetricsQuery, clauses: query.clauses ?? [] }
-}
-
-/** Dashboard filters that reach a metric widget: the date range, in every query language. */
-export function metricsWidgetDashboardControls(): DashboardControl[] {
- return ['dateRange']
-}
-
-export function metricsWidgetDefaultTitle(config: Record<string, unknown>): string | undefined {
- const query = metricsWidgetQuery(config)
- if (query.language === 'promql') {
- return 'PromQL query'
- }
- if (query.language === 'sql') {
- return 'SQL query'
- }
- if (query.formula) {
- return query.formula
- }
- const metricNames = query.clauses.map((clause) => clause.metricName.trim()).filter(Boolean)
- return metricNames.length ? metricNames.join(', ') : undefined
-}
-
-export function metricsWidgetNeedsConfiguration(config: Record<string, unknown>): boolean {
- const query = metricsWidgetQuery(config)
- if (query.language === 'promql') {
- return !query.promql?.trim()
- }
- if (query.language === 'sql') {
- return !query.sql?.trim()
- }
- return !query.clauses.length || query.clauses.some((clause) => !clause.metricName.trim())
-}
diff --git a/products/dashboards/frontend/widgets/metrics/metricsWidgetConfigValidation.ts b/products/dashboards/frontend/widgets/metrics/metricsWidgetConfigValidation.ts
deleted file mode 100644
index 2597684724f1..000000000000
--- a/products/dashboards/frontend/widgets/metrics/metricsWidgetConfigValidation.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { ApiError } from 'lib/api-error'
-
-import { metricsWidgetConfigSchema } from '../../generated/widget-configs.zod'
-import { fieldErrorsFromZodError } from '../widgetConfigValidation'
-
-export type MetricsWidgetFieldErrors = Partial<Record<'query', string>>
-
-export function parseMetricsWidgetConfigApiError(
- error: unknown,
- config: Record<string, unknown>
-): MetricsWidgetFieldErrors | null {
- if (!(error instanceof ApiError)) {
- return null
- }
-
- const parsedConfig = metricsWidgetConfigSchema.safeParse(config)
- if (parsedConfig.success) {
- return null
- }
-
- return fieldErrorsFromZodError(parsedConfig.error) as MetricsWidgetFieldErrors
-}
diff --git a/products/dashboards/frontend/widgets/metrics/metricsWidgetSampleData.ts b/products/dashboards/frontend/widgets/metrics/metricsWidgetSampleData.ts
deleted file mode 100644
index 35493b44bc69..000000000000
--- a/products/dashboards/frontend/widgets/metrics/metricsWidgetSampleData.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { MetricsHistogramQueryResponse, MetricsQuery, MetricsQueryResponse } from '~/queries/schema/schema-general'
-
-import type { MetricsWidgetPresetId } from './metricsWidgetConfig'
-import { METRICS_WIDGET_PRESETS, metricsWidgetDefaultConfig } from './metricsWidgetConfig'
-
-// Fixed sample data: previews and stories must render the same chart on every run.
-const SAMPLE_START = Date.UTC(2026, 0, 15, 9, 0)
-const SAMPLE_STEP_MS = 5 * 60 * 1000
-const SAMPLE_BUCKETS = 24
-
-const sampleTimes = Array.from({ length: SAMPLE_BUCKETS }, (_, index) =>
- new Date(SAMPLE_START + index * SAMPLE_STEP_MS).toISOString()
-)
-
-function sampleSeries(service: string, base: number, swing: number): MetricsQueryResponse['results'][number] {
- return {
- labels: { 'service.name': service },
- metricName: 'http_server_requests',
- unit: '{request}/s',
- points: sampleTimes.map((time, index) => ({
- time,
- value: Math.round(base + swing * Math.sin(index / 3) + (index % 4) * swing * 0.1),
- })),
- }
-}
-
-export const METRICS_WIDGET_SAMPLE_RESPONSE: MetricsQueryResponse = {
- results: [sampleSeries('checkout', 120, 30), sampleSeries('api-gateway', 260, 45), sampleSeries('search', 80, 20)],
-}
-
-const SAMPLE_BOUNDS = [5, 10, 25, 50, 100, 250, 500]
-
-export const METRICS_WIDGET_SAMPLE_HISTOGRAM_RESPONSE: MetricsHistogramQueryResponse = {
- results: null,
- times: sampleTimes,
- bounds: SAMPLE_BOUNDS,
- counts: SAMPLE_BOUNDS.map((_, row) =>
- sampleTimes.map((_, column) => Math.max(0, Math.round(40 * Math.exp(-((row - 3 - Math.sin(column / 4)) ** 2)))))
- ),
-}
-
-const METRICS_WIDGET_SAMPLE_TOTAL_RESPONSE: MetricsQueryResponse = {
- results: [{ ...sampleSeries('checkout', 460, 60), labels: {} }],
-}
-
-export function metricsWidgetSampleQuery(presetId: MetricsWidgetPresetId): MetricsQuery {
- const preset = METRICS_WIDGET_PRESETS.find((candidate) => candidate.id === presetId) ?? METRICS_WIDGET_PRESETS[0]
- const { query } = metricsWidgetDefaultConfig(preset.display) as { query: MetricsQuery }
- const clause =
- preset.id === 'heatmap'
- ? { name: 'a', metricName: 'http_server_request_duration', metricType: 'histogram' as const }
- : preset.id === 'stat'
- ? {
- name: 'a',
- metricName: 'http_server_requests',
- rangeFunction: 'rate' as const,
- aggregation: 'sum' as const,
- }
- : {
- name: 'a',
- metricName: 'http_server_requests',
- rangeFunction: 'rate' as const,
- aggregation: 'sum' as const,
- groupBy: [{ key: 'service.name' }],
- }
- return { ...query, clauses: [clause] }
-}
-
-export function metricsWidgetSampleResponse(
- presetId: MetricsWidgetPresetId
-): MetricsQueryResponse | MetricsHistogramQueryResponse {
- if (presetId === 'heatmap') {
- return METRICS_WIDGET_SAMPLE_HISTOGRAM_RESPONSE
- }
- return presetId === 'stat' ? METRICS_WIDGET_SAMPLE_TOTAL_RESPONSE : METRICS_WIDGET_SAMPLE_RESPONSE
-}
diff --git a/products/dashboards/frontend/widgets/previews/MetricsWidgetPreview.tsx b/products/dashboards/frontend/widgets/previews/MetricsWidgetPreview.tsx
deleted file mode 100644
index b2c8097cc63a..000000000000
--- a/products/dashboards/frontend/widgets/previews/MetricsWidgetPreview.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import { MetricsWidgetChart } from 'products/metrics/frontend/widgets/MetricsWidgetChart'
-
-import type { MetricsWidgetPresetId } from '../metrics/metricsWidgetConfig'
-import { metricsWidgetSampleQuery, metricsWidgetSampleResponse } from '../metrics/metricsWidgetSampleData'
-
-export function MetricsWidgetPreview({ presetId }: { presetId?: string }): JSX.Element {
- const preset = (presetId ?? 'time_series') as MetricsWidgetPresetId
- return (
- <div className="flex h-36 flex-col" translate="no">
- <MetricsWidgetChart
- query={metricsWidgetSampleQuery(preset)}
- response={metricsWidgetSampleResponse(preset)}
- />
- </div>
- )
-}
diff --git a/products/dashboards/frontend/widgets/previews/dashboardWidgetPreviews.ts b/products/dashboards/frontend/widgets/previews/dashboardWidgetPreviews.ts
index 4a256d7a0b98..e1a808ef5ff5 100644
--- a/products/dashboards/frontend/widgets/previews/dashboardWidgetPreviews.ts
+++ b/products/dashboards/frontend/widgets/previews/dashboardWidgetPreviews.ts
@@ -7,7 +7,6 @@ import { ErrorTrackingWidgetPreview } from './ErrorTrackingWidgetPreview'
import { ExperimentResultsWidgetPreview, ExperimentsListWidgetPreview } from './ExperimentsWidgetPreviews'
import { LogsWidgetPreview } from './LogsWidgetPreview'
import { MetricsTableWidgetPreview } from './MetricsTableWidgetPreview'
-import { MetricsWidgetPreview } from './MetricsWidgetPreview'
import { SessionReplayWidgetPreview } from './SessionReplayWidgetPreview'
import { SurveyResultsWidgetPreview } from './SurveysWidgetPreviews'
@@ -15,12 +14,8 @@ import { SurveyResultsWidgetPreview } from './SurveysWidgetPreviews'
// app shell, while the previews render product UI (recordings player, error tracking list, logs)
// that only the add-widget modal needs. Importing them from the catalog put ~1 MiB of product code
// on every logged-in page load.
-/** New widget types: add preview components here. See products/dashboards/CONTRIBUTING.md.
- * A type with picker presets gets the preset's id, so each preset card can preview its own chart. */
-export const DASHBOARD_WIDGET_PREVIEWS: Record<
- DashboardWidgetCatalogKey,
- (props: { presetId?: string }) => JSX.Element
-> = {
+/** New widget types: add preview components here. See products/dashboards/CONTRIBUTING.md. */
+export const DASHBOARD_WIDGET_PREVIEWS: Record<DashboardWidgetCatalogKey, () => JSX.Element> = {
notebook_widget: NotebookWidgetPreview,
conversations_recent_tickets: ConversationsWidgetPreview,
activity_events_list: ActivityEventsWidgetPreview,
@@ -31,5 +26,4 @@ export const DASHBOARD_WIDGET_PREVIEWS: Record<
survey_results: SurveyResultsWidgetPreview,
logs_list: LogsWidgetPreview,
metrics_table: MetricsTableWidgetPreview,
- metrics: MetricsWidgetPreview,
}
diff --git a/products/dashboards/frontend/widgets/registry.tsx b/products/dashboards/frontend/widgets/registry.tsx
index f5c8b62952f5..9eba1ea29739 100644
--- a/products/dashboards/frontend/widgets/registry.tsx
+++ b/products/dashboards/frontend/widgets/registry.tsx
@@ -27,8 +27,6 @@ import {
} from './experiments/experimentsWidgetConfigValidation'
import { parseLogsWidgetConfigApiError } from './logs/logsWidgetConfigValidation'
import { parseMetricsTableWidgetConfigApiError } from './metrics/metricsTableWidgetConfigValidation'
-import { metricsWidgetDefaultTitle } from './metrics/metricsWidgetConfig'
-import { parseMetricsWidgetConfigApiError } from './metrics/metricsWidgetConfigValidation'
import { parseSessionReplayWidgetConfigApiError } from './session_replay/sessionReplayWidgetConfigValidation'
import { parseSurveyResultsWidgetConfigApiError } from './surveys/surveysWidgetConfigValidation'
@@ -54,10 +52,6 @@ const EditNotebookWidgetModal = lazyWithRetry(() =>
default: m.EditNotebookWidgetModal,
}))
)
-const MetricsWidget = lazyWithRetry(() => import('./metrics/MetricsWidget').then((m) => ({ default: m.MetricsWidget })))
-const EditMetricsWidgetModal = lazyWithRetry(() =>
- import('./metrics/EditMetricsWidgetModal').then((m) => ({ default: m.EditMetricsWidgetModal }))
-)
const ConversationsWidget = lazyWithRetry(() =>
import('./conversations/ConversationsWidget').then((m) => ({ default: m.ConversationsWidget }))
)
@@ -210,8 +204,6 @@ export type DashboardWidgetDefinition = {
productAccess?: DashboardWidgetProductAccess
/** Maps dashboard PATCH API errors to edit-modal field errors for this widget type. */
parseConfigApiError: DashboardWidgetConfigApiErrorParser
- /** Card title when the tile has no name, derived from its config (e.g. the charted metric). */
- getDefaultTitle?: (config: Record<string, unknown>) => string | undefined
/** Fallback when catalog `availability` is unmet; defaults to `WidgetAvailabilitySetupPrompt`. */
unavailableContentFallback?: ComponentType<{ availability: WidgetAvailabilityConfig }>
}
@@ -237,8 +229,6 @@ export type DashboardWidgetComponentProps = {
canMutateConversationsTickets?: boolean
onUpdateConfig?: (config: Record<string, unknown>) => void | Promise<void>
onConfigPublished?: () => void
- /** Opens the widget settings; set only for viewers who can edit the tile. */
- onEdit?: () => void
}
export type DashboardWidgetMetadataPatch = {
@@ -332,13 +322,6 @@ export const DASHBOARD_WIDGET_REGISTRY = {
parseConfigApiError: parseMetricsTableWidgetConfigApiError,
productAccess: 'metrics',
},
- metrics: {
- Component: MetricsWidget,
- EditModal: EditMetricsWidgetModal,
- productAccess: 'metrics',
- parseConfigApiError: parseMetricsWidgetConfigApiError,
- getDefaultTitle: metricsWidgetDefaultTitle,
- },
} satisfies Record<DashboardWidgetCatalogKey, DashboardWidgetDefinition>
function isDashboardWidgetRegistryKey(widgetType: string): widgetType is DashboardWidgetCatalogKey {
diff --git a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
index 594dbfec7a28..6953649c3d8e 100644
--- a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
+++ b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
@@ -9,7 +9,6 @@ import {
experimentsWidgetConfigSchema,
logsWidgetConfigSchema,
metricsTableWidgetConfigSchema,
- metricsWidgetConfigSchema,
notebookWidgetConfigSchema,
sessionReplayWidgetConfigSchema,
surveyResultsWidgetConfigSchema,
@@ -26,7 +25,6 @@ const WIDGET_CONFIG_SCHEMAS = {
experiment_results: experimentResultsWidgetConfigSchema,
logs_list: logsWidgetConfigSchema,
metrics_table: metricsTableWidgetConfigSchema,
- metrics: metricsWidgetConfigSchema,
notebook_widget: notebookWidgetConfigSchema,
survey_results: surveyResultsWidgetConfigSchema,
} as const
@@ -41,7 +39,6 @@ type ZodDef = {
element?: SchemaNode
shape?: Record<string, SchemaNode>
entries?: Record<string, unknown>
- values?: readonly unknown[]
}
function zodDef(schema: SchemaNode): ZodDef | undefined {
@@ -86,20 +83,8 @@ function zodPropertyTree(schema: SchemaNode): unknown {
return { $enum: Object.keys(def.entries).sort() }
}
- if (def?.type === 'literal' && def.values) {
- return { $type: def.values.every((value) => typeof value === 'number') ? 'integer' : 'string' }
- }
-
if (def?.type === 'union' && def.options) {
const substantiveOptions = def.options.filter((option) => zodDef(unwrapZod(option))?.type !== 'null')
- // An integer enum (e.g. days of the week) is a union of literals, since a Zod enum holds strings only.
- const literalValues = substantiveOptions.flatMap((option) => zodDef(unwrapZod(option))?.values ?? [])
- if (
- literalValues.length > 1 &&
- substantiveOptions.every((option) => zodDef(unwrapZod(option))?.type === 'literal')
- ) {
- return { $enum: [...literalValues].sort() }
- }
if (substantiveOptions.length === 1) {
return zodPropertyTree(substantiveOptions[0]!)
}
@@ -150,11 +135,7 @@ function zodPropertyTree(schema: SchemaNode): unknown {
return { $type: 'unknown' }
}
-// The metrics config embeds a MetricsQuery, whose float fields (quantile, goal lines, axis bounds) OpenAPI types as
-// `number`. This helper reads every Zod number as `integer`, so only that config reads a `number` the same way.
-const WIDGETS_WITH_FLOAT_FIELDS: ReadonlySet<string> = new Set(['metrics'])
-
-function normalizePropertyTree(tree: unknown, readFloatsAsIntegers = false): unknown {
+function normalizePropertyTree(tree: unknown): unknown {
if (!tree || typeof tree !== 'object' || Array.isArray(tree)) {
return tree
}
@@ -168,13 +149,7 @@ function normalizePropertyTree(tree: unknown, readFloatsAsIntegers = false): unk
return { $type: 'integer' }
}
- if (readFloatsAsIntegers && '$type' in tree && tree.$type === 'number') {
- return { $type: 'integer' }
- }
-
- return Object.fromEntries(
- Object.entries(tree).map(([key, value]) => [key, normalizePropertyTree(value, readFloatsAsIntegers)])
- )
+ return Object.fromEntries(Object.entries(tree).map(([key, value]) => [key, normalizePropertyTree(value)]))
}
describe('widget config schema parity', () => {
@@ -188,10 +163,7 @@ describe('widget config schema parity', () => {
it('frontend zod schemas match nested OpenAPI property trees', () => {
for (const [widgetType, expectedTree] of Object.entries(configPropertyMetadata.configPropertyTrees)) {
const schema = WIDGET_CONFIG_SCHEMAS[widgetType as keyof typeof WIDGET_CONFIG_SCHEMAS]
- const readFloatsAsIntegers = WIDGETS_WITH_FLOAT_FIELDS.has(widgetType)
- expect(normalizePropertyTree(zodPropertyTree(schema))).toEqual(
- normalizePropertyTree(expectedTree, readFloatsAsIntegers)
- )
+ expect(normalizePropertyTree(zodPropertyTree(schema))).toEqual(normalizePropertyTree(expectedTree))
}
})
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 8bd2d7ed4de2..8980c551cd62 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -6525,7 +6525,6 @@ export namespace Schemas {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -6539,7 +6538,6 @@ export namespace Schemas {
| "experiment_results"
| "experiments_list"
| "logs_list"
- | "metrics"
| "metrics_table"
| "notebook_widget"
| "session_replay_list"
@@ -6722,105 +6720,6 @@ export namespace Schemas {
orderDirection: "ASC" | "DESC";
limit: number;
}>;
- export type MetricsAggregation =
- | "sum"
- | "avg"
- | "count"
- | "min"
- | "max"
- | "quantile"
- | "rate"
- | "increase"
- | "histogram_quantile";
- export type MetricsQueryGroupBy = {
- key: string;
- scope?: (MetricsAttributeScope | null) | undefined;
- };
- export type MetricsOtelType =
- | "gauge"
- | "sum"
- | "histogram"
- | "exponential_histogram"
- | "summary";
- export type MetricsRangeFunction = "rate" | "increase";
- export type MetricsQueryClause = {
- aggregation?: (MetricsAggregation | null) | undefined;
- filters?: (Array<MetricsQueryFilter> | null) | undefined;
- groupBy?: (Array<MetricsQueryGroupBy> | null) | undefined;
- metricName: string;
- metricType?: (MetricsOtelType | null) | undefined;
- /**
- * Alias a formula refers to (e.g. "a"); must be unique within the query
- */
- name: string;
- quantile?: (number | null) | undefined;
- rangeFunction?: (MetricsRangeFunction | null) | undefined;
- };
- export type MetricsReducer =
- | "last"
- | "mean"
- | "min"
- | "max"
- | "sum"
- | "delta";
- export type MetricsNullMode = "gap" | "zero" | "connect";
- export type MetricsStatSummary = "latest" | "average" | "total";
- export type MetricsThreshold = {
- /**
- * A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work.
- */
- color: string;
- /**
- * Lower bound of this band. The lowest step is the base color below every other step.
- */
- value: number;
- };
- export type MetricsDisplayType =
- | "line"
- | "area"
- | "bar"
- | "stat"
- | "gauge"
- | "bargauge"
- | "table"
- | "heatmap";
- export type MetricsAxisScale = "linear" | "log";
- export type MetricsYAxisSettings = Partial<{
- max: number | null;
- min: number | null;
- scale: MetricsAxisScale | null;
- startAtZero: boolean | null;
- }>;
- export type MetricsDisplaySettings = Partial<{
- goalLines: Array<GoalLine> | null;
- legendCalcs: Array<MetricsReducer> | null;
- nullMode: MetricsNullMode | null;
- reduce: MetricsReducer | null;
- statSummary: MetricsStatSummary | null;
- thresholds: Array<MetricsThreshold> | null;
- type: MetricsDisplayType | null;
- unit: string | null;
- yAxis: MetricsYAxisSettings | null;
- }>;
- export type MetricsQueryLanguage = "builder" | "promql" | "sql";
- /**
- * A `MetricsQuery` as a metrics widget stores it.
- *
- * Response, modifier and tag fields are runtime state, so a stored config can't carry them.
- */
- export type MetricsWidgetQuery = Partial<{
- clauses: Array<MetricsQueryClause>;
- dateRange: DateRange | null;
- display: MetricsDisplaySettings | null;
- formula: string | null;
- interval: string | null;
- kind: string;
- language: MetricsQueryLanguage | null;
- promql: string | null;
- sql: string | null;
- version: number | null;
- }>;
- export type MetricsWidgetConfig = Partial<{ query: MetricsWidgetQuery }>;
export type DashboardWidgetConfig =
| NotebookWidgetConfig
| ActivityEventsListWidgetConfig
@@ -6832,8 +6731,7 @@ export namespace Schemas {
| LogsListWidgetConfig
| ConversationsRecentTicketsWidgetConfig
| CanvasAppWidgetConfig
- | MetricsTableWidgetConfig
- | MetricsWidgetConfig;
+ | MetricsTableWidgetConfig;
export type DashboardPatchWidgetOpenApi = Partial<{
id: string;
widget_type: DashboardWidgetTypeEnum;
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 51c51b46f77d..cda08645418b 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -18,13 +18,7 @@ from django.db import connection
import structlog
-from posthog.schema import (
- DateRange,
- MetricsDashboardVariable,
- MetricsDashboardVariableSource,
- MetricsHistogramQuery,
- MetricsQuery,
-)
+from posthog.schema import DateRange, MetricsDashboardVariable, MetricsDashboardVariableSource
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
@@ -68,7 +62,6 @@ from products.metrics.backend.facade.enums import (
)
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
-from products.metrics.backend.heatmap import metrics_histogram_query_for as _metrics_histogram_query_for
from products.metrics.backend.investigation import investigate as _investigate
from products.metrics.backend.metric_attributes_query_runner import (
MetricAttributeKeysQueryRunner,
@@ -99,14 +92,6 @@ _RUNNER_AGGREGATIONS: dict[MetricAggregation, str] = {
}
-def metrics_histogram_query_for(query: MetricsQuery) -> MetricsHistogramQuery:
- """The histogram query that draws a metrics query with the heatmap display.
-
- Raises `MetricsHeatmapIneligibleError` when the query can't draw one.
- """
- return _metrics_histogram_query_for(query)
-
-
def team_has_metrics(team: Team) -> bool:
"""Return True if the given team has ingested at least one metric."""
return _team_has_metrics(team)
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 92de0ac18796..c311023d3cca 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -548,7 +548,3 @@ class SuggestedDashboardError(Exception):
class SuggestedDashboardNotFound(SuggestedDashboardError):
pass
-
-
-class MetricsHeatmapIneligibleError(ValueError):
- """A metrics query can't draw a heatmap. The message is safe to show."""
diff --git a/products/metrics/backend/heatmap.py b/products/metrics/backend/heatmap.py
deleted file mode 100644
index 7a36a1e770be..000000000000
--- a/products/metrics/backend/heatmap.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from posthog.schema import MetricsHistogramQuery, MetricsOtelType, MetricsQuery, MetricsQueryLanguage
-
-from products.metrics.backend.facade.contracts import MetricsHeatmapIneligibleError
-
-# A latency-over-time heatmap grids one distribution; gauges and counters have no per-bucket histogram.
-HISTOGRAM_METRIC_TYPES = frozenset(
- {MetricsOtelType.HISTOGRAM, MetricsOtelType.EXPONENTIAL_HISTOGRAM, MetricsOtelType.SUMMARY}
-)
-
-
-def metrics_histogram_query_for(query: MetricsQuery) -> MetricsHistogramQuery:
- """Build the heatmap's histogram query from a metrics query with the heatmap display.
-
- Mirrors `heatmapEligible` and `histogramQueryNode` in the frontend `metricsViewerLogic`, so a stored
- query renders the same grid the editor previewed. Raises `MetricsHeatmapIneligibleError` with a
- user-facing message when the query can't grid a distribution.
- """
- if query.language not in (None, MetricsQueryLanguage.BUILDER):
- raise MetricsHeatmapIneligibleError("A heatmap needs a builder query. PromQL and SQL can't draw one.")
- if len(query.clauses) != 1 or query.formula:
- raise MetricsHeatmapIneligibleError("A heatmap needs exactly one metric and no formula.")
- clause = query.clauses[0]
- if clause.groupBy:
- raise MetricsHeatmapIneligibleError("A heatmap can't group by attributes. Remove the group-by.")
- if clause.metricType not in HISTOGRAM_METRIC_TYPES:
- raise MetricsHeatmapIneligibleError("A heatmap needs a histogram metric.")
- return MetricsHistogramQuery(
- metricName=clause.metricName.strip(),
- metricType=clause.metricType,
- filters=clause.filters or None,
- dateRange=query.dateRange,
- interval=query.interval,
- variables=query.variables,
- )
diff --git a/products/metrics/backend/tests/test_metrics_dashboard_widget.py b/products/metrics/backend/tests/test_metrics_dashboard_widget.py
deleted file mode 100644
index 95c2d9c24c90..000000000000
--- a/products/metrics/backend/tests/test_metrics_dashboard_widget.py
+++ /dev/null
@@ -1,227 +0,0 @@
-import json
-import datetime as dt
-from typing import Any
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.api.snuffle_proxy import SNUFFLE_API_FEATURE_FLAG
-from posthog.api.test.dashboards import DashboardAPI
-from posthog.models import User
-from posthog.models.personal_api_key import PersonalAPIKey
-from posthog.models.utils import generate_random_token_personal, hash_key_value
-
-from products.metrics.backend.facade.testing import seed_metric
-
-GAUGE_QUERY: dict[str, Any] = {
- "kind": "MetricsQuery",
- "clauses": [{"name": "a", "metricName": "cpu_usage", "metricType": "gauge", "aggregation": "max"}],
- "dateRange": {"date_from": "-6h"},
-}
-
-HEATMAP_QUERY: dict[str, Any] = {
- "kind": "MetricsQuery",
- "clauses": [{"name": "a", "metricName": "request_duration", "metricType": "histogram"}],
- "dateRange": {"date_from": "-6h"},
- "display": {"type": "heatmap"},
-}
-
-
-class TestMetricsDashboardWidget(ClickhouseTestMixin, APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
- self.enabled_flags = {"metrics", SNUFFLE_API_FEATURE_FLAG}
- self.users_without_metrics: set[str] = set()
- flags_patcher = patch(
- "posthoganalytics.feature_enabled",
- side_effect=lambda flag, distinct_id, *args, **kwargs: (
- flag in self.enabled_flags and not (flag == "metrics" and distinct_id in self.users_without_metrics)
- ),
- )
- flags_patcher.start()
- self.addCleanup(flags_patcher.stop)
-
- now = dt.datetime.now(dt.UTC).replace(second=0, microsecond=0)
- # The value is the age in minutes, so a narrower window shows which points it kept.
- seed_metric(
- team_id=self.team.pk,
- metric_name="cpu_usage",
- points=[(now - dt.timedelta(minutes=age), float(age)) for age in (10, 30, 180)],
- )
- seed_metric(
- team_id=self.team.pk,
- metric_name="request_duration",
- metric_type="histogram",
- points=[(now - dt.timedelta(minutes=10), 6.0)],
- histogram_bounds=[10.0, 100.0],
- histogram_counts=[3, 2, 1],
- count=6,
- )
- self.dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "Service health"})
-
- def _add_tile(self, query: dict[str, Any] | None = None) -> int:
- config = {} if query is None else {"query": query}
- _, dashboard_json = self.dashboard_api.create_widget_tile(
- self.dashboard_id, widget_type="metrics", config=config
- )
- return dashboard_json["tiles"][-1]["id"]
-
- def _run(
- self,
- tile_id: int,
- filters_override: dict[str, Any] | None = None,
- refresh: bool = False,
- api_key: str | None = None,
- ) -> dict[str, Any]:
- params: dict[str, str] = {"tile_ids": str(tile_id)}
- if filters_override is not None:
- params["filters_override"] = json.dumps(filters_override)
- if refresh:
- params["refresh"] = "true"
- extra: dict[str, Any] = {"HTTP_AUTHORIZATION": f"Bearer {api_key}"} if api_key else {}
- response = self.client.get(
- f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}/run_widgets/", params, **extra
- )
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- return response.json()["results"][0]
-
- @staticmethod
- def _values(result: dict[str, Any]) -> list[float]:
- return sorted(
- point["value"]
- for series in result["result"]["results"]
- for point in series["points"]
- if point["value"] is not None
- )
-
- def test_runs_the_query_and_follows_the_dashboard_date_filter(self) -> None:
- tile_id = self._add_tile(GAUGE_QUERY)
-
- self.assertEqual(self._values(self._run(tile_id)), [10.0, 30.0, 180.0])
- self.assertEqual(self._values(self._run(tile_id, filters_override={"date_from": "-1h"})), [10.0, 30.0])
-
- def test_a_cleared_dashboard_date_range_restores_the_widget_range(self) -> None:
- tile_id = self._add_tile(GAUGE_QUERY)
- self.client.patch(
- f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}", {"filters": {"date_from": "-1h"}}
- )
-
- self.assertEqual(self._values(self._run(tile_id)), [10.0, 30.0])
- cleared: dict[str, Any] = {"date_from": None, "date_to": None}
- self.assertEqual(self._values(self._run(tile_id, filters_override=cleared)), [10.0, 30.0, 180.0])
-
- def test_a_manual_refresh_skips_the_query_cache(self) -> None:
- tile_id = self._add_tile(GAUGE_QUERY)
- self._run(tile_id)
- seed_metric(
- team_id=self.team.pk,
- metric_name="cpu_usage",
- points=[(dt.datetime.now(dt.UTC).replace(second=0, microsecond=0) - dt.timedelta(minutes=5), 5.0)],
- )
-
- self.assertNotIn(5.0, self._values(self._run(tile_id)))
- self.assertIn(5.0, self._values(self._run(tile_id, refresh=True)))
-
- def test_unconfigured_widget_asks_for_a_metric_without_running_a_query(self) -> None:
- tile_id = self._add_tile()
-
- result = self._run(tile_id)
-
- self.assertIsNone(result["error"])
- self.assertEqual(result["result"], {"needsConfiguration": True})
-
- def test_heatmap_display_runs_the_histogram_query(self) -> None:
- tile_id = self._add_tile(HEATMAP_QUERY)
-
- result = self._run(tile_id)
-
- self.assertIsNone(result["error"])
- self.assertEqual(result["result"]["bounds"][:2], [10.0, 100.0])
- self.assertTrue(result["result"]["times"])
-
- @parameterized.expand(
- [
- ("promql", {"clauses": [], "language": "promql", "promql": "up"}, "A heatmap needs a builder query"),
- (
- "gauge metric",
- {"clauses": [{"name": "a", "metricName": "cpu_usage", "metricType": "gauge"}]},
- "A heatmap needs a histogram metric.",
- ),
- ]
- )
- def test_heatmap_display_explains_an_ineligible_query(
- self, _name: str, query_patch: dict[str, Any], expected_error: str
- ) -> None:
- tile_id = self._add_tile({**HEATMAP_QUERY, **query_patch})
-
- result = self._run(tile_id)
-
- self.assertIsNone(result["result"])
- self.assertTrue(result["error"].startswith(expected_error), result["error"])
- self.assertTrue(result["error_is_user_facing"])
-
- def test_checks_metrics_access_for_the_viewer_not_the_widget_creator(self) -> None:
- tile_id = self._add_tile(GAUGE_QUERY)
- viewer = User.objects.create_and_join(self.organization, "[email protected]", "password")
- self.users_without_metrics.add(str(viewer.distinct_id))
-
- self.client.force_login(viewer)
- result = self._run(tile_id)
-
- self.assertIsNone(result["result"])
- self.assertEqual(result["error"], "You do not have access to metrics.")
-
- def test_a_promql_widget_needs_the_promql_flag(self) -> None:
- tile_id = self._add_tile({"kind": "MetricsQuery", "clauses": [], "language": "promql", "promql": "up"})
- self.enabled_flags.discard(SNUFFLE_API_FEATURE_FLAG)
-
- result = self._run(tile_id)
-
- self.assertIsNone(result["result"])
- self.assertEqual(result["error"], "You do not have access to metrics.")
-
- @parameterized.expand([("a signed-in viewer", False), ("a personal API key", True)])
- def test_every_request_counts_against_a_widget_throttle(self, _name: str, use_api_key: bool) -> None:
- tile_id = self._add_tile(GAUGE_QUERY)
- token: str | None = None
- if use_api_key:
- token = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="metrics widgets",
- user=self.user,
- secure_value=hash_key_value(token),
- scopes=["dashboard:read", "metrics:read"],
- scoped_teams=[],
- scoped_organizations=[],
- )
-
- with (
- patch(
- "products.dashboards.backend.api.dashboard.get_dashboard_widget_query_throttle_error",
- return_value="Rate limit exceeded. Try again later.",
- ) as shared_throttle,
- patch(
- "products.dashboards.backend.api.dashboard.get_dashboard_chart_widget_session_throttle_error",
- return_value="Rate limit exceeded. Try again later.",
- ) as per_viewer_throttle,
- ):
- result = self._run(tile_id, api_key=token)
-
- # A session run uses the per-viewer chart budget, not the team quota every other widget shares.
- self.assertEqual(shared_throttle.called, use_api_key)
- self.assertEqual(per_viewer_throttle.called, not use_api_key)
- self.assertEqual(result["error"], "Rate limit exceeded. Try again later.")
-
- def test_cannot_add_a_metrics_widget_without_the_metrics_flag(self) -> None:
- self.enabled_flags.discard("metrics")
-
- self.dashboard_api.create_widget_tile(
- self.dashboard_id,
- widget_type="metrics",
- config={"query": GAUGE_QUERY},
- expected_status=status.HTTP_400_BAD_REQUEST,
- )
diff --git a/products/metrics/frontend/components/MetricsQueryControls.tsx b/products/metrics/frontend/components/MetricsQueryControls.tsx
index dcd3bc4dd6cc..5c32436b6f5e 100644
--- a/products/metrics/frontend/components/MetricsQueryControls.tsx
+++ b/products/metrics/frontend/components/MetricsQueryControls.tsx
@@ -133,7 +133,7 @@ function MetricsQueryTextEditor({
export interface MetricsQueryControlsProps {
/** Prefix of the `data-attr` of each control, so each surface keeps its own analytics names. */
- dataAttrPrefix: 'metrics-viewer' | 'metrics-query-editor' | 'metrics-widget-editor'
+ dataAttrPrefix: 'metrics-viewer' | 'metrics-query-editor'
/** The query a language switch converts while the builder has no metric yet. */
fallbackQuery?: MetricsQuery
/** Shows the builder / PromQL / SQL switch. Gets the query as it is now, including an unrun draft. */
@@ -144,8 +144,6 @@ export interface MetricsQueryControlsProps {
resultIsGrouped?: boolean
/** Offers the heatmap display, which saves a histogram query instead of a time series. */
heatmap?: { eligible: boolean }
- /** Offers the stat, gauge, bar gauge and table panels without the panels flag, as metric widgets need them. */
- allPanels?: boolean
/** Controls after the date range and interval. */
toolbarExtras?: ReactNode
/** Controls after the display settings. */
@@ -162,7 +160,6 @@ export function MetricsQueryControls({
onRerun,
resultIsGrouped: resultIsGroupedProp,
heatmap,
- allPanels,
toolbarExtras,
displayExtras,
actions,
@@ -173,7 +170,7 @@ export function MetricsQueryControls({
const { addClause, setDateFrom, setDateTo, setInterval, setDisplayType, runQueryText } =
useActions(metricsViewerLogic)
const logic = useMountedLogic(metricsViewerLogic)
- const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS') || !!allPanels
+ const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS')
const disabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics, AccessControlLevel.Viewer)
// A changed query runs through the query node. An unchanged one (after a failure) runs again in place.
diff --git a/products/metrics/frontend/components/MetricsQueryEditor.tsx b/products/metrics/frontend/components/MetricsQueryEditor.tsx
index 89cb21c5406e..f0f9fcb374dc 100644
--- a/products/metrics/frontend/components/MetricsQueryEditor.tsx
+++ b/products/metrics/frontend/components/MetricsQueryEditor.tsx
@@ -5,20 +5,16 @@ import { objectsEqual } from 'lib/utils/objects'
import type { MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'
-import type { MetricsQueryControlsProps } from './MetricsQueryControls'
-import { MetricsQueryEditorControls } from './MetricsQueryEditorControls'
+import { MetricsQueryControls } from './MetricsQueryControls'
import { metricsViewerLogic } from './metricsViewerLogic'
-/** The `/metrics` viewer's builder, editing a `MetricsQuery` in the insight editor or a metric widget. */
+/** The `/metrics` viewer's builder, editing a `MetricsQuery` in the insight editor. */
export function MetricsQueryEditor({
editorKey,
query,
setQuery,
onSwitchLanguage,
onRerun,
- dataAttrPrefix = 'metrics-query-editor',
- allPanels,
- onUnrunTextChange,
}: {
editorKey: string
query: MetricsQuery
@@ -27,11 +23,6 @@ export function MetricsQueryEditor({
onSwitchLanguage?: (current: MetricsQuery, to: MetricsQueryLanguage) => void
/** Runs the current PromQL or SQL query again when Run is pressed without a change, as after a failure. */
onRerun?: () => void
- dataAttrPrefix?: MetricsQueryControlsProps['dataAttrPrefix']
- /** Offers every panel, the heatmap included, whatever the panels flag says. */
- allPanels?: boolean
- /** Gets whether the PromQL or SQL editor holds text that has not run yet, so it is not in `query`. */
- onUnrunTextChange?: (unrun: boolean) => void
}): JSX.Element {
// The query seeds the logic once. After that the builder only writes the query, so the two cannot loop.
const logicProps = useMemo(() => ({ key: editorKey, initialQuery: query }), [editorKey]) // eslint-disable-line react-hooks/exhaustive-deps
@@ -39,24 +30,16 @@ export function MetricsQueryEditor({
return (
<BindLogic logic={metricsViewerLogic} props={logicProps}>
<MetricsQuerySync query={query} setQuery={setQuery} />
- {onUnrunTextChange ? <MetricsQueryUnrunTextReporter onChange={onUnrunTextChange} /> : null}
- <MetricsQueryEditorControls
- dataAttrPrefix={dataAttrPrefix}
+ <MetricsQueryControls
+ dataAttrPrefix="metrics-query-editor"
fallbackQuery={query}
onSwitchLanguage={onSwitchLanguage}
onRerun={onRerun}
- allPanels={allPanels}
/>
</BindLogic>
)
}
-function MetricsQueryUnrunTextReporter({ onChange }: { onChange: (unrun: boolean) => void }): null {
- const { queryTextChanged } = useValues(metricsViewerLogic)
- useEffect(() => onChange(queryTextChanged), [queryTextChanged]) // eslint-disable-line react-hooks/exhaustive-deps
- return null
-}
-
/** Writes the builder's query back to the insight as it changes. */
function MetricsQuerySync({ query, setQuery }: { query: MetricsQuery; setQuery: (query: MetricsQuery) => void }): null {
const { metricsQueryNode } = useValues(metricsViewerLogic)
@@ -73,23 +56,13 @@ function MetricsQuerySync({ query, setQuery }: { query: MetricsQuery; setQuery:
const {
formula: _formula,
interval: _interval,
- display: storedDisplay,
+ display: _display,
language: _language,
promql: _promql,
sql: _sql,
...rest
} = query
- // The same goes for display settings: thresholds or a unit from an import or the API survive an edit.
- const {
- type: _type,
- goalLines: _goalLines,
- yAxis: _yAxis,
- reduce: _reduce,
- statSummary: _statSummary,
- ...displayNotOwnedByBuilder
- } = storedDisplay ?? {}
- const display = { ...displayNotOwnedByBuilder, ...metricsQueryNode.display }
- setQuery({ ...rest, ...metricsQueryNode, ...(Object.keys(display).length ? { display } : {}) })
+ setQuery({ ...rest, ...metricsQueryNode })
}, [metricsQueryNode]) // eslint-disable-line react-hooks/exhaustive-deps
return null
}
diff --git a/products/metrics/frontend/components/MetricsQueryEditorControls.tsx b/products/metrics/frontend/components/MetricsQueryEditorControls.tsx
deleted file mode 100644
index e18a8dac350c..000000000000
--- a/products/metrics/frontend/components/MetricsQueryEditorControls.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { useValues } from 'kea'
-
-import { MetricsQueryControls, type MetricsQueryControlsProps } from './MetricsQueryControls'
-import { metricsViewerLogic } from './metricsViewerLogic'
-
-/** The editor's controls. With `allPanels`, also offers the heatmap while the query can draw one. */
-export function MetricsQueryEditorControls({
- allPanels,
- ...props
-}: Pick<
- MetricsQueryControlsProps,
- 'dataAttrPrefix' | 'fallbackQuery' | 'onSwitchLanguage' | 'onRerun' | 'allPanels'
->): JSX.Element {
- const { heatmapEligible } = useValues(metricsViewerLogic)
- return (
- <MetricsQueryControls
- {...props}
- allPanels={allPanels}
- heatmap={allPanels ? { eligible: heatmapEligible } : undefined}
- />
- )
-}
diff --git a/products/metrics/frontend/components/MetricsQueryEditorSection.tsx b/products/metrics/frontend/components/MetricsQueryEditorSection.tsx
deleted file mode 100644
index 67e70a8c99c4..000000000000
--- a/products/metrics/frontend/components/MetricsQueryEditorSection.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useState } from 'react'
-
-import { LemonBanner } from '@posthog/lemon-ui'
-
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-
-import { MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'
-
-import { queryLanguage } from '../queryLanguages/convert'
-import { MetricsQueryEditor } from './MetricsQueryEditor'
-import { MetricsQueryLanguagePicker } from './MetricsQueryLanguagePicker'
-import { switchMetricsQueryLanguage } from './metricsQueryLanguageSwitch'
-import { isBuilderCompatibleQuery } from './metricsViewerLogic'
-
-let uniqueEditor = 0
-
-// Only a builder query can draw a heatmap, so a switch to PromQL or SQL falls back to the default chart.
-function withoutHeatmapDisplay(query: MetricsQuery): MetricsQuery {
- if (query.display?.type !== 'heatmap') {
- return query
- }
- const { type: _type, ...display } = query.display
- return { ...query, display }
-}
-
-/** The query editor of a saved metrics query: the builder / PromQL / SQL switch and the matching editor. */
-export function MetricsQueryEditorSection({
- query,
- setQuery,
- onRerun,
- onUnrunTextChange,
- surface,
-}: {
- query: MetricsQuery
- setQuery: (query: MetricsQuery) => void
- /** Runs the current PromQL or SQL query again when Run is pressed without a change, as after a failure. */
- onRerun?: () => void
- onUnrunTextChange?: (unrun: boolean) => void
- /** A widget offers every panel and the heatmap; an insight keeps the panels flag. */
- surface: 'insight' | 'widget'
-}): JSX.Element {
- const languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')
- // A language switch replaces the query, so the editor remounts to seed its logic from the new one.
- const [editorKey, setEditorKey] = useState(() => `MetricsQueryEditor.${uniqueEditor++}`)
-
- const onSwitchLanguage = languagesEnabled
- ? (current: MetricsQuery, to: MetricsQueryLanguage): void =>
- switchMetricsQueryLanguage(current, to, (converted) => {
- setQuery(to === 'builder' ? converted : withoutHeatmapDisplay(converted))
- // The converted query replaces the unrun text, and a builder-incompatible result shows no editor.
- onUnrunTextChange?.(false)
- setEditorKey(`MetricsQueryEditor.${uniqueEditor++}`)
- })
- : undefined
- const language = queryLanguage(query)
-
- if (language !== 'builder' && !languagesEnabled) {
- return (
- <LemonBanner type="info" className="w-full">
- {`This ${surface} uses a ${language === 'promql' ? 'PromQL' : 'SQL'} query, which you can't edit here.`}
- </LemonBanner>
- )
- }
-
- if (language !== 'builder' || isBuilderCompatibleQuery(query)) {
- return (
- <MetricsQueryEditor
- key={editorKey}
- editorKey={editorKey}
- query={query}
- setQuery={setQuery}
- onSwitchLanguage={onSwitchLanguage}
- onRerun={onRerun}
- onUnrunTextChange={onUnrunTextChange}
- dataAttrPrefix={surface === 'widget' ? 'metrics-widget-editor' : 'metrics-query-editor'}
- allPanels={surface === 'widget'}
- />
- )
- }
-
- return (
- <div className="flex flex-col items-start gap-2">
- {onSwitchLanguage && (
- <MetricsQueryLanguagePicker value="builder" onChange={(to) => onSwitchLanguage(query, to)} />
- )}
- <LemonBanner type="info" className="w-full">
- {onSwitchLanguage
- ? 'The builder cannot show this query. Switch to PromQL or SQL to edit it.'
- : `This ${surface} uses settings that the builder cannot show, so the builder is off for this ${surface}.`}
- </LemonBanner>
- </div>
- )
-}
diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
index a571627d2859..80a93b2a5471 100644
--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx
+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
@@ -6,17 +6,22 @@ import { LemonBanner, SpinnerOverlay } from '@posthog/lemon-ui'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { cn } from 'lib/utils/css-classes'
+import { truncate } from 'lib/utils/strings'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { AnyResponseType, MetricsQuery, MetricsQueryLanguage } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
-import { MetricsQueryEditorSection } from '../components/MetricsQueryEditorSection'
+import { MetricsQueryEditor } from '../components/MetricsQueryEditor'
+import { MetricsQueryLanguagePicker } from '../components/MetricsQueryLanguagePicker'
+import { switchMetricsQueryLanguage } from '../components/metricsQueryLanguageSwitch'
+import { isBuilderCompatibleQuery } from '../components/metricsViewerLogic'
import { MetricsPanel } from '../panels/MetricsPanel'
import { metricsQueryText, queryLanguage } from '../queryLanguages/convert'
-import { metricsQueryFallbackName, seriesFromMetricsResponse } from './metricsResponseSeries'
+import { seriesFromMetricsResponse } from './metricsResponseSeries'
let uniqueNode = 0
+let uniqueEditor = 0
interface MetricsQueryNodeProps {
query: MetricsQuery
@@ -28,21 +33,22 @@ interface MetricsQueryNodeProps {
/** With `setQuery`, shows the builder above the chart, as the insight editor does. */
editMode?: boolean
setQuery?: (query: MetricsQuery) => void
- /** Key of the data node that loads the results, so a caller can force it to run again. */
- dataKey?: string
}
/** Renders a `MetricsQuery` wherever the generic `Query` component is used —
* saved insights, dashboard tiles, notebooks. */
const EMPTY_QUERY_MESSAGE: Record<MetricsQueryLanguage, string> = {
- builder: 'Pick a metric to see its chart.',
+ builder: 'Pick a metric to see its time series.',
promql: 'Run a query to see results.',
sql: 'Run a query to see results.',
}
export function MetricsQueryNode(props: MetricsQueryNodeProps): JSX.Element | null {
const builderEnabled = useFeatureFlag('METRICS_INSIGHT_BUILDER')
- const [dataKey] = useState(() => props.dataKey ?? `MetricsQueryNode.${uniqueNode++}`)
+ const languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')
+ // A language switch replaces the query, so the editor remounts to seed its logic from the new one.
+ const [editorKey, setEditorKey] = useState(() => `MetricsQueryEditor.${uniqueEditor++}`)
+ const [dataKey] = useState(() => `MetricsQueryNode.${uniqueNode++}`)
const language = queryLanguage(props.query)
// A new insight starts with no clauses, which the backend rejects, so there is nothing to run yet.
@@ -60,14 +66,41 @@ export function MetricsQueryNode(props: MetricsQueryNodeProps): JSX.Element | nu
return results
}
+ const setQuery = props.setQuery
+ const onSwitchLanguage = languagesEnabled
+ ? (current: MetricsQuery, to: MetricsQueryLanguage): void =>
+ switchMetricsQueryLanguage(current, to, (converted) => {
+ setQuery(converted)
+ setEditorKey(`MetricsQueryEditor.${uniqueEditor++}`)
+ })
+ : undefined
+
return (
<div className="flex flex-col gap-3 w-full">
- <MetricsQueryEditorSection
- query={props.query}
- setQuery={props.setQuery}
- onRerun={() => dataNodeLogic.findMounted({ key: dataKey })?.actions.loadData('force_blocking')}
- surface="insight"
- />
+ {language !== 'builder' || isBuilderCompatibleQuery(props.query) ? (
+ <MetricsQueryEditor
+ key={editorKey}
+ editorKey={editorKey}
+ query={props.query}
+ setQuery={setQuery}
+ onSwitchLanguage={onSwitchLanguage}
+ onRerun={() => dataNodeLogic.findMounted({ key: dataKey })?.actions.loadData('force_blocking')}
+ />
+ ) : (
+ <div className="flex flex-col items-start gap-2">
+ {onSwitchLanguage && (
+ <MetricsQueryLanguagePicker
+ value="builder"
+ onChange={(to) => onSwitchLanguage(props.query, to)}
+ />
+ )}
+ <LemonBanner type="info" className="w-full">
+ {onSwitchLanguage
+ ? 'The builder cannot show this query. Switch to PromQL or SQL to edit it.'
+ : 'This insight uses settings that the builder cannot show, so the builder is off for this insight.'}
+ </LemonBanner>
+ </div>
+ )}
<div className="relative flex h-[360px] border rounded p-3">{results}</div>
</div>
)
@@ -98,7 +131,12 @@ function MetricsQueryResults({ dataKey: key, ...props }: MetricsQueryNodeProps &
const { response, responseLoading, responseError } = useValues(logic)
const series = seriesFromMetricsResponse(response)
const hasPoints = series.some((s) => s.points.length > 0)
- const fallbackName = metricsQueryFallbackName(props.query)
+ // A formula query returns only the formula result (metricName is null on it),
+ // so the formula text itself is the honest name for an unlabelled series.
+ const fallbackName =
+ props.query.formula ??
+ props.query.clauses[0]?.metricName ??
+ (props.query.language === 'promql' && props.query.promql ? truncate(props.query.promql, 80) : 'metric')
return (
// A dashboard tile sets the height, so a minimum would overflow a short tile. Elsewhere the
diff --git a/products/metrics/frontend/nodes/metricsResponseSeries.ts b/products/metrics/frontend/nodes/metricsResponseSeries.ts
index 4f34e43a2b9a..9e05c2c8dc21 100644
--- a/products/metrics/frontend/nodes/metricsResponseSeries.ts
+++ b/products/metrics/frontend/nodes/metricsResponseSeries.ts
@@ -1,6 +1,4 @@
-import { truncate } from 'lib/utils/strings'
-
-import { MetricsQuery, MetricsQuerySeries } from '~/queries/schema/schema-general'
+import { MetricsQuerySeries } from '~/queries/schema/schema-general'
/**
* Dashboard tiles hand dataNodeLogic the cached insight object, whose data sits
@@ -20,13 +18,3 @@ export function seriesFromMetricsResponse(response: unknown): MetricsQuerySeries
}
return []
}
-
-/** The name for a series without labels. A formula query returns only the formula result (metricName is null on
- * it), so the formula text itself is the honest name for an unlabelled series. */
-export function metricsQueryFallbackName(query: MetricsQuery): string {
- return (
- query.formula ??
- query.clauses[0]?.metricName ??
- (query.language === 'promql' && query.promql ? truncate(query.promql, 80) : 'metric')
- )
-}
diff --git a/products/metrics/frontend/widgets/MetricsWidgetChart.tsx b/products/metrics/frontend/widgets/MetricsWidgetChart.tsx
deleted file mode 100644
index b9e70db29e94..000000000000
--- a/products/metrics/frontend/widgets/MetricsWidgetChart.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { MetricsHistogramQueryResponse, MetricsQuery } from '~/queries/schema/schema-general'
-
-import { metricsQueryFallbackName, seriesFromMetricsResponse } from '../nodes/metricsResponseSeries'
-import { HeatmapPanel } from '../panels/HeatmapPanel'
-import { MetricsPanel } from '../panels/MetricsPanel'
-import { isMetricsHeatmapQuery } from './metricsHeatmapQuery'
-import { MetricsWidgetMessage } from './MetricsWidgetMessage'
-
-function isHistogramResponse(response: unknown): response is MetricsHistogramQueryResponse {
- return typeof response === 'object' && response !== null && Array.isArray((response as { times?: unknown }).times)
-}
-
-/** Draws a metric widget's query result: a heatmap grid for the heatmap display, otherwise the matching panel. */
-export function MetricsWidgetChart({ query, response }: { query: MetricsQuery; response: unknown }): JSX.Element {
- if (isMetricsHeatmapQuery(query) && isHistogramResponse(response)) {
- if (response.times.length === 0) {
- return <MetricsWidgetMessage>No data for this metric in the selected range.</MetricsWidgetMessage>
- }
- return <HeatmapPanel response={response} unit={query.display?.unit} />
- }
-
- const series = seriesFromMetricsResponse(response)
- if (!series.some((s) => s.points.length > 0)) {
- return <MetricsWidgetMessage>No data for this metric in the selected range.</MetricsWidgetMessage>
- }
- return (
- <MetricsPanel
- series={series}
- fallbackName={metricsQueryFallbackName(query)}
- display={query.display}
- query={query}
- />
- )
-}
diff --git a/products/metrics/frontend/widgets/MetricsWidgetMessage.tsx b/products/metrics/frontend/widgets/MetricsWidgetMessage.tsx
deleted file mode 100644
index 68b2f1bc58f3..000000000000
--- a/products/metrics/frontend/widgets/MetricsWidgetMessage.tsx
+++ /dev/null
@@ -1,6 +0,0 @@
-/** A centered note in a metric widget's chart area, for empty and ineligible states. */
-export function MetricsWidgetMessage({ children }: { children: string }): JSX.Element {
- return (
- <div className="flex-1 flex items-center justify-center p-4 text-center text-secondary text-sm">{children}</div>
- )
-}
diff --git a/products/metrics/frontend/widgets/MetricsWidgetQueryEditor.tsx b/products/metrics/frontend/widgets/MetricsWidgetQueryEditor.tsx
deleted file mode 100644
index 2f56cb8eb7b4..000000000000
--- a/products/metrics/frontend/widgets/MetricsWidgetQueryEditor.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useState } from 'react'
-
-import { LemonBanner } from '@posthog/lemon-ui'
-
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-
-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import type { MetricsQuery } from '~/queries/schema/schema-general'
-
-import { MetricsQueryEditorSection } from '../components/MetricsQueryEditorSection'
-import { MetricsWidgetQueryPreview } from './MetricsWidgetQueryPreview'
-
-let uniquePreview = 0
-
-/** Edits a metric widget's query with the metrics builder, PromQL or SQL, above a live preview of the tile. */
-export function MetricsWidgetQueryEditor({
- query,
- setQuery,
- onUnrunTextChange,
-}: {
- query: MetricsQuery
- setQuery: (query: MetricsQuery) => void
- /** Gets whether the PromQL or SQL editor holds text that has not run yet. */
- onUnrunTextChange?: (unrun: boolean) => void
-}): JSX.Element {
- const [dataKey] = useState(() => `MetricsWidgetQueryPreview.${uniquePreview++}`)
- // The same audience as the metrics insight builder can edit a metric widget's query.
- const builderEnabled = useFeatureFlag('METRICS_INSIGHT_BUILDER')
-
- return (
- <div className="flex flex-col gap-3 min-w-0">
- {builderEnabled ? (
- <MetricsQueryEditorSection
- query={query}
- setQuery={setQuery}
- onRerun={() => dataNodeLogic.findMounted({ key: dataKey })?.actions.loadData('force_blocking')}
- onUnrunTextChange={onUnrunTextChange}
- surface="widget"
- />
- ) : (
- <LemonBanner type="info">
- You can't edit the query of a metric widget yet. You can still change the tile title and
- description.
- </LemonBanner>
- )}
- <div className="relative flex h-[320px] min-w-0 border rounded p-3" data-attr="metrics-widget-preview">
- <MetricsWidgetQueryPreview query={query} dataKey={dataKey} />
- </div>
- </div>
- )
-}
diff --git a/products/metrics/frontend/widgets/MetricsWidgetQueryPreview.tsx b/products/metrics/frontend/widgets/MetricsWidgetQueryPreview.tsx
deleted file mode 100644
index 82b84e170981..000000000000
--- a/products/metrics/frontend/widgets/MetricsWidgetQueryPreview.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { MetricsQuery } from '~/queries/schema/schema-general'
-
-import { MetricsHistogramQueryNode } from '../nodes/MetricsHistogramQueryNode'
-import { MetricsQueryNode } from '../nodes/MetricsQueryNode'
-import { isMetricsHeatmapQuery, metricsHeatmapIneligibleReason, metricsHistogramQueryFor } from './metricsHeatmapQuery'
-import { MetricsWidgetMessage } from './MetricsWidgetMessage'
-
-/** Runs a metric widget's query as the tile would and draws it, the heatmap through its histogram query. */
-export function MetricsWidgetQueryPreview({ query, dataKey }: { query: MetricsQuery; dataKey: string }): JSX.Element {
- if (!isMetricsHeatmapQuery(query)) {
- return <MetricsQueryNode query={query} context={{}} dataKey={dataKey} />
- }
- if (!query.clauses.length) {
- return <MetricsWidgetMessage>Pick a histogram metric to see its heatmap.</MetricsWidgetMessage>
- }
- const histogramQuery = metricsHistogramQueryFor(query)
- if (!histogramQuery) {
- return <MetricsWidgetMessage>{metricsHeatmapIneligibleReason(query) ?? ''}</MetricsWidgetMessage>
- }
- return <MetricsHistogramQueryNode query={histogramQuery} context={{}} />
-}
diff --git a/products/metrics/frontend/widgets/metricsHeatmapQuery.ts b/products/metrics/frontend/widgets/metricsHeatmapQuery.ts
deleted file mode 100644
index 5888012257bd..000000000000
--- a/products/metrics/frontend/widgets/metricsHeatmapQuery.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { MetricsHistogramQuery, MetricsOtelType, MetricsQuery, NodeKind } from '~/queries/schema/schema-general'
-
-import { queryLanguage } from '../queryLanguages/convert'
-
-const HISTOGRAM_METRIC_TYPES: readonly MetricsOtelType[] = ['histogram', 'exponential_histogram', 'summary']
-
-/** Why a query with the heatmap display can't draw one, or null when it can. Mirrors the backend's
- * `metrics_histogram_query_for`, so the editor preview and the dashboard tile agree. */
-export function metricsHeatmapIneligibleReason(query: MetricsQuery): string | null {
- if (queryLanguage(query) !== 'builder') {
- return "A heatmap needs a builder query. PromQL and SQL can't draw one."
- }
- if (query.clauses.length !== 1 || query.formula) {
- return 'A heatmap needs exactly one metric and no formula.'
- }
- const [clause] = query.clauses
- if (clause.groupBy?.length) {
- return "A heatmap can't group by attributes. Remove the group-by."
- }
- if (!clause.metricType || !HISTOGRAM_METRIC_TYPES.includes(clause.metricType)) {
- return 'A heatmap needs a histogram metric.'
- }
- return null
-}
-
-/** The histogram query that draws a metrics query with the heatmap display, or null when it can't. */
-export function metricsHistogramQueryFor(query: MetricsQuery): MetricsHistogramQuery | null {
- if (metricsHeatmapIneligibleReason(query) !== null) {
- return null
- }
- const [clause] = query.clauses
- return {
- kind: NodeKind.MetricsHistogramQuery,
- metricName: clause.metricName.trim(),
- metricType: clause.metricType,
- ...(clause.filters?.length ? { filters: clause.filters } : {}),
- ...(query.dateRange ? { dateRange: query.dateRange } : {}),
- ...(query.interval ? { interval: query.interval } : {}),
- ...(query.display?.unit ? { unit: query.display.unit } : {}),
- }
-}
-
-export function isMetricsHeatmapQuery(query: MetricsQuery): boolean {
- return query.display?.type === 'heatmap'
-}
diff --git a/products/metrics/manifest.tsx b/products/metrics/manifest.tsx
index 61abc7fd9c48..2e7295ada4ae 100644
--- a/products/metrics/manifest.tsx
+++ b/products/metrics/manifest.tsx
@@ -1,6 +1,7 @@
+import { FEATURE_FLAGS, INSIGHT_VISUAL_ORDER } from 'lib/constants'
import { urls } from 'scenes/urls'
-import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+import { MetricsQuery, NodeKind, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
import { FileSystemIconColor, ProductManifest } from '~/types'
import type { MetricsSceneActiveTab } from './frontend/metricsSceneLogic'
@@ -41,6 +42,19 @@ export const manifest: ProductManifest = {
templateId ? `/metrics/dashboard-review/${templateId}` : '/metrics/dashboard-review',
},
fileSystemTypes: {},
+ treeItemsNew: [
+ {
+ path: `Insight/Metrics`,
+ type: 'insight',
+ href: urls.insightNew({
+ query: { kind: NodeKind.MetricsQuery, clauses: [], dateRange: { date_from: '-1h' } } as MetricsQuery,
+ }),
+ flag: FEATURE_FLAGS.METRICS_INSIGHT_BUILDER,
+ iconType: 'metrics',
+ visualOrder: INSIGHT_VISUAL_ORDER.metrics,
+ sceneKeys: ['Insight'],
+ },
+ ],
treeItemsProducts: [
{
path: 'Metrics',
diff --git a/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.test.ts b/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.test.ts
index 8a384a189d34..30bfc3302249 100644
--- a/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.test.ts
+++ b/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.test.ts
@@ -236,20 +236,20 @@ describe('insightNavLogic', () => {
})
describe('metrics tab visibility', () => {
- it('does not offer the metrics tab on a new insight, because new metrics charts are widgets', () => {
+ const enableMetricsBuilder = (): void => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.METRICS]: true,
[FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]: true,
})
+ }
+
+ it('hides the metrics tab without both flags', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]: true })
expect(logic.values.tabs.map((tab) => tab.type)).not.toContain(InsightType.METRICS)
})
it('keeps the metrics tab and its draft after switching to another tab and back', async () => {
- // Only an open metrics query keeps the tab, as for a saved metrics insight.
- featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.METRICS]: true,
- [FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]: true,
- })
+ enableMetricsBuilder()
await expectLogic(builtInsightDataLogic, () => {
logic.actions.setActiveView(InsightType.METRICS)
diff --git a/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.tsx b/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.tsx
index b57eac8c4312..82bcc7ce0f4c 100644
--- a/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.tsx
+++ b/products/product_analytics/frontend/insights/InsightNav/insightNavLogic.tsx
@@ -587,12 +587,7 @@ export interface insightNavLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
activeView: (query: Node<Record<string, any>> | null) => InsightType
- tabs: (
- activeView: InsightType,
- query: Node<Record<string, any>> | null,
- featureFlags: FeatureFlagsSet,
- metricsQueryCache: MetricsQuery | null
- ) => Tab[]
+ tabs: (activeView: InsightType, query: Node<Record<string, any>> | null, featureFlags: FeatureFlagsSet) => Tab[]
}
}
@@ -664,12 +659,11 @@ export const insightNavLogic = kea<insightNavLogicType>([
},
],
tabs: [
- (s) => [s.activeView, s.query, s.featureFlags, s.metricsQueryCache],
+ (s) => [s.activeView, s.query, s.featureFlags],
(
activeView: InsightType,
query: null | import('~/queries/schema/schema-general').Node,
- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
- metricsQueryCache: MetricsQuery | null
+ featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet
) => {
const tabs: Tab[] = [
{
@@ -728,9 +722,10 @@ export const insightNavLogic = kea<insightNavLogicType>([
})
}
- // New metrics charts are metric widgets. The tab stays only so saved metrics insights remain
- // editable, including after a switch to another tab and back.
- if (activeView === InsightType.METRICS || metricsQueryCache) {
+ if (
+ (featureFlags[FEATURE_FLAGS.METRICS] && featureFlags[FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]) ||
+ activeView === InsightType.METRICS
+ ) {
tabs.push({
label: 'Metrics',
type: InsightType.METRICS,
diff --git a/products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu.tsx b/products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu.tsx
index 8a103aadc789..0d1e91aad946 100644
--- a/products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu.tsx
+++ b/products/product_analytics/frontend/insights/newInsightMenu/NewInsightMenu.tsx
@@ -5,6 +5,7 @@ import { IconPlusSmall, IconSparkles } from '@posthog/icons'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconInsightNumber, IconInsightPie, IconInsightTable, IconInsightWorldMap } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -15,7 +16,11 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { cn } from 'lib/utils/css-classes'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { INSIGHT_TYPE_URLS } from 'scenes/insights/utils'
-import { INSIGHT_TYPES_METADATA, isInsightTypeCreatable } from 'scenes/saved-insights/insightTypesMetadata'
+import {
+ INSIGHT_TYPES_METADATA,
+ QUERY_TYPES_METADATA,
+ isInsightTypeCreatable,
+} from 'scenes/saved-insights/insightTypesMetadata'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -155,8 +160,20 @@ const AI_CARD: NewInsightCardSpec = {
dataAttr: 'new-insight-menu-ai',
}
+const METRICS_CARD: NewInsightCardSpec = {
+ key: 'metrics',
+ name: QUERY_TYPES_METADATA[NodeKind.MetricsQuery].name,
+ description: QUERY_TYPES_METADATA[NodeKind.MetricsQuery].description ?? '',
+ icon: QUERY_TYPES_METADATA[NodeKind.MetricsQuery].icon,
+ sketch: GenericInsightSketch,
+ to: urls.insightNew({ type: InsightType.METRICS }),
+ dataAttr: 'new-insight-menu-metrics',
+ onClick: () => eventUsageLogic.actions.reportSavedInsightNewInsightClicked(InsightType.METRICS),
+}
+
function useNewInsightCards(): {
ai: NewInsightCardSpec
+ metrics?: NewInsightCardSpec
byType: Partial<Record<InsightType, NewInsightCardSpec>>
} {
const { featureFlags } = useValues(featureFlagLogic)
@@ -178,7 +195,9 @@ function useNewInsightCards(): {
}
byType[insightType as InsightType] = spec
}
- return { ai: AI_CARD, byType }
+ const metricsEnabled =
+ !!featureFlags[FEATURE_FLAGS.METRICS] && !!featureFlags[FEATURE_FLAGS.METRICS_INSIGHT_BUILDER]
+ return { ai: AI_CARD, metrics: metricsEnabled ? METRICS_CARD : undefined, byType }
}
function NewInsightCard({
@@ -232,6 +251,7 @@ const SHORT_CARD_DESCRIPTIONS: Record<string, string> = {
[InsightType.JOURNEYS]: 'The steps users take and where they stop.',
[InsightType.SQL]: 'Query your data with SQL.',
[InsightType.HOG]: 'Query your data with Hog.',
+ metrics: 'Chart service metrics over time.',
ai: 'Describe an insight and let AI build it.',
}
@@ -242,7 +262,7 @@ interface QuestionSection {
}
function useQuestionSections(): QuestionSection[] {
- const { ai, byType } = useNewInsightCards()
+ const { ai, metrics, byType } = useNewInsightCards()
const sections: { title: string; description: string; cards: (NewInsightCardSpec | undefined)[] }[] = [
{
title: 'How does it change over time?',
@@ -272,7 +292,7 @@ function useQuestionSections(): QuestionSection[] {
{
title: 'Build your own',
description: 'Write SQL against your data, or let AI build it.',
- cards: [byType[InsightType.SQL], byType[InsightType.HOG], ai],
+ cards: [byType[InsightType.SQL], byType[InsightType.HOG], metrics, ai],
},
]
return sections.map((section) => ({
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9aa577a11476..812d1586e524 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8232,7 +8232,6 @@ export namespace Schemas {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -8249,7 +8248,6 @@ export namespace Schemas {
ExperimentResults: 'experiment_results',
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
- Metrics: 'metrics',
MetricsTable: 'metrics_table',
NotebookWidget: 'notebook_widget',
SessionReplayList: 'session_replay_list',
@@ -8278,7 +8276,6 @@ export namespace Schemas {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -8293,7 +8290,7 @@ export namespace Schemas {
*/
export interface AddDashboardWidgetsBatchRequestOpenApi {
/**
- * Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
+ * Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
* @minItems 1
* @maxItems 10
*/
@@ -12019,193 +12016,7 @@ export namespace Schemas {
limit?: number;
}
- export type MetricsAggregation = typeof MetricsAggregation[keyof typeof MetricsAggregation];
-
-
- export const MetricsAggregation = {
- Sum: 'sum',
- Avg: 'avg',
- Count: 'count',
- Min: 'min',
- Max: 'max',
- Quantile: 'quantile',
- Rate: 'rate',
- Increase: 'increase',
- HistogramQuantile: 'histogram_quantile',
- } as const;
-
- export interface MetricsQueryGroupBy {
- key: string;
- scope?: MetricsAttributeScope | null;
- }
-
- export type MetricsOtelType = typeof MetricsOtelType[keyof typeof MetricsOtelType];
-
-
- export const MetricsOtelType = {
- Gauge: 'gauge',
- Sum: 'sum',
- Histogram: 'histogram',
- ExponentialHistogram: 'exponential_histogram',
- Summary: 'summary',
- } as const;
-
- export type MetricsRangeFunction = typeof MetricsRangeFunction[keyof typeof MetricsRangeFunction];
-
-
- export const MetricsRangeFunction = {
- Rate: 'rate',
- Increase: 'increase',
- } as const;
-
- export interface MetricsQueryClause {
- /** Omit to get one line per series (at most 100), without combining them */
- aggregation?: MetricsAggregation | null;
- filters?: MetricsQueryFilter[] | null;
- groupBy?: MetricsQueryGroupBy[] | null;
- metricName: string;
- /** Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series. */
- metricType?: MetricsOtelType | null;
- /** Alias a formula refers to (e.g. "a"); must be unique within the query */
- name: string;
- /** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
- quantile?: number | null;
- /** Applied to each series before `aggregation`, like `rate()` in PromQL */
- rangeFunction?: MetricsRangeFunction | null;
- }
-
- export type MetricsReducer = typeof MetricsReducer[keyof typeof MetricsReducer];
-
-
- export const MetricsReducer = {
- Last: 'last',
- Mean: 'mean',
- Min: 'min',
- Max: 'max',
- Sum: 'sum',
- Delta: 'delta',
- } as const;
-
- export type MetricsNullMode = typeof MetricsNullMode[keyof typeof MetricsNullMode];
-
-
- export const MetricsNullMode = {
- Gap: 'gap',
- Zero: 'zero',
- Connect: 'connect',
- } as const;
-
- export type MetricsStatSummary = typeof MetricsStatSummary[keyof typeof MetricsStatSummary];
-
-
- export const MetricsStatSummary = {
- Latest: 'latest',
- Average: 'average',
- Total: 'total',
- } as const;
-
- export interface MetricsThreshold {
- /** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
- color: string;
- /** Lower bound of this band. The lowest step is the base color below every other step. */
- value: number;
- }
-
- export type MetricsDisplayType = typeof MetricsDisplayType[keyof typeof MetricsDisplayType];
-
-
- export const MetricsDisplayType = {
- Line: 'line',
- Area: 'area',
- Bar: 'bar',
- Stat: 'stat',
- Gauge: 'gauge',
- Bargauge: 'bargauge',
- Table: 'table',
- Heatmap: 'heatmap',
- } as const;
-
- export type MetricsAxisScale = typeof MetricsAxisScale[keyof typeof MetricsAxisScale];
-
-
- export const MetricsAxisScale = {
- Linear: 'linear',
- Log: 'log',
- } as const;
-
- export interface MetricsYAxisSettings {
- /** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot. */
- max?: number | null;
- /** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
- min?: number | null;
- scale?: MetricsAxisScale | null;
- /** When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero. */
- startAtZero?: boolean | null;
- }
-
- export interface MetricsDisplaySettings {
- goalLines?: GoalLine[] | null;
- /** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
- legendCalcs?: MetricsReducer[] | null;
- /** How a null bucket renders on a time-series chart. */
- nullMode?: MetricsNullMode | null;
- /** How scalar panels and legend calcs collapse a series to one number. */
- reduce?: MetricsReducer | null;
- /** `stat` display only: which summary the headline value shows. */
- statSummary?: MetricsStatSummary | null;
- /** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
- thresholds?: MetricsThreshold[] | null;
- type?: MetricsDisplayType | null;
- /** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
- unit?: string | null;
- yAxis?: MetricsYAxisSettings | null;
- }
-
- export type MetricsQueryLanguage = typeof MetricsQueryLanguage[keyof typeof MetricsQueryLanguage];
-
-
- export const MetricsQueryLanguage = {
- Builder: 'builder',
- Promql: 'promql',
- Sql: 'sql',
- } as const;
-
- /**
- * A `MetricsQuery` as a metrics widget stores it.
- *
- * Response, modifier and tag fields are runtime state, so a stored config can't carry them.
- */
- export interface MetricsWidgetQuery {
- /**
- * Builder series. Empty when `language` is `promql` or `sql`, or until a metric is picked.
- * @maxItems 10
- */
- clauses?: MetricsQueryClause[];
- /** Defaults to the last 24 hours when omitted; dashboard date filters override it */
- dateRange?: DateRange | null;
- /** Chart presentation. A node without it renders as a line chart. */
- display?: MetricsDisplaySettings | null;
- /** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */
- formula?: string | null;
- /** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week; auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets. A dashboard variable reference such as `$window` pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable. */
- interval?: string | null;
- kind?: 'MetricsQuery';
- /** How the query is written; the builder when unset. */
- language?: MetricsQueryLanguage | null;
- /** PromQL expression, run as a range query. Used when `language` is `promql`. */
- promql?: string | null;
- /** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a `value` column; every other column is a series label. */
- sql?: string | null;
- /** version of the node, used for schema migrations */
- version?: number | null;
- }
-
- export interface MetricsWidgetConfig {
- /** Metrics query the tile runs and how it draws it (`display.type`: line, area, bar, stat, gauge, bargauge, table or heatmap). `dateRange` is the default window; the dashboard date filter overrides it. A config update replaces the whole query. */
- query?: MetricsWidgetQuery;
- }
-
- export type DashboardWidgetConfig = NotebookWidgetConfig | ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig | ExperimentsListWidgetConfig | ExperimentResultsWidgetConfig | SurveyResultsWidgetConfig | LogsListWidgetConfig | ConversationsRecentTicketsWidgetConfig | CanvasAppWidgetConfig | MetricsTableWidgetConfig | MetricsWidgetConfig;
+ export type DashboardWidgetConfig = NotebookWidgetConfig | ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig | ExperimentsListWidgetConfig | ExperimentResultsWidgetConfig | SurveyResultsWidgetConfig | LogsListWidgetConfig | ConversationsRecentTicketsWidgetConfig | CanvasAppWidgetConfig | MetricsTableWidgetConfig;
export interface DashboardWidget {
readonly id: string;
@@ -30488,7 +30299,6 @@ export namespace Schemas {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -30660,8 +30470,6 @@ export namespace Schemas {
* @nullable
*/
error: string | null;
- /** True when `error` explains the failure to the viewer (for example, no access or an invalid query) and can be shown as is. Other errors are generic. */
- error_is_user_facing?: boolean;
}
export interface DataCatalogCertification {
@@ -62734,6 +62542,157 @@ export namespace Schemas {
version?: number | null;
}
+ export type MetricsAggregation = typeof MetricsAggregation[keyof typeof MetricsAggregation];
+
+
+ export const MetricsAggregation = {
+ Sum: 'sum',
+ Avg: 'avg',
+ Count: 'count',
+ Min: 'min',
+ Max: 'max',
+ Quantile: 'quantile',
+ Rate: 'rate',
+ Increase: 'increase',
+ HistogramQuantile: 'histogram_quantile',
+ } as const;
+
+ export interface MetricsQueryGroupBy {
+ key: string;
+ scope?: MetricsAttributeScope | null;
+ }
+
+ export type MetricsOtelType = typeof MetricsOtelType[keyof typeof MetricsOtelType];
+
+
+ export const MetricsOtelType = {
+ Gauge: 'gauge',
+ Sum: 'sum',
+ Histogram: 'histogram',
+ ExponentialHistogram: 'exponential_histogram',
+ Summary: 'summary',
+ } as const;
+
+ export type MetricsRangeFunction = typeof MetricsRangeFunction[keyof typeof MetricsRangeFunction];
+
+
+ export const MetricsRangeFunction = {
+ Rate: 'rate',
+ Increase: 'increase',
+ } as const;
+
+ export interface MetricsQueryClause {
+ /** Omit to get one line per series (at most 100), without combining them */
+ aggregation?: MetricsAggregation | null;
+ filters?: MetricsQueryFilter[] | null;
+ groupBy?: MetricsQueryGroupBy[] | null;
+ metricName: string;
+ /** Series identity includes the OTel type — one name can exist as e.g. both a counter and a gauge — so a clause pins it to avoid blending distinct series. */
+ metricType?: MetricsOtelType | null;
+ /** Alias a formula refers to (e.g. "a"); must be unique within the query */
+ name: string;
+ /** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
+ quantile?: number | null;
+ /** Applied to each series before `aggregation`, like `rate()` in PromQL */
+ rangeFunction?: MetricsRangeFunction | null;
+ }
+
+ export type MetricsReducer = typeof MetricsReducer[keyof typeof MetricsReducer];
+
+
+ export const MetricsReducer = {
+ Last: 'last',
+ Mean: 'mean',
+ Min: 'min',
+ Max: 'max',
+ Sum: 'sum',
+ Delta: 'delta',
+ } as const;
+
+ export type MetricsNullMode = typeof MetricsNullMode[keyof typeof MetricsNullMode];
+
+
+ export const MetricsNullMode = {
+ Gap: 'gap',
+ Zero: 'zero',
+ Connect: 'connect',
+ } as const;
+
+ export type MetricsStatSummary = typeof MetricsStatSummary[keyof typeof MetricsStatSummary];
+
+
+ export const MetricsStatSummary = {
+ Latest: 'latest',
+ Average: 'average',
+ Total: 'total',
+ } as const;
+
+ export interface MetricsThreshold {
+ /** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
+ color: string;
+ /** Lower bound of this band. The lowest step is the base color below every other step. */
+ value: number;
+ }
+
+ export type MetricsDisplayType = typeof MetricsDisplayType[keyof typeof MetricsDisplayType];
+
+
+ export const MetricsDisplayType = {
+ Line: 'line',
+ Area: 'area',
+ Bar: 'bar',
+ Stat: 'stat',
+ Gauge: 'gauge',
+ Bargauge: 'bargauge',
+ Table: 'table',
+ Heatmap: 'heatmap',
+ } as const;
+
+ export type MetricsAxisScale = typeof MetricsAxisScale[keyof typeof MetricsAxisScale];
+
+
+ export const MetricsAxisScale = {
+ Linear: 'linear',
+ Log: 'log',
+ } as const;
+
+ export interface MetricsYAxisSettings {
+ /** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot. */
+ max?: number | null;
+ /** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
+ min?: number | null;
+ scale?: MetricsAxisScale | null;
+ /** When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero. */
+ startAtZero?: boolean | null;
+ }
+
+ export interface MetricsDisplaySettings {
+ goalLines?: GoalLine[] | null;
+ /** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
+ legendCalcs?: MetricsReducer[] | null;
+ /** How a null bucket renders on a time-series chart. */
+ nullMode?: MetricsNullMode | null;
+ /** How scalar panels and legend calcs collapse a series to one number. */
+ reduce?: MetricsReducer | null;
+ /** `stat` display only: which summary the headline value shows. */
+ statSummary?: MetricsStatSummary | null;
+ /** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
+ thresholds?: MetricsThreshold[] | null;
+ type?: MetricsDisplayType | null;
+ /** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
+ unit?: string | null;
+ yAxis?: MetricsYAxisSettings | null;
+ }
+
+ export type MetricsQueryLanguage = typeof MetricsQueryLanguage[keyof typeof MetricsQueryLanguage];
+
+
+ export const MetricsQueryLanguage = {
+ Builder: 'builder',
+ Promql: 'promql',
+ Sql: 'sql',
+ } as const;
+
export interface MetricsQueryPoint {
/** Bucket start, ISO 8601 */
time: string;
@@ -73910,37 +73869,6 @@ export namespace Schemas {
MetricsTable: 'metrics_table',
} as const;
- export type MetricsWidgetCatalogEntryOpenApiWidgetType = typeof MetricsWidgetCatalogEntryOpenApiWidgetType[keyof typeof MetricsWidgetCatalogEntryOpenApiWidgetType];
-
-
- export const MetricsWidgetCatalogEntryOpenApiWidgetType = {
- Metrics: 'metrics',
- } as const;
-
- export interface MetricsWidgetCatalogEntryOpenApi {
- widget_type: MetricsWidgetCatalogEntryOpenApiWidgetType;
- group_id: string;
- group_label: string;
- label: string;
- description: string;
- /** Config shape for this widget type. Build the config for the batch add and batch update tools from it, because their schemas do not list config keys. */
- readonly config_schema: MetricsWidgetConfig;
- /** @nullable */
- required_product_access?: string | null;
- /** Whether tiles of this type self-update in real time after load. Live tiles show a fixed real-time window and cannot apply test-account filtering to the stream, so their config takes neither dateRange nor filterTestAccounts. */
- live: boolean;
- }
-
- /**
- * * `metrics` - metrics
- */
- export type MetricsWidgetTypeEnum = typeof MetricsWidgetTypeEnum[keyof typeof MetricsWidgetTypeEnum];
-
-
- export const MetricsWidgetTypeEnum = {
- Metrics: 'metrics',
- } as const;
-
export interface MicrosoftDefenderCloudAppsScannerFindingSignalExtra {
severity_value: string | null;
resolution_status_value: string | null;
@@ -95630,7 +95558,6 @@ export namespace Schemas {
* * `experiment_results` - Experiment Results
* * `experiments_list` - Experiments List
* * `logs_list` - Logs List
- * * `metrics` - Metrics
* * `metrics_table` - Metrics Table
* * `notebook_widget` - Notebook Widget
* * `session_replay_list` - Session Replay List
@@ -125678,7 +125605,7 @@ export namespace Schemas {
generation_id: string;
}
- export type WidgetCatalogEntry = NotebookWidgetCatalogEntryOpenApi | ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi | ExperimentsListWidgetCatalogEntryOpenApi | ExperimentResultsWidgetCatalogEntryOpenApi | SurveyResultsWidgetCatalogEntryOpenApi | LogsListWidgetCatalogEntryOpenApi | ConversationsRecentTicketsWidgetCatalogEntryOpenApi | CanvasAppWidgetCatalogEntryOpenApi | MetricsTableWidgetCatalogEntryOpenApi | MetricsWidgetCatalogEntryOpenApi;
+ export type WidgetCatalogEntry = NotebookWidgetCatalogEntryOpenApi | ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi | ExperimentsListWidgetCatalogEntryOpenApi | ExperimentResultsWidgetCatalogEntryOpenApi | SurveyResultsWidgetCatalogEntryOpenApi | LogsListWidgetCatalogEntryOpenApi | ConversationsRecentTicketsWidgetCatalogEntryOpenApi | CanvasAppWidgetCatalogEntryOpenApi | MetricsTableWidgetCatalogEntryOpenApi;
export interface WidgetCatalogResponse {
/** Registered dashboard widget types. */
@@ -134235,15 +134162,7 @@ export namespace Schemas {
} as const;
export type DashboardsRunWidgetsRetrieveParams = {
- /**
- * Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.
- */
- filters_override?: string;
format?: DashboardsRunWidgetsRetrieveFormat;
- /**
- * Recompute widgets that follow dashboard filters (such as metrics) instead of serving their query cache, as a manual refresh of an insight tile does.
- */
- refresh?: boolean;
/**
* Comma-separated dashboard tile IDs to run widgets for.
*/
@@ -134401,7 +134320,6 @@ export namespace Schemas {
ExperimentResults: 'experiment_results',
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
- Metrics: 'metrics',
MetricsTable: 'metrics_table',
NotebookWidget: 'notebook_widget',
SessionReplayList: 'session_replay_list',
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index 2639a02ffff3..daeb0f63e974 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -803,19 +803,7 @@ export const DashboardsRunWidgetsRetrieveParams = () => zod.object({
})
export const DashboardsRunWidgetsRetrieveQueryParams = () => zod.object({
- filters_override: zod
- .string()
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'
- ),
format: zod.enum(['json', 'txt']).optional(),
- refresh: zod
- .boolean()
- .optional()
- .describe(
- 'Recompute widgets that follow dashboard filters (such as metrics) instead of serving their query cache, as a manual refresh of an insight tile does.'
- ),
tile_ids: zod.string().describe('Comma-separated dashboard tile IDs to run widgets for.'),
})
@@ -976,17 +964,16 @@ export const DashboardsWidgetsBatchCreateBody = () => zod
'experiment_results',
'experiments_list',
'logs_list',
- 'metrics',
'metrics_table',
'notebook_widget',
'session_replay_list',
'survey_results',
])
.describe(
- '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
)
.describe(
- 'Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ 'Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
),
config: zod
.record(zod.string(), zod.unknown())
@@ -998,7 +985,7 @@ export const DashboardsWidgetsBatchCreateBody = () => zod
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsMax)
.describe(
- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'
+ 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'
),
})
.describe('OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.')
@@ -1057,18 +1044,17 @@ export const DashboardsUpdateWidgetsBatchBody = () => zod
'experiment_results',
'experiments_list',
'logs_list',
- 'metrics',
'metrics_table',
'notebook_widget',
'session_replay_list',
'survey_results',
])
.describe(
- '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
+ '\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results'
)
.optional()
.describe(
- "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics` - Metrics\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results"
+ "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n\* `activity_events_list` - Activity Events List\n\* `canvas_app` - Canvas App\n\* `conversations_recent_tickets` - Conversations Recent Tickets\n\* `error_tracking_list` - Error Tracking List\n\* `experiment_results` - Experiment Results\n\* `experiments_list` - Experiments List\n\* `logs_list` - Logs List\n\* `metrics_table` - Metrics Table\n\* `notebook_widget` - Notebook Widget\n\* `session_replay_list` - Session Replay List\n\* `survey_results` - Survey Results"
),
config: zod
.record(zod.string(), zod.unknown())
@@ -1136,7 +1122,6 @@ export const DashboardsWidgetCatalogRetrieveQueryParams = () => zod.object({
'experiment_results',
'experiments_list',
'logs_list',
- 'metrics',
'metrics_table',
'notebook_widget',
'session_replay_list',
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index b20bb5a0c664..d757a24ec617 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -860,14 +860,6 @@ const DashboardWidgetsRunSchema = () => {
return DashboardsRunWidgetsRetrieveParams.omit({ project_id: true })
.extend(DashboardsRunWidgetsRetrieveQueryParams.omit({ format: true }).shape)
.extend({ id: z.preprocess(castStringToInt, DashboardsRunWidgetsRetrieveParams.shape['id']) })
- .extend({
- filters_override: z
- .union([z.string(), z.record(z.string(), z.unknown())])
- .optional()
- .describe(
- 'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'
- ),
- })
}
const dashboardWidgetsRun = (): ToolBase<
@@ -882,8 +874,6 @@ const dashboardWidgetsRun = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(params.id))}/run_widgets/`,
query: {
- filters_override: params.filters_override,
- refresh: params.refresh,
tile_ids: params.tile_ids,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widget-catalog-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widget-catalog-list.json
index 1af314d306ce..aeca606c296d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widget-catalog-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widget-catalog-list.json
@@ -12,7 +12,6 @@
"experiment_results",
"experiments_list",
"logs_list",
- "metrics",
"metrics_table",
"notebook_widget",
"session_replay_list",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
index 263671512d93..0b4b3a093ef8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
@@ -6,7 +6,7 @@
"type": "number"
},
"widgets": {
- "description": "Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).",
+ "description": "Widget tiles to add atomically. Supported widget_type values: activity_events_list, canvas_app, conversations_recent_tickets, error_tracking_list, experiment_results, experiments_list, logs_list, metrics_table, notebook_widget, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).",
"items": {
"properties": {
"config": {
@@ -88,7 +88,7 @@
"type": "boolean"
},
"widget_type": {
- "description": "Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n* `activity_events_list` - Activity Events List\n* `canvas_app` - Canvas App\n* `conversations_recent_tickets` - Conversations Recent Tickets\n* `error_tracking_list` - Error Tracking List\n* `experiment_results` - Experiment Results\n* `experiments_list` - Experiments List\n* `logs_list` - Logs List\n* `metrics` - Metrics\n* `metrics_table` - Metrics Table\n* `notebook_widget` - Notebook Widget\n* `session_replay_list` - Session Replay List\n* `survey_results` - Survey Results",
+ "description": "Widget type to add. Use dashboard-widget-catalog-list to pick one.\n\n* `activity_events_list` - Activity Events List\n* `canvas_app` - Canvas App\n* `conversations_recent_tickets` - Conversations Recent Tickets\n* `error_tracking_list` - Error Tracking List\n* `experiment_results` - Experiment Results\n* `experiments_list` - Experiments List\n* `logs_list` - Logs List\n* `metrics_table` - Metrics Table\n* `notebook_widget` - Notebook Widget\n* `session_replay_list` - Session Replay List\n* `survey_results` - Survey Results",
"enum": [
"activity_events_list",
"canvas_app",
@@ -97,7 +97,6 @@
"experiment_results",
"experiments_list",
"logs_list",
- "metrics",
"metrics_table",
"notebook_widget",
"session_replay_list",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
index 474526423010..3310816cecb0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
@@ -38,7 +38,7 @@
"type": "number"
},
"widget_type": {
- "description": "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n* `activity_events_list` - Activity Events List\n* `canvas_app` - Canvas App\n* `conversations_recent_tickets` - Conversations Recent Tickets\n* `error_tracking_list` - Error Tracking List\n* `experiment_results` - Experiment Results\n* `experiments_list` - Experiments List\n* `logs_list` - Logs List\n* `metrics` - Metrics\n* `metrics_table` - Metrics Table\n* `notebook_widget` - Notebook Widget\n* `session_replay_list` - Session Replay List\n* `survey_results` - Survey Results",
+ "description": "The tile's widget type. It cannot be changed, so omit it or pass the current type.\n\n* `activity_events_list` - Activity Events List\n* `canvas_app` - Canvas App\n* `conversations_recent_tickets` - Conversations Recent Tickets\n* `error_tracking_list` - Error Tracking List\n* `experiment_results` - Experiment Results\n* `experiments_list` - Experiments List\n* `logs_list` - Logs List\n* `metrics_table` - Metrics Table\n* `notebook_widget` - Notebook Widget\n* `session_replay_list` - Session Replay List\n* `survey_results` - Survey Results",
"enum": [
"activity_events_list",
"canvas_app",
@@ -47,7 +47,6 @@
"experiment_results",
"experiments_list",
"logs_list",
- "metrics",
"metrics_table",
"notebook_widget",
"session_replay_list",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-run.json
index d8e655b5bf97..d830b2b3c068 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-run.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-run.json
@@ -1,29 +1,10 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
- "filters_override": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "additionalProperties": {},
- "propertyNames": {
- "type": "string"
- },
- "type": "object"
- }
- ],
- "description": "Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token."
- },
"id": {
"description": "A unique integer value identifying this dashboard.",
"type": "number"
},
- "refresh": {
- "description": "Recompute widgets that follow dashboard filters (such as metrics) instead of serving their query cache, as a manual refresh of an insight tile does.",
- "type": "boolean"
- },
"tile_ids": {
"description": "Comma-separated dashboard tile IDs to run widgets for.",
"type": "string"
diff --git a/tach.toml b/tach.toml
index e452f8be022e..bffb116ff9ac 100644
--- a/tach.toml
+++ b/tach.toml
@@ -316,8 +316,6 @@ depends_on = [
"products.surveys", "products.access_control",
# The canvas_app widget resolves its canvas through the canvas facade as the viewer.
"products.canvas",
- # The metrics widget runs metrics queries through the metrics facade as the viewer.
- "products.metrics",
# Facade-only: the dashboard filter access check asks the subscriptions facade whether a
# subscription delivers the dashboard.
"products.subscriptions",