@mastra/playground-ui 71.0.0-alpha.8 → 71.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/domains/agents/chat/stream-error-message.cjs.js +13 -6
  2. package/dist/domains/agents/chat/stream-error-message.cjs.js.map +1 -1
  3. package/dist/domains/agents/chat/stream-error-message.es.js +13 -6
  4. package/dist/domains/agents/chat/stream-error-message.es.js.map +1 -1
  5. package/dist/domains/agents/chat/use-chat-send-handler.cjs.js +4 -1
  6. package/dist/domains/agents/chat/use-chat-send-handler.cjs.js.map +1 -1
  7. package/dist/domains/agents/chat/use-chat-send-handler.es.js +4 -1
  8. package/dist/domains/agents/chat/use-chat-send-handler.es.js.map +1 -1
  9. package/dist/domains/dashboards/components/stateless-widget.cjs.js.map +1 -1
  10. package/dist/domains/dashboards/components/stateless-widget.es.js.map +1 -1
  11. package/dist/domains/dashboards/components/view-tabs.cjs.js +30 -0
  12. package/dist/domains/dashboards/components/view-tabs.cjs.js.map +1 -0
  13. package/dist/domains/dashboards/components/view-tabs.d.ts +1 -0
  14. package/dist/domains/dashboards/components/view-tabs.es.js +29 -0
  15. package/dist/domains/dashboards/components/view-tabs.es.js.map +1 -0
  16. package/dist/domains/dashboards/hooks/use-widget-views.cjs.js +24 -5
  17. package/dist/domains/dashboards/hooks/use-widget-views.cjs.js.map +1 -1
  18. package/dist/domains/dashboards/hooks/use-widget-views.es.js +24 -6
  19. package/dist/domains/dashboards/hooks/use-widget-views.es.js.map +1 -1
  20. package/dist/domains/dashboards/kinds/scores/scores-widget.cjs.js +2 -2
  21. package/dist/domains/dashboards/kinds/scores/scores-widget.cjs.js.map +1 -1
  22. package/dist/domains/dashboards/kinds/scores/scores-widget.es.js +1 -1
  23. package/dist/domains/dashboards/kinds/scores/scores-widget.es.js.map +1 -1
  24. package/dist/domains/dashboards/kinds/table/table-tabs.cjs.js +0 -11
  25. package/dist/domains/dashboards/kinds/table/table-tabs.cjs.js.map +1 -1
  26. package/dist/domains/dashboards/kinds/table/table-tabs.es.js +0 -11
  27. package/dist/domains/dashboards/kinds/table/table-tabs.es.js.map +1 -1
  28. package/dist/domains/dashboards/kinds/table/table-widget.cjs.js.map +1 -1
  29. package/dist/domains/dashboards/kinds/table/table-widget.es.js.map +1 -1
  30. package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.cjs.js +1 -1
  31. package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.cjs.js.map +1 -1
  32. package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.es.js +1 -1
  33. package/dist/domains/dashboards/kinds/timeseries/timeseries-widget.es.js.map +1 -1
  34. package/dist/domains/dashboards/lib/chrome.cjs.js +1 -23
  35. package/dist/domains/dashboards/lib/chrome.cjs.js.map +1 -1
  36. package/dist/domains/dashboards/lib/chrome.es.js +2 -23
  37. package/dist/domains/dashboards/lib/chrome.es.js.map +1 -1
  38. package/dist/domains/dashboards/lib/view-labels.cjs.js +9 -7
  39. package/dist/domains/dashboards/lib/view-labels.cjs.js.map +1 -1
  40. package/dist/domains/dashboards/lib/view-labels.es.js +9 -7
  41. package/dist/domains/dashboards/lib/view-labels.es.js.map +1 -1
  42. package/dist/domains/dashboards/metrics-dashboard.cjs.js +1 -1
  43. package/dist/domains/dashboards/metrics-dashboard.cjs.js.map +1 -1
  44. package/dist/domains/dashboards/metrics-dashboard.es.js +1 -1
  45. package/dist/domains/dashboards/metrics-dashboard.es.js.map +1 -1
  46. package/dist/domains/dashboards/widget-kind.cjs.js.map +1 -1
  47. package/dist/domains/dashboards/widget-kind.es.js.map +1 -1
  48. package/dist/domains/dashboards.cjs.js +1 -1
  49. package/dist/domains/dashboards.es.js +1 -1
  50. package/dist/domains/metrics/components/breakdown/breakdown-table.cjs.js +2 -2
  51. package/dist/domains/metrics/components/breakdown/breakdown-table.cjs.js.map +1 -1
  52. package/dist/domains/metrics/components/breakdown/breakdown-table.es.js +2 -2
  53. package/dist/domains/metrics/components/breakdown/breakdown-table.es.js.map +1 -1
  54. package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.cjs.js +4 -2
  55. package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.cjs.js.map +1 -1
  56. package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.es.js +4 -2
  57. package/dist/domains/metrics/components/distinct-ids/distinct-ids-chart.es.js.map +1 -1
  58. package/dist/src/domains/agents/chat/stream-error-message.d.ts +16 -11
  59. package/dist/src/domains/dashboards/components/stateless-widget.d.ts +1 -2
  60. package/dist/src/domains/dashboards/components/view-tabs.d.ts +13 -0
  61. package/dist/src/domains/dashboards/hooks/use-widget-views.d.ts +11 -5
  62. package/dist/src/domains/dashboards/lib/chrome.d.ts +4 -13
  63. package/dist/src/domains/dashboards/lib/view-labels.d.ts +3 -3
  64. package/dist/src/domains/dashboards/widget-kind.d.ts +2 -3
  65. package/package.json +13 -12
  66. package/dist/domains/dashboards/kinds/table/table-view-tabs.cjs.js +0 -32
  67. package/dist/domains/dashboards/kinds/table/table-view-tabs.cjs.js.map +0 -1
  68. package/dist/domains/dashboards/kinds/table/table-view-tabs.d.ts +0 -1
  69. package/dist/domains/dashboards/kinds/table/table-view-tabs.es.js +0 -31
  70. package/dist/domains/dashboards/kinds/table/table-view-tabs.es.js.map +0 -1
  71. package/dist/src/domains/dashboards/kinds/table/table-view-tabs.d.ts +0 -14
@@ -1 +1 @@
1
- {"version":3,"file":"view-labels.es.js","names":[],"sources":["../../../../src/domains/dashboards/lib/view-labels.ts"],"sourcesContent":["/** \"agent\" → \"agents\", \"entity\" → \"entities\", \"box\" → \"boxes\"; a word already ending in \"s\" (\"teams\") stays. */\nconst plural = (word: string) => {\n if (/s$/i.test(word)) return word;\n if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;\n if (/(x|z|ch|sh)$/i.test(word)) return `${word}es`;\n return `${word}s`;\n};\n\n/** How many leading words every label shares, leaving each at least one word of its own. */\nfunction sharedWords(words: readonly string[][]): number {\n const [first = []] = words;\n let shared = 0;\n while (words.length > 1 && words.every(w => w.length > shared + 1 && w[shared] === first[shared])) shared++;\n return shared;\n}\n\n/**\n * Short tab names for a card's views: their labels without the words they all start with,\n * capitalised (\"Breakdown by agent\", \"Breakdown by tool\" → \"Agents\", \"Tools\"; after \"by\", the\n * rest names what each row is, so it reads as a plural). Labels that share nothing, or that would\n * shorten to the same name, stay as they are.\n */\nexport function shortViewLabels(labels: readonly string[]): string[] {\n const words = labels.map(label => label.split(/\\s+/));\n const shared = sharedWords(words);\n if (shared === 0) return [...labels];\n const byRows = words[0]?.[shared - 1]?.toLowerCase() === 'by';\n const names = words.map(w => {\n const rest = w.slice(shared);\n const last = rest.pop() ?? '';\n const name = [...rest, byRows ? plural(last) : last].join(' ');\n return name.charAt(0).toUpperCase() + name.slice(1);\n });\n // Two views that shorten to the same name (\"by team\", \"by teams\") keep their labels, to tell apart.\n return new Set(names).size === names.length ? names : [...labels];\n}\n"],"mappings":";;AACA,IAAM,UAAU,SAAiB;CAC/B,IAAI,MAAM,KAAK,IAAI,GAAG,OAAO;CAC7B,IAAI,cAAc,KAAK,IAAI,GAAG,OAAO,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE;CAC1D,IAAI,gBAAgB,KAAK,IAAI,GAAG,OAAO,GAAG,KAAK;CAC/C,OAAO,GAAG,KAAK;AACjB;;AAGA,SAAS,YAAY,OAAoC;CACvD,MAAM,CAAC,QAAQ,CAAC,KAAK;CACrB,IAAI,SAAS;CACb,OAAO,MAAM,SAAS,KAAK,MAAM,OAAM,MAAK,EAAE,SAAS,SAAS,KAAK,EAAE,YAAY,MAAM,OAAO,GAAG;CACnG,OAAO;AACT;;;;;;;AAQA,SAAgB,gBAAgB,QAAqC;CACnE,MAAM,QAAQ,OAAO,KAAI,UAAS,MAAM,MAAM,KAAK,CAAC;CACpD,MAAM,SAAS,YAAY,KAAK;CAChC,IAAI,WAAW,GAAG,OAAO,CAAC,GAAG,MAAM;CACnC,MAAM,SAAS,MAAM,EAAE,GAAG,SAAS,EAAE,EAAE,YAAY,MAAM;CACzD,MAAM,QAAQ,MAAM,KAAI,MAAK;EAC3B,MAAM,OAAO,EAAE,MAAM,MAAM;EAC3B,MAAM,OAAO,KAAK,IAAI,KAAK;EAC3B,MAAM,OAAO,CAAC,GAAG,MAAM,SAAS,OAAO,IAAI,IAAI,IAAI,CAAC,CAAC,KAAK,GAAG;EAC7D,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC;CACpD,CAAC;CAED,OAAO,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM,SAAS,QAAQ,CAAC,GAAG,MAAM;AAClE"}
1
+ {"version":3,"file":"view-labels.es.js","names":[],"sources":["../../../../src/domains/dashboards/lib/view-labels.ts"],"sourcesContent":["/** \"agent\" → \"agents\", \"entity\" → \"entities\", \"box\" → \"boxes\"; a word already ending in \"s\" (\"teams\") stays. */\nconst plural = (word: string) => {\n if (/s$/i.test(word)) return word;\n if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;\n if (/(x|z|ch|sh)$/i.test(word)) return `${word}es`;\n return `${word}s`;\n};\n\n/** How many leading words every label shares, leaving each at least one word of its own. */\nfunction sharedWords(words: readonly string[][]): number {\n const [first = []] = words;\n let shared = 0;\n while (words.length > 1 && words.every(w => w.length > shared + 1 && w[shared] === first[shared])) shared++;\n return shared;\n}\n\nconst reversed = (words: readonly string[][]) => words.map(w => [...w].reverse());\n\n/**\n * Short tab names for a card's views: their labels without the words they all start or end with,\n * capitalised (\"Breakdown by agent\", \"Breakdown by tool\" → \"Agents\", \"Tools\"; after \"by\", the\n * rest names what each row is, so it reads as a plural. \"Agent latency\", \"Tool latency\" → \"Agent\",\n * \"Tool\"). Labels that share nothing, or that would shorten to the same name, stay as they are.\n */\nexport function shortViewLabels(labels: readonly string[]): string[] {\n const words = labels.map(label => label.split(/\\s+/));\n const leading = sharedWords(words);\n const trailing = sharedWords(reversed(words.map(w => w.slice(leading))));\n if (leading === 0 && trailing === 0) return [...labels];\n const byRows = words[0]?.[leading - 1]?.toLowerCase() === 'by';\n const names = words.map(w => {\n const rest = w.slice(leading, w.length - trailing);\n const last = rest.pop() ?? '';\n const name = [...rest, byRows ? plural(last) : last].join(' ');\n return name.charAt(0).toUpperCase() + name.slice(1);\n });\n // Two views that shorten to the same name (\"by team\", \"by teams\") keep their labels, to tell apart.\n return new Set(names).size === names.length ? names : [...labels];\n}\n"],"mappings":";;AACA,IAAM,UAAU,SAAiB;CAC/B,IAAI,MAAM,KAAK,IAAI,GAAG,OAAO;CAC7B,IAAI,cAAc,KAAK,IAAI,GAAG,OAAO,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE;CAC1D,IAAI,gBAAgB,KAAK,IAAI,GAAG,OAAO,GAAG,KAAK;CAC/C,OAAO,GAAG,KAAK;AACjB;;AAGA,SAAS,YAAY,OAAoC;CACvD,MAAM,CAAC,QAAQ,CAAC,KAAK;CACrB,IAAI,SAAS;CACb,OAAO,MAAM,SAAS,KAAK,MAAM,OAAM,MAAK,EAAE,SAAS,SAAS,KAAK,EAAE,YAAY,MAAM,OAAO,GAAG;CACnG,OAAO;AACT;AAEA,IAAM,YAAY,UAA+B,MAAM,KAAI,MAAK,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;;;;;;;AAQhF,SAAgB,gBAAgB,QAAqC;CACnE,MAAM,QAAQ,OAAO,KAAI,UAAS,MAAM,MAAM,KAAK,CAAC;CACpD,MAAM,UAAU,YAAY,KAAK;CACjC,MAAM,WAAW,YAAY,SAAS,MAAM,KAAI,MAAK,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC;CACvE,IAAI,YAAY,KAAK,aAAa,GAAG,OAAO,CAAC,GAAG,MAAM;CACtD,MAAM,SAAS,MAAM,EAAE,GAAG,UAAU,EAAE,EAAE,YAAY,MAAM;CAC1D,MAAM,QAAQ,MAAM,KAAI,MAAK;EAC3B,MAAM,OAAO,EAAE,MAAM,SAAS,EAAE,SAAS,QAAQ;EACjD,MAAM,OAAO,KAAK,IAAI,KAAK;EAC3B,MAAM,OAAO,CAAC,GAAG,MAAM,SAAS,OAAO,IAAI,IAAI,IAAI,CAAC,CAAC,KAAK,GAAG;EAC7D,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC;CACpD,CAAC;CAED,OAAO,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM,SAAS,QAAQ,CAAC,GAAG,MAAM;AAClE"}
@@ -113,7 +113,7 @@ var failedAgentRuns = [{
113
113
  fieldId: "status",
114
114
  value: "error"
115
115
  }];
116
- /** Agent runs, with Failure rate in its title menu, as the Agent runs card. */
116
+ /** Agent runs, with Failure rate as its second tab, as the Agent runs card. */
117
117
  var agentRunsWidget = {
118
118
  id: "agent-runs",
119
119
  span: 6,
@@ -1 +1 @@
1
- {"version":3,"file":"metrics-dashboard.cjs.js","names":[],"sources":["../../../src/domains/dashboards/metrics-dashboard.ts"],"sourcesContent":["import type {\n DashboardColumn,\n DashboardDefinition,\n DashboardDrilldownTarget,\n DashboardQuery,\n DashboardWidget,\n DashboardWidgetView,\n} from '@mastra/client-js';\n\nconst INPUT = 'mastra_model_total_input_tokens';\nconst OUTPUT = 'mastra_model_total_output_tokens';\nconst CACHE_READ = 'mastra_model_input_cache_read_tokens';\nconst AGENT_DURATION = 'mastra_agent_duration_ms';\n\nconst sumSeries = (id: string, name: string): DashboardQuery => ({\n id,\n source: 'metrics',\n request: 'timeSeries',\n name: [name],\n aggregation: 'sum',\n});\n\nconst agentRunsByStatus: DashboardQuery = {\n id: 'runs',\n source: 'metrics',\n request: 'timeSeries',\n name: [AGENT_DURATION],\n aggregation: 'count',\n groupBy: ['status'],\n};\n\n// Runs report status `ok` or `error` (observability/mastra auto-extract); the card also counts `failed`.\nconst FAILED = ['error', 'failed'];\nconst completedRuns = { query: 'runs', notGroups: FAILED };\nconst failedRuns = { query: 'runs', groups: FAILED };\nconst agentRunsTraces: DashboardDrilldownTarget = {\n page: 'traces',\n filters: [{ fieldId: 'rootEntityType', value: 'agent' }],\n};\n\nconst tokenUsageWidget: DashboardWidget = {\n id: 'token-usage',\n span: 6,\n kind: 'timeseries',\n title: 'Token usage',\n drilldown: { action: { page: 'traces' }, click: { page: 'traces' } },\n views: [\n {\n label: 'Token usage',\n description: 'Input, cache reads and output.',\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'count',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'input',\n label: 'Input',\n color: 'green',\n value: { max: [{ minus: [{ query: 'input' }, { query: 'cacheRead' }] }, { const: 0 }] },\n },\n { dataKey: 'cacheRead', label: 'Cache read', color: 'violet', value: { query: 'cacheRead' } },\n { dataKey: 'output', label: 'Output', color: 'sky', value: { query: 'output' } },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Model cost',\n description: 'Estimated model spend.',\n // Cache reads aren't charted here, but fetching them keeps their answer, so going back to\n // Token usage sends nothing, as the card's one request for both views does.\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'usd',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'cost',\n label: 'Cost',\n color: 'green',\n value: {\n sum: [\n { query: 'input', field: 'estimatedCost' },\n { query: 'output', field: 'estimatedCost' },\n ],\n },\n },\n ],\n total: { value: 'total' },\n },\n },\n ],\n};\n\nconst failedAgentRuns = [\n { fieldId: 'rootEntityType', value: 'agent' },\n { fieldId: 'status', value: 'error' },\n];\n\n/** Agent runs, with Failure rate in its title menu, as the Agent runs card. */\nconst agentRunsWidget: DashboardWidget = {\n id: 'agent-runs',\n span: 6,\n kind: 'timeseries',\n title: 'Agent runs',\n views: [\n {\n label: 'Agent runs',\n description: 'Completed and failed runs.',\n drilldown: { click: agentRunsTraces },\n queries: [agentRunsByStatus],\n options: {\n chart: 'stackedBar',\n format: 'count',\n axis: false,\n xLabels: 'edges',\n series: [\n { dataKey: 'completed', label: 'Completed', color: 'green', value: completedRuns },\n { dataKey: 'failed', label: 'Failed', color: 'error', value: failedRuns },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Failure rate',\n description: 'Share of agent runs that failed.',\n drilldown: {\n action: { page: 'logs', filters: failedAgentRuns },\n click: { page: 'traces', filters: failedAgentRuns },\n },\n queries: [agentRunsByStatus],\n options: {\n chart: 'line',\n format: 'percent',\n xLabels: 'edges',\n flatYDomain: [0, 1],\n series: [\n {\n dataKey: 'failureRate',\n label: 'Failed runs',\n color: 'error',\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n ],\n total: {\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n emptyWhenZero: { sum: [completedRuns, failedRuns] },\n },\n },\n ],\n};\n\nconst latencyView = (label: string, metric: string, rootEntityType: string): DashboardWidgetView => ({\n label,\n queries: [\n {\n id: 'latency',\n source: 'metrics',\n request: 'percentiles',\n name: metric,\n percentiles: [0.5, 0.95, 0.99],\n } satisfies DashboardQuery,\n ],\n drilldown: { action: { page: 'traces', filters: [{ fieldId: 'rootEntityType', value: rootEntityType }] } },\n options: {\n chart: 'line',\n format: 'duration',\n buckets: 'api',\n xLabels: 'edges',\n series: [\n { dataKey: 'p50', label: 'P50', color: 'sky', value: { query: 'latency', percentile: 0.5 }, round: true },\n {\n dataKey: 'p95',\n label: 'P95',\n color: 'green',\n emphasis: true,\n value: { query: 'latency', percentile: 0.95 },\n round: true,\n },\n { dataKey: 'p99', label: 'P99', color: 'violet', value: { query: 'latency', percentile: 0.99 }, round: true },\n ],\n total: { value: { peak: 'p95' } },\n },\n});\n\nconst latencyWidget: DashboardWidget = {\n id: 'latency',\n span: 6,\n kind: 'timeseries',\n title: 'Latency',\n description: 'Duration percentiles.',\n drilldown: { click: { page: 'traces' } },\n views: [\n latencyView('Agent latency', 'mastra_agent_duration_ms', 'agent'),\n latencyView('Workflow latency', 'mastra_workflow_duration_ms', 'workflow_run'),\n latencyView('Tool latency', 'mastra_tool_duration_ms', 'tool'),\n ],\n};\n\nconst DISTINCT_IDS = [\n ['countDistinct.resourceId', 'resources', 'Resources', 'sky'],\n ['countDistinct.threadId', 'threads', 'Threads', 'green'],\n ['countDistinct.userId', 'users', 'Users', 'violet'],\n ['countDistinct.sessionId', 'sessions', 'Sessions', 'teal'],\n] as const;\nconst distinctMeasures = DISTINCT_IDS.map(([measure]) => measure);\n\nconst distinctIdsWidget: DashboardWidget = {\n id: 'distinct-ids',\n span: 6,\n kind: 'timeseries',\n title: 'Resources and threads',\n description: 'Unique ids on traces; users and sessions only when set.',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n queries: [\n { id: 'buckets', source: 'traceAggregate', measures: distinctMeasures, limit: 10 },\n { id: 'totals', source: 'traceAggregate', measures: distinctMeasures },\n ],\n options: {\n chart: 'line',\n format: 'count',\n xLabels: 'edges',\n totals: ['totals'],\n hideEmpty: true,\n emphasizeFirst: true,\n series: DISTINCT_IDS.map(([measure, dataKey, label, color]) => ({\n dataKey,\n label,\n color,\n value: { query: 'buckets', measure },\n rangeTotal: { query: 'totals', measure },\n })),\n },\n },\n ],\n};\n\nconst USAGE = [INPUT, OUTPUT];\nconst TRACE_LIMIT = 1000;\nconst SPAN_LIMIT = 500;\ntype TraceMeasure = NonNullable<Extract<DashboardQuery, { source: 'traceAggregate' }>['measures']>[number];\ntype SpanMeasure = NonNullable<Extract<DashboardQuery, { source: 'spanAggregate' }>['measures']>[number];\nconst ERRORS: TraceMeasure[] = ['count', 'errorRate', 'duration.p95'];\n/** Traces with a thread. */\nconst hasThread = { op: 'exists', path: 'threadId' } as const;\n\nconst usageTotals = (groupBy: string[], filters?: Record<string, string>): DashboardQuery => ({\n id: 'usage',\n source: 'metrics',\n request: 'breakdown',\n name: USAGE,\n groupBy,\n aggregation: 'sum',\n orderDirection: 'DESC',\n limit: 1000,\n ...(filters ? { filters } : {}),\n compare: 'previousWindow',\n});\n\nconst TRACE_DESCRIPTION = 'A trace is one end-to-end request, with every step it took.';\nconst SPAN_DESCRIPTION =\n 'A span is one step inside a trace, such as a tool call or a model call. One trace can have many.';\n\nconst nameColumn = (label: string, options: Record<string, unknown> = {}): DashboardColumn => ({\n id: 'name',\n label,\n options: { type: 'name', width: 'minmax(12rem,3fr)', ...options },\n});\nconst projectColumn: DashboardColumn = {\n id: 'project',\n label: 'Project',\n scope: 'org',\n options: { type: 'dimension', dimension: 'projectId', as: 'project', width: 'minmax(8rem,2fr)' },\n};\nconst errorColumns: DashboardColumn[] = [\n {\n id: 'errorRate',\n label: 'Errors',\n options: { type: 'value', value: { query: 'figures', measure: 'errorRate' }, format: 'percent', better: 'lower' },\n },\n {\n id: 'p95',\n label: 'P95 latency',\n options: {\n type: 'value',\n value: { query: 'figures', measure: 'duration.p95' },\n format: 'duration',\n better: 'lower',\n },\n },\n];\nconst usageColumns: DashboardColumn[] = [\n {\n id: 'tokens',\n label: 'Tokens',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'value' },\n format: 'count',\n missing: 0,\n additive: true,\n better: 'lower',\n },\n },\n {\n id: 'cost',\n label: 'Cost',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'estimatedCost' },\n format: 'usd',\n additive: true,\n better: 'lower',\n unpricedWhen: 'tokens',\n },\n },\n];\nconst countColumn = (count: { label: string; value: Record<string, unknown>; spans: boolean }): DashboardColumn => ({\n id: 'count',\n label: count.label,\n options: {\n type: 'value',\n value: count.value,\n format: 'count',\n emphasis: true,\n missing: 0,\n additive: true,\n better: 'higher',\n description: count.spans ? SPAN_DESCRIPTION : TRACE_DESCRIPTION,\n },\n});\nconst changeColumn: DashboardColumn = { id: 'change', label: '% Change', options: { type: 'change' } };\nconst TRACES = { label: 'Traces', value: { query: 'figures', measure: 'count' }, spans: false };\n\nconst tableOptions = (groupBy: string[], name: string, emptyMessage: string, extra: Record<string, unknown> = {}) => ({\n groupBy,\n defaultSort: { column: 'count', direction: 'desc' },\n pageSize: 10,\n emptyMessage,\n ariaLabel: `${name} breakdown`,\n ...extra,\n});\n\n/** Row clicks open traces in the row's project, plus the row's own name as `field`. */\nconst drill = (scope: 'org' | 'project', name: string, field: string, extra: Record<string, unknown> = {}) => ({\n rowDrilldown: { fields: { ...(scope === 'org' ? { projectId: 'projectId' } : {}), [name]: field }, ...extra },\n});\n\nconst scoped = (scope: 'org' | 'project', dimension: string) =>\n scope === 'org' ? ['projectId', dimension] : [dimension];\n\nconst ENTITIES = {\n Agents: { name: 'Agent', icon: 'agent', spanTypes: ['agent_run'] },\n Workflows: { name: 'Workflow', icon: 'workflow', spanTypes: ['workflow_run'] },\n Tools: { name: 'Tool', icon: 'tool', spanTypes: ['tool_call', 'mcp_tool_call'] },\n} as const;\n\n/** An entity's figures; agents and workflows count the traces they ran in, tools every call. */\nconst spanMeasures = (traces: boolean): SpanMeasure[] => [\n 'count',\n ...(traces ? (['countDistinct.traceId'] as const) : []),\n 'errorCount',\n 'errorRate',\n 'duration.p95',\n];\n\nconst entityView = (\n scope: 'org' | 'project',\n label: keyof typeof ENTITIES,\n description: string,\n emptyMessage: string,\n): DashboardWidgetView => {\n const { name, icon, spanTypes } = ENTITIES[label];\n const groupBy = scoped(scope, 'entityName');\n const usage = label === 'Agents';\n const traces = label !== 'Tools';\n return {\n label: `Breakdown by ${name.toLowerCase()}`,\n scope,\n description,\n queries: [\n {\n id: 'figures',\n source: 'spanAggregate',\n where:\n spanTypes.length === 1\n ? { op: 'eq', left: { path: 'spanType' }, right: { literal: spanTypes[0] } }\n : { op: 'in', value: { path: 'spanType' }, set: [...spanTypes] },\n groupBy,\n measures: spanMeasures(traces),\n limit: SPAN_LIMIT,\n compare: 'previousWindow',\n },\n ...(usage ? [usageTotals(groupBy, { entityType: 'agent' })] : []),\n ],\n columns: [\n nameColumn(name, { mark: { icon } }),\n projectColumn,\n ...errorColumns,\n ...(usage ? usageColumns : []),\n countColumn(\n traces\n ? { label: 'Traces', value: { query: 'figures', measure: 'countDistinct.traceId' }, spans: false }\n : { label: 'Spans', value: { query: 'figures', measure: 'count' }, spans: true },\n ),\n changeColumn,\n ],\n options: tableOptions(\n groupBy,\n name,\n emptyMessage,\n drill(scope, 'entityName', 'entityName', { spanTypes, keepEmpty: true }),\n ),\n };\n};\n\nconst traceColumns = (\n name: string,\n options: Record<string, unknown> = {},\n extra: DashboardColumn[] = [],\n): DashboardColumn[] => [\n nameColumn(name, options),\n projectColumn,\n ...extra,\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n];\n\nconst environmentsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'environment');\n return {\n label: 'Breakdown by environment',\n scope,\n description: 'Traces, errors, latency and spend per environment.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy,\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: traceColumns('Environment', { unnamed: 'No environment' }),\n options: tableOptions(\n groupBy,\n 'Environment',\n 'No traces in this range.',\n drill(scope, 'environment', 'environment'),\n ),\n };\n};\n\nconst threadsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'threadId');\n const threads: DashboardQuery = {\n id: 'figures',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: scope === 'org' ? ['projectId', 'threadId'] : ['resourceId', 'threadId'],\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n };\n // Org-wide the second dimension is the project, so a third request names each thread's resource.\n const resources: DashboardQuery = {\n id: 'resources',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: ['resourceId', 'threadId'],\n measures: ['count'],\n limit: TRACE_LIMIT,\n };\n const resourceColumn: DashboardColumn = {\n id: 'resource',\n label: 'Resource',\n options: {\n type: 'dimension',\n dimension: 'resourceId',\n query: scope === 'org' ? 'resources' : 'figures',\n joinOn: 'threadId',\n width: 'minmax(6rem,1fr)',\n },\n };\n return {\n label: 'Breakdown by thread',\n scope,\n description: 'Traces, errors, latency and spend per thread.',\n queries: [threads, usageTotals(groupBy), ...(scope === 'org' ? [resources] : [])],\n columns: traceColumns('Thread', {}, [resourceColumn]),\n options: tableOptions(groupBy, 'Thread', 'No traces with a thread in this range.', {\n hideUnnamed: true,\n dropped: false,\n ...drill(scope, 'threadId', 'threadId', { keepEmpty: true }),\n }),\n };\n};\n\nconst modelsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'provider').concat('model');\n return {\n label: 'Breakdown by model',\n scope,\n description: 'Model calls, tokens and spend per model.',\n queries: [\n {\n id: 'calls',\n source: 'metrics',\n request: 'breakdown',\n name: [INPUT],\n groupBy,\n aggregation: 'count',\n orderDirection: 'DESC',\n limit: 1000,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: [\n nameColumn('Model', { unnamed: 'Unknown model', mark: { providerDimension: 'provider' } }),\n projectColumn,\n ...usageColumns,\n countColumn({ label: 'Spans', value: { query: 'calls', field: 'value' }, spans: true }),\n changeColumn,\n ],\n options: tableOptions(groupBy, 'Model', 'No model usage in this range.', drill(scope, 'model', 'model')),\n };\n};\n\nconst scopedViews = (scope: 'org' | 'project'): DashboardWidgetView[] => [\n entityView(\n scope,\n 'Agents',\n 'Traces each agent ran in, nested runs included, with errors, latency and spend.',\n 'No agent runs in this range.',\n ),\n entityView(\n scope,\n 'Workflows',\n 'Traces each workflow ran in, nested runs included, with errors and latency.',\n 'No workflow runs in this range.',\n ),\n entityView(\n scope,\n 'Tools',\n 'Every tool call, MCP tools included, with errors and latency.',\n 'No tool calls in this range.',\n ),\n modelsView(scope),\n threadsView(scope),\n environmentsView(scope),\n];\n\nconst breakdownWidget: DashboardWidget = {\n id: 'breakdown',\n span: 12,\n kind: 'table',\n title: 'Breakdown',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n label: 'Breakdown by project',\n scope: 'org',\n description: 'Traces, errors, latency and spend per project.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy: ['projectId'],\n measures: [...ERRORS, 'countDistinct.resourceId', 'countDistinct.threadId'],\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(['projectId']),\n ],\n columns: [\n nameColumn('Project', { as: 'project' }),\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n ],\n options: tableOptions(['projectId'], 'Project', 'No traces in this range.', {\n openWhen: { minRows: 2 },\n rowDrilldown: { fields: { projectId: 'projectId' } },\n }),\n },\n ...scopedViews('org'),\n ...scopedViews('project'),\n ],\n};\n\n/** Freezes a value and everything it holds, so a shared definition can't be edited in place. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The Metrics page as a dashboard: four charts in two rows (usage and health first), then the\n * breakdown of who caused them. Org and project pages share it; scope-tagged parts pick per page.\n * It is frozen: copy it (`structuredClone(METRICS_DASHBOARD)`) before customising.\n */\nexport const METRICS_DASHBOARD: DashboardDefinition = deepFreeze({\n schemaVersion: 1,\n rows: [\n { widgets: [tokenUsageWidget, agentRunsWidget] },\n { widgets: [latencyWidget, distinctIdsWidget] },\n { widgets: [breakdownWidget] },\n ],\n});\n"],"mappings":";;AASA,IAAM,QAAQ;AACd,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,aAAa,IAAY,UAAkC;CAC/D;CACA,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,IAAI;CACX,aAAa;AACf;AAEA,IAAM,oBAAoC;CACxC,IAAI;CACJ,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,cAAc;CACrB,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ACE,IAAI;IACJ,QAAQ;IACR,SAAS,CAAC,WAAW;IACrB,UAAU;KAAC,GAAG;KAAQ;KAA4B;IAAwB;IAC1E,OAAO;IACP,SAAS;GACX,GACA,YAAY,CAAC,WAAW,CAAC,CAC3B;GACA,SAAS;IACP,WAAW,WAAW,EAAE,IAAI,UAAU,CAAC;IACvC,GAAG;IACH,GAAG;IACH,YAAY,MAAM;IAClB;GACF;GACA,SAAS,aAAa,CAAC,WAAW,GAAG,WAAW,4BAA4B;IAC1E,UAAU,EAAE,SAAS,EAAE;IACvB,cAAc,EAAE,QAAQ,EAAE,WAAW,YAAY,EAAE;GACrD,CAAC;EACH;EACA,GAAG,YAAY,KAAK;EACpB,GAAG,YAAY,SAAS;CAC1B;AACF;;AAGA,SAAS,WAAc,OAAa;CAClC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;EACjE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,WAAW,KAAK;EAC1D,OAAO,OAAO,KAAK;CACrB;CACA,OAAO;AACT;;;;;;AAOA,IAAa,oBAAyC,WAAW;CAC/D,eAAe;CACf,MAAM;EACJ,EAAE,SAAS,CAAC,kBAAkB,eAAe,EAAE;EAC/C,EAAE,SAAS,CAAC,eAAe,iBAAiB,EAAE;EAC9C,EAAE,SAAS,CAAC,eAAe,EAAE;CAC/B;AACF,CAAC"}
1
+ {"version":3,"file":"metrics-dashboard.cjs.js","names":[],"sources":["../../../src/domains/dashboards/metrics-dashboard.ts"],"sourcesContent":["import type {\n DashboardColumn,\n DashboardDefinition,\n DashboardDrilldownTarget,\n DashboardQuery,\n DashboardWidget,\n DashboardWidgetView,\n} from '@mastra/client-js';\n\nconst INPUT = 'mastra_model_total_input_tokens';\nconst OUTPUT = 'mastra_model_total_output_tokens';\nconst CACHE_READ = 'mastra_model_input_cache_read_tokens';\nconst AGENT_DURATION = 'mastra_agent_duration_ms';\n\nconst sumSeries = (id: string, name: string): DashboardQuery => ({\n id,\n source: 'metrics',\n request: 'timeSeries',\n name: [name],\n aggregation: 'sum',\n});\n\nconst agentRunsByStatus: DashboardQuery = {\n id: 'runs',\n source: 'metrics',\n request: 'timeSeries',\n name: [AGENT_DURATION],\n aggregation: 'count',\n groupBy: ['status'],\n};\n\n// Runs report status `ok` or `error` (observability/mastra auto-extract); the card also counts `failed`.\nconst FAILED = ['error', 'failed'];\nconst completedRuns = { query: 'runs', notGroups: FAILED };\nconst failedRuns = { query: 'runs', groups: FAILED };\nconst agentRunsTraces: DashboardDrilldownTarget = {\n page: 'traces',\n filters: [{ fieldId: 'rootEntityType', value: 'agent' }],\n};\n\nconst tokenUsageWidget: DashboardWidget = {\n id: 'token-usage',\n span: 6,\n kind: 'timeseries',\n title: 'Token usage',\n drilldown: { action: { page: 'traces' }, click: { page: 'traces' } },\n views: [\n {\n label: 'Token usage',\n description: 'Input, cache reads and output.',\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'count',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'input',\n label: 'Input',\n color: 'green',\n value: { max: [{ minus: [{ query: 'input' }, { query: 'cacheRead' }] }, { const: 0 }] },\n },\n { dataKey: 'cacheRead', label: 'Cache read', color: 'violet', value: { query: 'cacheRead' } },\n { dataKey: 'output', label: 'Output', color: 'sky', value: { query: 'output' } },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Model cost',\n description: 'Estimated model spend.',\n // Cache reads aren't charted here, but fetching them keeps their answer, so going back to\n // Token usage sends nothing, as the card's one request for both views does.\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'usd',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'cost',\n label: 'Cost',\n color: 'green',\n value: {\n sum: [\n { query: 'input', field: 'estimatedCost' },\n { query: 'output', field: 'estimatedCost' },\n ],\n },\n },\n ],\n total: { value: 'total' },\n },\n },\n ],\n};\n\nconst failedAgentRuns = [\n { fieldId: 'rootEntityType', value: 'agent' },\n { fieldId: 'status', value: 'error' },\n];\n\n/** Agent runs, with Failure rate as its second tab, as the Agent runs card. */\nconst agentRunsWidget: DashboardWidget = {\n id: 'agent-runs',\n span: 6,\n kind: 'timeseries',\n title: 'Agent runs',\n views: [\n {\n label: 'Agent runs',\n description: 'Completed and failed runs.',\n drilldown: { click: agentRunsTraces },\n queries: [agentRunsByStatus],\n options: {\n chart: 'stackedBar',\n format: 'count',\n axis: false,\n xLabels: 'edges',\n series: [\n { dataKey: 'completed', label: 'Completed', color: 'green', value: completedRuns },\n { dataKey: 'failed', label: 'Failed', color: 'error', value: failedRuns },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Failure rate',\n description: 'Share of agent runs that failed.',\n drilldown: {\n action: { page: 'logs', filters: failedAgentRuns },\n click: { page: 'traces', filters: failedAgentRuns },\n },\n queries: [agentRunsByStatus],\n options: {\n chart: 'line',\n format: 'percent',\n xLabels: 'edges',\n flatYDomain: [0, 1],\n series: [\n {\n dataKey: 'failureRate',\n label: 'Failed runs',\n color: 'error',\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n ],\n total: {\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n emptyWhenZero: { sum: [completedRuns, failedRuns] },\n },\n },\n ],\n};\n\nconst latencyView = (label: string, metric: string, rootEntityType: string): DashboardWidgetView => ({\n label,\n queries: [\n {\n id: 'latency',\n source: 'metrics',\n request: 'percentiles',\n name: metric,\n percentiles: [0.5, 0.95, 0.99],\n } satisfies DashboardQuery,\n ],\n drilldown: { action: { page: 'traces', filters: [{ fieldId: 'rootEntityType', value: rootEntityType }] } },\n options: {\n chart: 'line',\n format: 'duration',\n buckets: 'api',\n xLabels: 'edges',\n series: [\n { dataKey: 'p50', label: 'P50', color: 'sky', value: { query: 'latency', percentile: 0.5 }, round: true },\n {\n dataKey: 'p95',\n label: 'P95',\n color: 'green',\n emphasis: true,\n value: { query: 'latency', percentile: 0.95 },\n round: true,\n },\n { dataKey: 'p99', label: 'P99', color: 'violet', value: { query: 'latency', percentile: 0.99 }, round: true },\n ],\n total: { value: { peak: 'p95' } },\n },\n});\n\nconst latencyWidget: DashboardWidget = {\n id: 'latency',\n span: 6,\n kind: 'timeseries',\n title: 'Latency',\n description: 'Duration percentiles.',\n drilldown: { click: { page: 'traces' } },\n views: [\n latencyView('Agent latency', 'mastra_agent_duration_ms', 'agent'),\n latencyView('Workflow latency', 'mastra_workflow_duration_ms', 'workflow_run'),\n latencyView('Tool latency', 'mastra_tool_duration_ms', 'tool'),\n ],\n};\n\nconst DISTINCT_IDS = [\n ['countDistinct.resourceId', 'resources', 'Resources', 'sky'],\n ['countDistinct.threadId', 'threads', 'Threads', 'green'],\n ['countDistinct.userId', 'users', 'Users', 'violet'],\n ['countDistinct.sessionId', 'sessions', 'Sessions', 'teal'],\n] as const;\nconst distinctMeasures = DISTINCT_IDS.map(([measure]) => measure);\n\nconst distinctIdsWidget: DashboardWidget = {\n id: 'distinct-ids',\n span: 6,\n kind: 'timeseries',\n title: 'Resources and threads',\n description: 'Unique ids on traces; users and sessions only when set.',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n queries: [\n { id: 'buckets', source: 'traceAggregate', measures: distinctMeasures, limit: 10 },\n { id: 'totals', source: 'traceAggregate', measures: distinctMeasures },\n ],\n options: {\n chart: 'line',\n format: 'count',\n xLabels: 'edges',\n totals: ['totals'],\n hideEmpty: true,\n emphasizeFirst: true,\n series: DISTINCT_IDS.map(([measure, dataKey, label, color]) => ({\n dataKey,\n label,\n color,\n value: { query: 'buckets', measure },\n rangeTotal: { query: 'totals', measure },\n })),\n },\n },\n ],\n};\n\nconst USAGE = [INPUT, OUTPUT];\nconst TRACE_LIMIT = 1000;\nconst SPAN_LIMIT = 500;\ntype TraceMeasure = NonNullable<Extract<DashboardQuery, { source: 'traceAggregate' }>['measures']>[number];\ntype SpanMeasure = NonNullable<Extract<DashboardQuery, { source: 'spanAggregate' }>['measures']>[number];\nconst ERRORS: TraceMeasure[] = ['count', 'errorRate', 'duration.p95'];\n/** Traces with a thread. */\nconst hasThread = { op: 'exists', path: 'threadId' } as const;\n\nconst usageTotals = (groupBy: string[], filters?: Record<string, string>): DashboardQuery => ({\n id: 'usage',\n source: 'metrics',\n request: 'breakdown',\n name: USAGE,\n groupBy,\n aggregation: 'sum',\n orderDirection: 'DESC',\n limit: 1000,\n ...(filters ? { filters } : {}),\n compare: 'previousWindow',\n});\n\nconst TRACE_DESCRIPTION = 'A trace is one end-to-end request, with every step it took.';\nconst SPAN_DESCRIPTION =\n 'A span is one step inside a trace, such as a tool call or a model call. One trace can have many.';\n\nconst nameColumn = (label: string, options: Record<string, unknown> = {}): DashboardColumn => ({\n id: 'name',\n label,\n options: { type: 'name', width: 'minmax(12rem,3fr)', ...options },\n});\nconst projectColumn: DashboardColumn = {\n id: 'project',\n label: 'Project',\n scope: 'org',\n options: { type: 'dimension', dimension: 'projectId', as: 'project', width: 'minmax(8rem,2fr)' },\n};\nconst errorColumns: DashboardColumn[] = [\n {\n id: 'errorRate',\n label: 'Errors',\n options: { type: 'value', value: { query: 'figures', measure: 'errorRate' }, format: 'percent', better: 'lower' },\n },\n {\n id: 'p95',\n label: 'P95 latency',\n options: {\n type: 'value',\n value: { query: 'figures', measure: 'duration.p95' },\n format: 'duration',\n better: 'lower',\n },\n },\n];\nconst usageColumns: DashboardColumn[] = [\n {\n id: 'tokens',\n label: 'Tokens',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'value' },\n format: 'count',\n missing: 0,\n additive: true,\n better: 'lower',\n },\n },\n {\n id: 'cost',\n label: 'Cost',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'estimatedCost' },\n format: 'usd',\n additive: true,\n better: 'lower',\n unpricedWhen: 'tokens',\n },\n },\n];\nconst countColumn = (count: { label: string; value: Record<string, unknown>; spans: boolean }): DashboardColumn => ({\n id: 'count',\n label: count.label,\n options: {\n type: 'value',\n value: count.value,\n format: 'count',\n emphasis: true,\n missing: 0,\n additive: true,\n better: 'higher',\n description: count.spans ? SPAN_DESCRIPTION : TRACE_DESCRIPTION,\n },\n});\nconst changeColumn: DashboardColumn = { id: 'change', label: '% Change', options: { type: 'change' } };\nconst TRACES = { label: 'Traces', value: { query: 'figures', measure: 'count' }, spans: false };\n\nconst tableOptions = (groupBy: string[], name: string, emptyMessage: string, extra: Record<string, unknown> = {}) => ({\n groupBy,\n defaultSort: { column: 'count', direction: 'desc' },\n pageSize: 10,\n emptyMessage,\n ariaLabel: `${name} breakdown`,\n ...extra,\n});\n\n/** Row clicks open traces in the row's project, plus the row's own name as `field`. */\nconst drill = (scope: 'org' | 'project', name: string, field: string, extra: Record<string, unknown> = {}) => ({\n rowDrilldown: { fields: { ...(scope === 'org' ? { projectId: 'projectId' } : {}), [name]: field }, ...extra },\n});\n\nconst scoped = (scope: 'org' | 'project', dimension: string) =>\n scope === 'org' ? ['projectId', dimension] : [dimension];\n\nconst ENTITIES = {\n Agents: { name: 'Agent', icon: 'agent', spanTypes: ['agent_run'] },\n Workflows: { name: 'Workflow', icon: 'workflow', spanTypes: ['workflow_run'] },\n Tools: { name: 'Tool', icon: 'tool', spanTypes: ['tool_call', 'mcp_tool_call'] },\n} as const;\n\n/** An entity's figures; agents and workflows count the traces they ran in, tools every call. */\nconst spanMeasures = (traces: boolean): SpanMeasure[] => [\n 'count',\n ...(traces ? (['countDistinct.traceId'] as const) : []),\n 'errorCount',\n 'errorRate',\n 'duration.p95',\n];\n\nconst entityView = (\n scope: 'org' | 'project',\n label: keyof typeof ENTITIES,\n description: string,\n emptyMessage: string,\n): DashboardWidgetView => {\n const { name, icon, spanTypes } = ENTITIES[label];\n const groupBy = scoped(scope, 'entityName');\n const usage = label === 'Agents';\n const traces = label !== 'Tools';\n return {\n label: `Breakdown by ${name.toLowerCase()}`,\n scope,\n description,\n queries: [\n {\n id: 'figures',\n source: 'spanAggregate',\n where:\n spanTypes.length === 1\n ? { op: 'eq', left: { path: 'spanType' }, right: { literal: spanTypes[0] } }\n : { op: 'in', value: { path: 'spanType' }, set: [...spanTypes] },\n groupBy,\n measures: spanMeasures(traces),\n limit: SPAN_LIMIT,\n compare: 'previousWindow',\n },\n ...(usage ? [usageTotals(groupBy, { entityType: 'agent' })] : []),\n ],\n columns: [\n nameColumn(name, { mark: { icon } }),\n projectColumn,\n ...errorColumns,\n ...(usage ? usageColumns : []),\n countColumn(\n traces\n ? { label: 'Traces', value: { query: 'figures', measure: 'countDistinct.traceId' }, spans: false }\n : { label: 'Spans', value: { query: 'figures', measure: 'count' }, spans: true },\n ),\n changeColumn,\n ],\n options: tableOptions(\n groupBy,\n name,\n emptyMessage,\n drill(scope, 'entityName', 'entityName', { spanTypes, keepEmpty: true }),\n ),\n };\n};\n\nconst traceColumns = (\n name: string,\n options: Record<string, unknown> = {},\n extra: DashboardColumn[] = [],\n): DashboardColumn[] => [\n nameColumn(name, options),\n projectColumn,\n ...extra,\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n];\n\nconst environmentsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'environment');\n return {\n label: 'Breakdown by environment',\n scope,\n description: 'Traces, errors, latency and spend per environment.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy,\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: traceColumns('Environment', { unnamed: 'No environment' }),\n options: tableOptions(\n groupBy,\n 'Environment',\n 'No traces in this range.',\n drill(scope, 'environment', 'environment'),\n ),\n };\n};\n\nconst threadsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'threadId');\n const threads: DashboardQuery = {\n id: 'figures',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: scope === 'org' ? ['projectId', 'threadId'] : ['resourceId', 'threadId'],\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n };\n // Org-wide the second dimension is the project, so a third request names each thread's resource.\n const resources: DashboardQuery = {\n id: 'resources',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: ['resourceId', 'threadId'],\n measures: ['count'],\n limit: TRACE_LIMIT,\n };\n const resourceColumn: DashboardColumn = {\n id: 'resource',\n label: 'Resource',\n options: {\n type: 'dimension',\n dimension: 'resourceId',\n query: scope === 'org' ? 'resources' : 'figures',\n joinOn: 'threadId',\n width: 'minmax(6rem,1fr)',\n },\n };\n return {\n label: 'Breakdown by thread',\n scope,\n description: 'Traces, errors, latency and spend per thread.',\n queries: [threads, usageTotals(groupBy), ...(scope === 'org' ? [resources] : [])],\n columns: traceColumns('Thread', {}, [resourceColumn]),\n options: tableOptions(groupBy, 'Thread', 'No traces with a thread in this range.', {\n hideUnnamed: true,\n dropped: false,\n ...drill(scope, 'threadId', 'threadId', { keepEmpty: true }),\n }),\n };\n};\n\nconst modelsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'provider').concat('model');\n return {\n label: 'Breakdown by model',\n scope,\n description: 'Model calls, tokens and spend per model.',\n queries: [\n {\n id: 'calls',\n source: 'metrics',\n request: 'breakdown',\n name: [INPUT],\n groupBy,\n aggregation: 'count',\n orderDirection: 'DESC',\n limit: 1000,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: [\n nameColumn('Model', { unnamed: 'Unknown model', mark: { providerDimension: 'provider' } }),\n projectColumn,\n ...usageColumns,\n countColumn({ label: 'Spans', value: { query: 'calls', field: 'value' }, spans: true }),\n changeColumn,\n ],\n options: tableOptions(groupBy, 'Model', 'No model usage in this range.', drill(scope, 'model', 'model')),\n };\n};\n\nconst scopedViews = (scope: 'org' | 'project'): DashboardWidgetView[] => [\n entityView(\n scope,\n 'Agents',\n 'Traces each agent ran in, nested runs included, with errors, latency and spend.',\n 'No agent runs in this range.',\n ),\n entityView(\n scope,\n 'Workflows',\n 'Traces each workflow ran in, nested runs included, with errors and latency.',\n 'No workflow runs in this range.',\n ),\n entityView(\n scope,\n 'Tools',\n 'Every tool call, MCP tools included, with errors and latency.',\n 'No tool calls in this range.',\n ),\n modelsView(scope),\n threadsView(scope),\n environmentsView(scope),\n];\n\nconst breakdownWidget: DashboardWidget = {\n id: 'breakdown',\n span: 12,\n kind: 'table',\n title: 'Breakdown',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n label: 'Breakdown by project',\n scope: 'org',\n description: 'Traces, errors, latency and spend per project.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy: ['projectId'],\n measures: [...ERRORS, 'countDistinct.resourceId', 'countDistinct.threadId'],\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(['projectId']),\n ],\n columns: [\n nameColumn('Project', { as: 'project' }),\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n ],\n options: tableOptions(['projectId'], 'Project', 'No traces in this range.', {\n openWhen: { minRows: 2 },\n rowDrilldown: { fields: { projectId: 'projectId' } },\n }),\n },\n ...scopedViews('org'),\n ...scopedViews('project'),\n ],\n};\n\n/** Freezes a value and everything it holds, so a shared definition can't be edited in place. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The Metrics page as a dashboard: four charts in two rows (usage and health first), then the\n * breakdown of who caused them. Org and project pages share it; scope-tagged parts pick per page.\n * It is frozen: copy it (`structuredClone(METRICS_DASHBOARD)`) before customising.\n */\nexport const METRICS_DASHBOARD: DashboardDefinition = deepFreeze({\n schemaVersion: 1,\n rows: [\n { widgets: [tokenUsageWidget, agentRunsWidget] },\n { widgets: [latencyWidget, distinctIdsWidget] },\n { widgets: [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
115
- /** Agent runs, with Failure rate in its title menu, as the Agent runs card. */
115
+ /** Agent runs, with Failure rate as its second tab, as the Agent runs card. */
116
116
  var agentRunsWidget = {
117
117
  id: "agent-runs",
118
118
  span: 6,
@@ -1 +1 @@
1
- {"version":3,"file":"metrics-dashboard.es.js","names":[],"sources":["../../../src/domains/dashboards/metrics-dashboard.ts"],"sourcesContent":["import type {\n DashboardColumn,\n DashboardDefinition,\n DashboardDrilldownTarget,\n DashboardQuery,\n DashboardWidget,\n DashboardWidgetView,\n} from '@mastra/client-js';\n\nconst INPUT = 'mastra_model_total_input_tokens';\nconst OUTPUT = 'mastra_model_total_output_tokens';\nconst CACHE_READ = 'mastra_model_input_cache_read_tokens';\nconst AGENT_DURATION = 'mastra_agent_duration_ms';\n\nconst sumSeries = (id: string, name: string): DashboardQuery => ({\n id,\n source: 'metrics',\n request: 'timeSeries',\n name: [name],\n aggregation: 'sum',\n});\n\nconst agentRunsByStatus: DashboardQuery = {\n id: 'runs',\n source: 'metrics',\n request: 'timeSeries',\n name: [AGENT_DURATION],\n aggregation: 'count',\n groupBy: ['status'],\n};\n\n// Runs report status `ok` or `error` (observability/mastra auto-extract); the card also counts `failed`.\nconst FAILED = ['error', 'failed'];\nconst completedRuns = { query: 'runs', notGroups: FAILED };\nconst failedRuns = { query: 'runs', groups: FAILED };\nconst agentRunsTraces: DashboardDrilldownTarget = {\n page: 'traces',\n filters: [{ fieldId: 'rootEntityType', value: 'agent' }],\n};\n\nconst tokenUsageWidget: DashboardWidget = {\n id: 'token-usage',\n span: 6,\n kind: 'timeseries',\n title: 'Token usage',\n drilldown: { action: { page: 'traces' }, click: { page: 'traces' } },\n views: [\n {\n label: 'Token usage',\n description: 'Input, cache reads and output.',\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'count',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'input',\n label: 'Input',\n color: 'green',\n value: { max: [{ minus: [{ query: 'input' }, { query: 'cacheRead' }] }, { const: 0 }] },\n },\n { dataKey: 'cacheRead', label: 'Cache read', color: 'violet', value: { query: 'cacheRead' } },\n { dataKey: 'output', label: 'Output', color: 'sky', value: { query: 'output' } },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Model cost',\n description: 'Estimated model spend.',\n // Cache reads aren't charted here, but fetching them keeps their answer, so going back to\n // Token usage sends nothing, as the card's one request for both views does.\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'usd',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'cost',\n label: 'Cost',\n color: 'green',\n value: {\n sum: [\n { query: 'input', field: 'estimatedCost' },\n { query: 'output', field: 'estimatedCost' },\n ],\n },\n },\n ],\n total: { value: 'total' },\n },\n },\n ],\n};\n\nconst failedAgentRuns = [\n { fieldId: 'rootEntityType', value: 'agent' },\n { fieldId: 'status', value: 'error' },\n];\n\n/** Agent runs, with Failure rate in its title menu, as the Agent runs card. */\nconst agentRunsWidget: DashboardWidget = {\n id: 'agent-runs',\n span: 6,\n kind: 'timeseries',\n title: 'Agent runs',\n views: [\n {\n label: 'Agent runs',\n description: 'Completed and failed runs.',\n drilldown: { click: agentRunsTraces },\n queries: [agentRunsByStatus],\n options: {\n chart: 'stackedBar',\n format: 'count',\n axis: false,\n xLabels: 'edges',\n series: [\n { dataKey: 'completed', label: 'Completed', color: 'green', value: completedRuns },\n { dataKey: 'failed', label: 'Failed', color: 'error', value: failedRuns },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Failure rate',\n description: 'Share of agent runs that failed.',\n drilldown: {\n action: { page: 'logs', filters: failedAgentRuns },\n click: { page: 'traces', filters: failedAgentRuns },\n },\n queries: [agentRunsByStatus],\n options: {\n chart: 'line',\n format: 'percent',\n xLabels: 'edges',\n flatYDomain: [0, 1],\n series: [\n {\n dataKey: 'failureRate',\n label: 'Failed runs',\n color: 'error',\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n ],\n total: {\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n emptyWhenZero: { sum: [completedRuns, failedRuns] },\n },\n },\n ],\n};\n\nconst latencyView = (label: string, metric: string, rootEntityType: string): DashboardWidgetView => ({\n label,\n queries: [\n {\n id: 'latency',\n source: 'metrics',\n request: 'percentiles',\n name: metric,\n percentiles: [0.5, 0.95, 0.99],\n } satisfies DashboardQuery,\n ],\n drilldown: { action: { page: 'traces', filters: [{ fieldId: 'rootEntityType', value: rootEntityType }] } },\n options: {\n chart: 'line',\n format: 'duration',\n buckets: 'api',\n xLabels: 'edges',\n series: [\n { dataKey: 'p50', label: 'P50', color: 'sky', value: { query: 'latency', percentile: 0.5 }, round: true },\n {\n dataKey: 'p95',\n label: 'P95',\n color: 'green',\n emphasis: true,\n value: { query: 'latency', percentile: 0.95 },\n round: true,\n },\n { dataKey: 'p99', label: 'P99', color: 'violet', value: { query: 'latency', percentile: 0.99 }, round: true },\n ],\n total: { value: { peak: 'p95' } },\n },\n});\n\nconst latencyWidget: DashboardWidget = {\n id: 'latency',\n span: 6,\n kind: 'timeseries',\n title: 'Latency',\n description: 'Duration percentiles.',\n drilldown: { click: { page: 'traces' } },\n views: [\n latencyView('Agent latency', 'mastra_agent_duration_ms', 'agent'),\n latencyView('Workflow latency', 'mastra_workflow_duration_ms', 'workflow_run'),\n latencyView('Tool latency', 'mastra_tool_duration_ms', 'tool'),\n ],\n};\n\nconst DISTINCT_IDS = [\n ['countDistinct.resourceId', 'resources', 'Resources', 'sky'],\n ['countDistinct.threadId', 'threads', 'Threads', 'green'],\n ['countDistinct.userId', 'users', 'Users', 'violet'],\n ['countDistinct.sessionId', 'sessions', 'Sessions', 'teal'],\n] as const;\nconst distinctMeasures = DISTINCT_IDS.map(([measure]) => measure);\n\nconst distinctIdsWidget: DashboardWidget = {\n id: 'distinct-ids',\n span: 6,\n kind: 'timeseries',\n title: 'Resources and threads',\n description: 'Unique ids on traces; users and sessions only when set.',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n queries: [\n { id: 'buckets', source: 'traceAggregate', measures: distinctMeasures, limit: 10 },\n { id: 'totals', source: 'traceAggregate', measures: distinctMeasures },\n ],\n options: {\n chart: 'line',\n format: 'count',\n xLabels: 'edges',\n totals: ['totals'],\n hideEmpty: true,\n emphasizeFirst: true,\n series: DISTINCT_IDS.map(([measure, dataKey, label, color]) => ({\n dataKey,\n label,\n color,\n value: { query: 'buckets', measure },\n rangeTotal: { query: 'totals', measure },\n })),\n },\n },\n ],\n};\n\nconst USAGE = [INPUT, OUTPUT];\nconst TRACE_LIMIT = 1000;\nconst SPAN_LIMIT = 500;\ntype TraceMeasure = NonNullable<Extract<DashboardQuery, { source: 'traceAggregate' }>['measures']>[number];\ntype SpanMeasure = NonNullable<Extract<DashboardQuery, { source: 'spanAggregate' }>['measures']>[number];\nconst ERRORS: TraceMeasure[] = ['count', 'errorRate', 'duration.p95'];\n/** Traces with a thread. */\nconst hasThread = { op: 'exists', path: 'threadId' } as const;\n\nconst usageTotals = (groupBy: string[], filters?: Record<string, string>): DashboardQuery => ({\n id: 'usage',\n source: 'metrics',\n request: 'breakdown',\n name: USAGE,\n groupBy,\n aggregation: 'sum',\n orderDirection: 'DESC',\n limit: 1000,\n ...(filters ? { filters } : {}),\n compare: 'previousWindow',\n});\n\nconst TRACE_DESCRIPTION = 'A trace is one end-to-end request, with every step it took.';\nconst SPAN_DESCRIPTION =\n 'A span is one step inside a trace, such as a tool call or a model call. One trace can have many.';\n\nconst nameColumn = (label: string, options: Record<string, unknown> = {}): DashboardColumn => ({\n id: 'name',\n label,\n options: { type: 'name', width: 'minmax(12rem,3fr)', ...options },\n});\nconst projectColumn: DashboardColumn = {\n id: 'project',\n label: 'Project',\n scope: 'org',\n options: { type: 'dimension', dimension: 'projectId', as: 'project', width: 'minmax(8rem,2fr)' },\n};\nconst errorColumns: DashboardColumn[] = [\n {\n id: 'errorRate',\n label: 'Errors',\n options: { type: 'value', value: { query: 'figures', measure: 'errorRate' }, format: 'percent', better: 'lower' },\n },\n {\n id: 'p95',\n label: 'P95 latency',\n options: {\n type: 'value',\n value: { query: 'figures', measure: 'duration.p95' },\n format: 'duration',\n better: 'lower',\n },\n },\n];\nconst usageColumns: DashboardColumn[] = [\n {\n id: 'tokens',\n label: 'Tokens',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'value' },\n format: 'count',\n missing: 0,\n additive: true,\n better: 'lower',\n },\n },\n {\n id: 'cost',\n label: 'Cost',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'estimatedCost' },\n format: 'usd',\n additive: true,\n better: 'lower',\n unpricedWhen: 'tokens',\n },\n },\n];\nconst countColumn = (count: { label: string; value: Record<string, unknown>; spans: boolean }): DashboardColumn => ({\n id: 'count',\n label: count.label,\n options: {\n type: 'value',\n value: count.value,\n format: 'count',\n emphasis: true,\n missing: 0,\n additive: true,\n better: 'higher',\n description: count.spans ? SPAN_DESCRIPTION : TRACE_DESCRIPTION,\n },\n});\nconst changeColumn: DashboardColumn = { id: 'change', label: '% Change', options: { type: 'change' } };\nconst TRACES = { label: 'Traces', value: { query: 'figures', measure: 'count' }, spans: false };\n\nconst tableOptions = (groupBy: string[], name: string, emptyMessage: string, extra: Record<string, unknown> = {}) => ({\n groupBy,\n defaultSort: { column: 'count', direction: 'desc' },\n pageSize: 10,\n emptyMessage,\n ariaLabel: `${name} breakdown`,\n ...extra,\n});\n\n/** Row clicks open traces in the row's project, plus the row's own name as `field`. */\nconst drill = (scope: 'org' | 'project', name: string, field: string, extra: Record<string, unknown> = {}) => ({\n rowDrilldown: { fields: { ...(scope === 'org' ? { projectId: 'projectId' } : {}), [name]: field }, ...extra },\n});\n\nconst scoped = (scope: 'org' | 'project', dimension: string) =>\n scope === 'org' ? ['projectId', dimension] : [dimension];\n\nconst ENTITIES = {\n Agents: { name: 'Agent', icon: 'agent', spanTypes: ['agent_run'] },\n Workflows: { name: 'Workflow', icon: 'workflow', spanTypes: ['workflow_run'] },\n Tools: { name: 'Tool', icon: 'tool', spanTypes: ['tool_call', 'mcp_tool_call'] },\n} as const;\n\n/** An entity's figures; agents and workflows count the traces they ran in, tools every call. */\nconst spanMeasures = (traces: boolean): SpanMeasure[] => [\n 'count',\n ...(traces ? (['countDistinct.traceId'] as const) : []),\n 'errorCount',\n 'errorRate',\n 'duration.p95',\n];\n\nconst entityView = (\n scope: 'org' | 'project',\n label: keyof typeof ENTITIES,\n description: string,\n emptyMessage: string,\n): DashboardWidgetView => {\n const { name, icon, spanTypes } = ENTITIES[label];\n const groupBy = scoped(scope, 'entityName');\n const usage = label === 'Agents';\n const traces = label !== 'Tools';\n return {\n label: `Breakdown by ${name.toLowerCase()}`,\n scope,\n description,\n queries: [\n {\n id: 'figures',\n source: 'spanAggregate',\n where:\n spanTypes.length === 1\n ? { op: 'eq', left: { path: 'spanType' }, right: { literal: spanTypes[0] } }\n : { op: 'in', value: { path: 'spanType' }, set: [...spanTypes] },\n groupBy,\n measures: spanMeasures(traces),\n limit: SPAN_LIMIT,\n compare: 'previousWindow',\n },\n ...(usage ? [usageTotals(groupBy, { entityType: 'agent' })] : []),\n ],\n columns: [\n nameColumn(name, { mark: { icon } }),\n projectColumn,\n ...errorColumns,\n ...(usage ? usageColumns : []),\n countColumn(\n traces\n ? { label: 'Traces', value: { query: 'figures', measure: 'countDistinct.traceId' }, spans: false }\n : { label: 'Spans', value: { query: 'figures', measure: 'count' }, spans: true },\n ),\n changeColumn,\n ],\n options: tableOptions(\n groupBy,\n name,\n emptyMessage,\n drill(scope, 'entityName', 'entityName', { spanTypes, keepEmpty: true }),\n ),\n };\n};\n\nconst traceColumns = (\n name: string,\n options: Record<string, unknown> = {},\n extra: DashboardColumn[] = [],\n): DashboardColumn[] => [\n nameColumn(name, options),\n projectColumn,\n ...extra,\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n];\n\nconst environmentsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'environment');\n return {\n label: 'Breakdown by environment',\n scope,\n description: 'Traces, errors, latency and spend per environment.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy,\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: traceColumns('Environment', { unnamed: 'No environment' }),\n options: tableOptions(\n groupBy,\n 'Environment',\n 'No traces in this range.',\n drill(scope, 'environment', 'environment'),\n ),\n };\n};\n\nconst threadsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'threadId');\n const threads: DashboardQuery = {\n id: 'figures',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: scope === 'org' ? ['projectId', 'threadId'] : ['resourceId', 'threadId'],\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n };\n // Org-wide the second dimension is the project, so a third request names each thread's resource.\n const resources: DashboardQuery = {\n id: 'resources',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: ['resourceId', 'threadId'],\n measures: ['count'],\n limit: TRACE_LIMIT,\n };\n const resourceColumn: DashboardColumn = {\n id: 'resource',\n label: 'Resource',\n options: {\n type: 'dimension',\n dimension: 'resourceId',\n query: scope === 'org' ? 'resources' : 'figures',\n joinOn: 'threadId',\n width: 'minmax(6rem,1fr)',\n },\n };\n return {\n label: 'Breakdown by thread',\n scope,\n description: 'Traces, errors, latency and spend per thread.',\n queries: [threads, usageTotals(groupBy), ...(scope === 'org' ? [resources] : [])],\n columns: traceColumns('Thread', {}, [resourceColumn]),\n options: tableOptions(groupBy, 'Thread', 'No traces with a thread in this range.', {\n hideUnnamed: true,\n dropped: false,\n ...drill(scope, 'threadId', 'threadId', { keepEmpty: true }),\n }),\n };\n};\n\nconst modelsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'provider').concat('model');\n return {\n label: 'Breakdown by model',\n scope,\n description: 'Model calls, tokens and spend per model.',\n queries: [\n {\n id: 'calls',\n source: 'metrics',\n request: 'breakdown',\n name: [INPUT],\n groupBy,\n aggregation: 'count',\n orderDirection: 'DESC',\n limit: 1000,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: [\n nameColumn('Model', { unnamed: 'Unknown model', mark: { providerDimension: 'provider' } }),\n projectColumn,\n ...usageColumns,\n countColumn({ label: 'Spans', value: { query: 'calls', field: 'value' }, spans: true }),\n changeColumn,\n ],\n options: tableOptions(groupBy, 'Model', 'No model usage in this range.', drill(scope, 'model', 'model')),\n };\n};\n\nconst scopedViews = (scope: 'org' | 'project'): DashboardWidgetView[] => [\n entityView(\n scope,\n 'Agents',\n 'Traces each agent ran in, nested runs included, with errors, latency and spend.',\n 'No agent runs in this range.',\n ),\n entityView(\n scope,\n 'Workflows',\n 'Traces each workflow ran in, nested runs included, with errors and latency.',\n 'No workflow runs in this range.',\n ),\n entityView(\n scope,\n 'Tools',\n 'Every tool call, MCP tools included, with errors and latency.',\n 'No tool calls in this range.',\n ),\n modelsView(scope),\n threadsView(scope),\n environmentsView(scope),\n];\n\nconst breakdownWidget: DashboardWidget = {\n id: 'breakdown',\n span: 12,\n kind: 'table',\n title: 'Breakdown',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n label: 'Breakdown by project',\n scope: 'org',\n description: 'Traces, errors, latency and spend per project.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy: ['projectId'],\n measures: [...ERRORS, 'countDistinct.resourceId', 'countDistinct.threadId'],\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(['projectId']),\n ],\n columns: [\n nameColumn('Project', { as: 'project' }),\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n ],\n options: tableOptions(['projectId'], 'Project', 'No traces in this range.', {\n openWhen: { minRows: 2 },\n rowDrilldown: { fields: { projectId: 'projectId' } },\n }),\n },\n ...scopedViews('org'),\n ...scopedViews('project'),\n ],\n};\n\n/** Freezes a value and everything it holds, so a shared definition can't be edited in place. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The Metrics page as a dashboard: four charts in two rows (usage and health first), then the\n * breakdown of who caused them. Org and project pages share it; scope-tagged parts pick per page.\n * It is frozen: copy it (`structuredClone(METRICS_DASHBOARD)`) before customising.\n */\nexport const METRICS_DASHBOARD: DashboardDefinition = deepFreeze({\n schemaVersion: 1,\n rows: [\n { widgets: [tokenUsageWidget, agentRunsWidget] },\n { widgets: [latencyWidget, distinctIdsWidget] },\n { widgets: [breakdownWidget] },\n ],\n});\n"],"mappings":";AASA,IAAM,QAAQ;AACd,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,aAAa,IAAY,UAAkC;CAC/D;CACA,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,IAAI;CACX,aAAa;AACf;AAEA,IAAM,oBAAoC;CACxC,IAAI;CACJ,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,cAAc;CACrB,aAAa;CACb,SAAS,CAAC,QAAQ;AACpB;AAGA,IAAM,SAAS,CAAC,SAAS,QAAQ;AACjC,IAAM,gBAAgB;CAAE,OAAO;CAAQ,WAAW;AAAO;AACzD,IAAM,aAAa;CAAE,OAAO;CAAQ,QAAQ;AAAO;AACnD,IAAM,kBAA4C;CAChD,MAAM;CACN,SAAS,CAAC;EAAE,SAAS;EAAkB,OAAO;CAAQ,CAAC;AACzD;AAEA,IAAM,mBAAoC;CACxC,IAAI;CACJ,MAAM;CACN,MAAM;CACN,OAAO;CACP,WAAW;EAAE,QAAQ,EAAE,MAAM,SAAS;EAAG,OAAO,EAAE,MAAM,SAAS;CAAE;CACnE,OAAO,CACL;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pB,GAAG,YAAY,SAAS;CAC1B;AACF;;AAGA,SAAS,WAAc,OAAa;CAClC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;EACjE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,WAAW,KAAK;EAC1D,OAAO,OAAO,KAAK;CACrB;CACA,OAAO;AACT;;;;;;AAOA,IAAa,oBAAyC,WAAW;CAC/D,eAAe;CACf,MAAM;EACJ,EAAE,SAAS,CAAC,kBAAkB,eAAe,EAAE;EAC/C,EAAE,SAAS,CAAC,eAAe,iBAAiB,EAAE;EAC9C,EAAE,SAAS,CAAC,eAAe,EAAE;CAC/B;AACF,CAAC"}
1
+ {"version":3,"file":"metrics-dashboard.es.js","names":[],"sources":["../../../src/domains/dashboards/metrics-dashboard.ts"],"sourcesContent":["import type {\n DashboardColumn,\n DashboardDefinition,\n DashboardDrilldownTarget,\n DashboardQuery,\n DashboardWidget,\n DashboardWidgetView,\n} from '@mastra/client-js';\n\nconst INPUT = 'mastra_model_total_input_tokens';\nconst OUTPUT = 'mastra_model_total_output_tokens';\nconst CACHE_READ = 'mastra_model_input_cache_read_tokens';\nconst AGENT_DURATION = 'mastra_agent_duration_ms';\n\nconst sumSeries = (id: string, name: string): DashboardQuery => ({\n id,\n source: 'metrics',\n request: 'timeSeries',\n name: [name],\n aggregation: 'sum',\n});\n\nconst agentRunsByStatus: DashboardQuery = {\n id: 'runs',\n source: 'metrics',\n request: 'timeSeries',\n name: [AGENT_DURATION],\n aggregation: 'count',\n groupBy: ['status'],\n};\n\n// Runs report status `ok` or `error` (observability/mastra auto-extract); the card also counts `failed`.\nconst FAILED = ['error', 'failed'];\nconst completedRuns = { query: 'runs', notGroups: FAILED };\nconst failedRuns = { query: 'runs', groups: FAILED };\nconst agentRunsTraces: DashboardDrilldownTarget = {\n page: 'traces',\n filters: [{ fieldId: 'rootEntityType', value: 'agent' }],\n};\n\nconst tokenUsageWidget: DashboardWidget = {\n id: 'token-usage',\n span: 6,\n kind: 'timeseries',\n title: 'Token usage',\n drilldown: { action: { page: 'traces' }, click: { page: 'traces' } },\n views: [\n {\n label: 'Token usage',\n description: 'Input, cache reads and output.',\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'count',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'input',\n label: 'Input',\n color: 'green',\n value: { max: [{ minus: [{ query: 'input' }, { query: 'cacheRead' }] }, { const: 0 }] },\n },\n { dataKey: 'cacheRead', label: 'Cache read', color: 'violet', value: { query: 'cacheRead' } },\n { dataKey: 'output', label: 'Output', color: 'sky', value: { query: 'output' } },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Model cost',\n description: 'Estimated model spend.',\n // Cache reads aren't charted here, but fetching them keeps their answer, so going back to\n // Token usage sends nothing, as the card's one request for both views does.\n queries: [sumSeries('input', INPUT), sumSeries('output', OUTPUT), sumSeries('cacheRead', CACHE_READ)],\n options: {\n chart: 'stackedBar',\n format: 'usd',\n xLabels: 'edges',\n series: [\n {\n dataKey: 'cost',\n label: 'Cost',\n color: 'green',\n value: {\n sum: [\n { query: 'input', field: 'estimatedCost' },\n { query: 'output', field: 'estimatedCost' },\n ],\n },\n },\n ],\n total: { value: 'total' },\n },\n },\n ],\n};\n\nconst failedAgentRuns = [\n { fieldId: 'rootEntityType', value: 'agent' },\n { fieldId: 'status', value: 'error' },\n];\n\n/** Agent runs, with Failure rate as its second tab, as the Agent runs card. */\nconst agentRunsWidget: DashboardWidget = {\n id: 'agent-runs',\n span: 6,\n kind: 'timeseries',\n title: 'Agent runs',\n views: [\n {\n label: 'Agent runs',\n description: 'Completed and failed runs.',\n drilldown: { click: agentRunsTraces },\n queries: [agentRunsByStatus],\n options: {\n chart: 'stackedBar',\n format: 'count',\n axis: false,\n xLabels: 'edges',\n series: [\n { dataKey: 'completed', label: 'Completed', color: 'green', value: completedRuns },\n { dataKey: 'failed', label: 'Failed', color: 'error', value: failedRuns },\n ],\n total: { value: 'total' },\n },\n },\n {\n label: 'Failure rate',\n description: 'Share of agent runs that failed.',\n drilldown: {\n action: { page: 'logs', filters: failedAgentRuns },\n click: { page: 'traces', filters: failedAgentRuns },\n },\n queries: [agentRunsByStatus],\n options: {\n chart: 'line',\n format: 'percent',\n xLabels: 'edges',\n flatYDomain: [0, 1],\n series: [\n {\n dataKey: 'failureRate',\n label: 'Failed runs',\n color: 'error',\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n ],\n total: {\n value: {\n coalesce: [{ ratio: { of: failedRuns, over: { sum: [completedRuns, failedRuns] } } }, { const: 0 }],\n },\n },\n emptyWhenZero: { sum: [completedRuns, failedRuns] },\n },\n },\n ],\n};\n\nconst latencyView = (label: string, metric: string, rootEntityType: string): DashboardWidgetView => ({\n label,\n queries: [\n {\n id: 'latency',\n source: 'metrics',\n request: 'percentiles',\n name: metric,\n percentiles: [0.5, 0.95, 0.99],\n } satisfies DashboardQuery,\n ],\n drilldown: { action: { page: 'traces', filters: [{ fieldId: 'rootEntityType', value: rootEntityType }] } },\n options: {\n chart: 'line',\n format: 'duration',\n buckets: 'api',\n xLabels: 'edges',\n series: [\n { dataKey: 'p50', label: 'P50', color: 'sky', value: { query: 'latency', percentile: 0.5 }, round: true },\n {\n dataKey: 'p95',\n label: 'P95',\n color: 'green',\n emphasis: true,\n value: { query: 'latency', percentile: 0.95 },\n round: true,\n },\n { dataKey: 'p99', label: 'P99', color: 'violet', value: { query: 'latency', percentile: 0.99 }, round: true },\n ],\n total: { value: { peak: 'p95' } },\n },\n});\n\nconst latencyWidget: DashboardWidget = {\n id: 'latency',\n span: 6,\n kind: 'timeseries',\n title: 'Latency',\n description: 'Duration percentiles.',\n drilldown: { click: { page: 'traces' } },\n views: [\n latencyView('Agent latency', 'mastra_agent_duration_ms', 'agent'),\n latencyView('Workflow latency', 'mastra_workflow_duration_ms', 'workflow_run'),\n latencyView('Tool latency', 'mastra_tool_duration_ms', 'tool'),\n ],\n};\n\nconst DISTINCT_IDS = [\n ['countDistinct.resourceId', 'resources', 'Resources', 'sky'],\n ['countDistinct.threadId', 'threads', 'Threads', 'green'],\n ['countDistinct.userId', 'users', 'Users', 'violet'],\n ['countDistinct.sessionId', 'sessions', 'Sessions', 'teal'],\n] as const;\nconst distinctMeasures = DISTINCT_IDS.map(([measure]) => measure);\n\nconst distinctIdsWidget: DashboardWidget = {\n id: 'distinct-ids',\n span: 6,\n kind: 'timeseries',\n title: 'Resources and threads',\n description: 'Unique ids on traces; users and sessions only when set.',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n queries: [\n { id: 'buckets', source: 'traceAggregate', measures: distinctMeasures, limit: 10 },\n { id: 'totals', source: 'traceAggregate', measures: distinctMeasures },\n ],\n options: {\n chart: 'line',\n format: 'count',\n xLabels: 'edges',\n totals: ['totals'],\n hideEmpty: true,\n emphasizeFirst: true,\n series: DISTINCT_IDS.map(([measure, dataKey, label, color]) => ({\n dataKey,\n label,\n color,\n value: { query: 'buckets', measure },\n rangeTotal: { query: 'totals', measure },\n })),\n },\n },\n ],\n};\n\nconst USAGE = [INPUT, OUTPUT];\nconst TRACE_LIMIT = 1000;\nconst SPAN_LIMIT = 500;\ntype TraceMeasure = NonNullable<Extract<DashboardQuery, { source: 'traceAggregate' }>['measures']>[number];\ntype SpanMeasure = NonNullable<Extract<DashboardQuery, { source: 'spanAggregate' }>['measures']>[number];\nconst ERRORS: TraceMeasure[] = ['count', 'errorRate', 'duration.p95'];\n/** Traces with a thread. */\nconst hasThread = { op: 'exists', path: 'threadId' } as const;\n\nconst usageTotals = (groupBy: string[], filters?: Record<string, string>): DashboardQuery => ({\n id: 'usage',\n source: 'metrics',\n request: 'breakdown',\n name: USAGE,\n groupBy,\n aggregation: 'sum',\n orderDirection: 'DESC',\n limit: 1000,\n ...(filters ? { filters } : {}),\n compare: 'previousWindow',\n});\n\nconst TRACE_DESCRIPTION = 'A trace is one end-to-end request, with every step it took.';\nconst SPAN_DESCRIPTION =\n 'A span is one step inside a trace, such as a tool call or a model call. One trace can have many.';\n\nconst nameColumn = (label: string, options: Record<string, unknown> = {}): DashboardColumn => ({\n id: 'name',\n label,\n options: { type: 'name', width: 'minmax(12rem,3fr)', ...options },\n});\nconst projectColumn: DashboardColumn = {\n id: 'project',\n label: 'Project',\n scope: 'org',\n options: { type: 'dimension', dimension: 'projectId', as: 'project', width: 'minmax(8rem,2fr)' },\n};\nconst errorColumns: DashboardColumn[] = [\n {\n id: 'errorRate',\n label: 'Errors',\n options: { type: 'value', value: { query: 'figures', measure: 'errorRate' }, format: 'percent', better: 'lower' },\n },\n {\n id: 'p95',\n label: 'P95 latency',\n options: {\n type: 'value',\n value: { query: 'figures', measure: 'duration.p95' },\n format: 'duration',\n better: 'lower',\n },\n },\n];\nconst usageColumns: DashboardColumn[] = [\n {\n id: 'tokens',\n label: 'Tokens',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'value' },\n format: 'count',\n missing: 0,\n additive: true,\n better: 'lower',\n },\n },\n {\n id: 'cost',\n label: 'Cost',\n options: {\n type: 'value',\n value: { query: 'usage', field: 'estimatedCost' },\n format: 'usd',\n additive: true,\n better: 'lower',\n unpricedWhen: 'tokens',\n },\n },\n];\nconst countColumn = (count: { label: string; value: Record<string, unknown>; spans: boolean }): DashboardColumn => ({\n id: 'count',\n label: count.label,\n options: {\n type: 'value',\n value: count.value,\n format: 'count',\n emphasis: true,\n missing: 0,\n additive: true,\n better: 'higher',\n description: count.spans ? SPAN_DESCRIPTION : TRACE_DESCRIPTION,\n },\n});\nconst changeColumn: DashboardColumn = { id: 'change', label: '% Change', options: { type: 'change' } };\nconst TRACES = { label: 'Traces', value: { query: 'figures', measure: 'count' }, spans: false };\n\nconst tableOptions = (groupBy: string[], name: string, emptyMessage: string, extra: Record<string, unknown> = {}) => ({\n groupBy,\n defaultSort: { column: 'count', direction: 'desc' },\n pageSize: 10,\n emptyMessage,\n ariaLabel: `${name} breakdown`,\n ...extra,\n});\n\n/** Row clicks open traces in the row's project, plus the row's own name as `field`. */\nconst drill = (scope: 'org' | 'project', name: string, field: string, extra: Record<string, unknown> = {}) => ({\n rowDrilldown: { fields: { ...(scope === 'org' ? { projectId: 'projectId' } : {}), [name]: field }, ...extra },\n});\n\nconst scoped = (scope: 'org' | 'project', dimension: string) =>\n scope === 'org' ? ['projectId', dimension] : [dimension];\n\nconst ENTITIES = {\n Agents: { name: 'Agent', icon: 'agent', spanTypes: ['agent_run'] },\n Workflows: { name: 'Workflow', icon: 'workflow', spanTypes: ['workflow_run'] },\n Tools: { name: 'Tool', icon: 'tool', spanTypes: ['tool_call', 'mcp_tool_call'] },\n} as const;\n\n/** An entity's figures; agents and workflows count the traces they ran in, tools every call. */\nconst spanMeasures = (traces: boolean): SpanMeasure[] => [\n 'count',\n ...(traces ? (['countDistinct.traceId'] as const) : []),\n 'errorCount',\n 'errorRate',\n 'duration.p95',\n];\n\nconst entityView = (\n scope: 'org' | 'project',\n label: keyof typeof ENTITIES,\n description: string,\n emptyMessage: string,\n): DashboardWidgetView => {\n const { name, icon, spanTypes } = ENTITIES[label];\n const groupBy = scoped(scope, 'entityName');\n const usage = label === 'Agents';\n const traces = label !== 'Tools';\n return {\n label: `Breakdown by ${name.toLowerCase()}`,\n scope,\n description,\n queries: [\n {\n id: 'figures',\n source: 'spanAggregate',\n where:\n spanTypes.length === 1\n ? { op: 'eq', left: { path: 'spanType' }, right: { literal: spanTypes[0] } }\n : { op: 'in', value: { path: 'spanType' }, set: [...spanTypes] },\n groupBy,\n measures: spanMeasures(traces),\n limit: SPAN_LIMIT,\n compare: 'previousWindow',\n },\n ...(usage ? [usageTotals(groupBy, { entityType: 'agent' })] : []),\n ],\n columns: [\n nameColumn(name, { mark: { icon } }),\n projectColumn,\n ...errorColumns,\n ...(usage ? usageColumns : []),\n countColumn(\n traces\n ? { label: 'Traces', value: { query: 'figures', measure: 'countDistinct.traceId' }, spans: false }\n : { label: 'Spans', value: { query: 'figures', measure: 'count' }, spans: true },\n ),\n changeColumn,\n ],\n options: tableOptions(\n groupBy,\n name,\n emptyMessage,\n drill(scope, 'entityName', 'entityName', { spanTypes, keepEmpty: true }),\n ),\n };\n};\n\nconst traceColumns = (\n name: string,\n options: Record<string, unknown> = {},\n extra: DashboardColumn[] = [],\n): DashboardColumn[] => [\n nameColumn(name, options),\n projectColumn,\n ...extra,\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n];\n\nconst environmentsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'environment');\n return {\n label: 'Breakdown by environment',\n scope,\n description: 'Traces, errors, latency and spend per environment.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy,\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: traceColumns('Environment', { unnamed: 'No environment' }),\n options: tableOptions(\n groupBy,\n 'Environment',\n 'No traces in this range.',\n drill(scope, 'environment', 'environment'),\n ),\n };\n};\n\nconst threadsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'threadId');\n const threads: DashboardQuery = {\n id: 'figures',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: scope === 'org' ? ['projectId', 'threadId'] : ['resourceId', 'threadId'],\n measures: ERRORS,\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n };\n // Org-wide the second dimension is the project, so a third request names each thread's resource.\n const resources: DashboardQuery = {\n id: 'resources',\n source: 'traceAggregate',\n where: hasThread,\n groupBy: ['resourceId', 'threadId'],\n measures: ['count'],\n limit: TRACE_LIMIT,\n };\n const resourceColumn: DashboardColumn = {\n id: 'resource',\n label: 'Resource',\n options: {\n type: 'dimension',\n dimension: 'resourceId',\n query: scope === 'org' ? 'resources' : 'figures',\n joinOn: 'threadId',\n width: 'minmax(6rem,1fr)',\n },\n };\n return {\n label: 'Breakdown by thread',\n scope,\n description: 'Traces, errors, latency and spend per thread.',\n queries: [threads, usageTotals(groupBy), ...(scope === 'org' ? [resources] : [])],\n columns: traceColumns('Thread', {}, [resourceColumn]),\n options: tableOptions(groupBy, 'Thread', 'No traces with a thread in this range.', {\n hideUnnamed: true,\n dropped: false,\n ...drill(scope, 'threadId', 'threadId', { keepEmpty: true }),\n }),\n };\n};\n\nconst modelsView = (scope: 'org' | 'project'): DashboardWidgetView => {\n const groupBy = scoped(scope, 'provider').concat('model');\n return {\n label: 'Breakdown by model',\n scope,\n description: 'Model calls, tokens and spend per model.',\n queries: [\n {\n id: 'calls',\n source: 'metrics',\n request: 'breakdown',\n name: [INPUT],\n groupBy,\n aggregation: 'count',\n orderDirection: 'DESC',\n limit: 1000,\n compare: 'previousWindow',\n },\n usageTotals(groupBy),\n ],\n columns: [\n nameColumn('Model', { unnamed: 'Unknown model', mark: { providerDimension: 'provider' } }),\n projectColumn,\n ...usageColumns,\n countColumn({ label: 'Spans', value: { query: 'calls', field: 'value' }, spans: true }),\n changeColumn,\n ],\n options: tableOptions(groupBy, 'Model', 'No model usage in this range.', drill(scope, 'model', 'model')),\n };\n};\n\nconst scopedViews = (scope: 'org' | 'project'): DashboardWidgetView[] => [\n entityView(\n scope,\n 'Agents',\n 'Traces each agent ran in, nested runs included, with errors, latency and spend.',\n 'No agent runs in this range.',\n ),\n entityView(\n scope,\n 'Workflows',\n 'Traces each workflow ran in, nested runs included, with errors and latency.',\n 'No workflow runs in this range.',\n ),\n entityView(\n scope,\n 'Tools',\n 'Every tool call, MCP tools included, with errors and latency.',\n 'No tool calls in this range.',\n ),\n modelsView(scope),\n threadsView(scope),\n environmentsView(scope),\n];\n\nconst breakdownWidget: DashboardWidget = {\n id: 'breakdown',\n span: 12,\n kind: 'table',\n title: 'Breakdown',\n drilldown: { click: { page: 'traces' } },\n views: [\n {\n label: 'Breakdown by project',\n scope: 'org',\n description: 'Traces, errors, latency and spend per project.',\n queries: [\n {\n id: 'figures',\n source: 'traceAggregate',\n groupBy: ['projectId'],\n measures: [...ERRORS, 'countDistinct.resourceId', 'countDistinct.threadId'],\n limit: TRACE_LIMIT,\n compare: 'previousWindow',\n },\n usageTotals(['projectId']),\n ],\n columns: [\n nameColumn('Project', { as: 'project' }),\n ...errorColumns,\n ...usageColumns,\n countColumn(TRACES),\n changeColumn,\n ],\n options: tableOptions(['projectId'], 'Project', 'No traces in this range.', {\n openWhen: { minRows: 2 },\n rowDrilldown: { fields: { projectId: 'projectId' } },\n }),\n },\n ...scopedViews('org'),\n ...scopedViews('project'),\n ],\n};\n\n/** Freezes a value and everything it holds, so a shared definition can't be edited in place. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The Metrics page as a dashboard: four charts in two rows (usage and health first), then the\n * breakdown of who caused them. Org and project pages share it; scope-tagged parts pick per page.\n * It is frozen: copy it (`structuredClone(METRICS_DASHBOARD)`) before customising.\n */\nexport const METRICS_DASHBOARD: DashboardDefinition = deepFreeze({\n schemaVersion: 1,\n rows: [\n { widgets: [tokenUsageWidget, agentRunsWidget] },\n { widgets: [latencyWidget, distinctIdsWidget] },\n { widgets: [breakdownWidget] },\n ],\n});\n"],"mappings":";AASA,IAAM,QAAQ;AACd,IAAM,SAAS;AACf,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,aAAa,IAAY,UAAkC;CAC/D;CACA,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,IAAI;CACX,aAAa;AACf;AAEA,IAAM,oBAAoC;CACxC,IAAI;CACJ,QAAQ;CACR,SAAS;CACT,MAAM,CAAC,cAAc;CACrB,aAAa;CACb,SAAS,CAAC,QAAQ;AACpB;AAGA,IAAM,SAAS,CAAC,SAAS,QAAQ;AACjC,IAAM,gBAAgB;CAAE,OAAO;CAAQ,WAAW;AAAO;AACzD,IAAM,aAAa;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CAAC,CAC3B;GACA,SAAS;IACP,WAAW,WAAW,EAAE,IAAI,UAAU,CAAC;IACvC,GAAG;IACH,GAAG;IACH,YAAY,MAAM;IAClB;GACF;GACA,SAAS,aAAa,CAAC,WAAW,GAAG,WAAW,4BAA4B;IAC1E,UAAU,EAAE,SAAS,EAAE;IACvB,cAAc,EAAE,QAAQ,EAAE,WAAW,YAAY,EAAE;GACrD,CAAC;EACH;EACA,GAAG,YAAY,KAAK;EACpB,GAAG,YAAY,SAAS;CAC1B;AACF;;AAGA,SAAS,WAAc,OAAa;CAClC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;EACjE,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,WAAW,KAAK;EAC1D,OAAO,OAAO,KAAK;CACrB;CACA,OAAO;AACT;;;;;;AAOA,IAAa,oBAAyC,WAAW;CAC/D,eAAe;CACf,MAAM;EACJ,EAAE,SAAS,CAAC,kBAAkB,eAAe,EAAE;EAC/C,EAAE,SAAS,CAAC,eAAe,iBAAiB,EAAE;EAC9C,EAAE,SAAS,CAAC,eAAe,EAAE;CAC/B;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"widget-kind.cjs.js","names":[],"sources":["../../../src/domains/dashboards/widget-kind.ts"],"sourcesContent":["import type { DashboardQuery, DashboardWidget, DashboardWidgetView } from '@mastra/client-js';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { z } from 'zod/v4';\nimport type { ChartCardProps } from '../metrics/components/chart-card';\nimport type { DashboardScope, OnDashboardDrilldown } from './lib/definition';\nimport type { BlockedFields, WidgetGate } from './lib/gate';\nimport type { DashboardPageContext, DashboardRequest, DashboardResult } from './lib/requests';\nimport type { ValueRef } from './lib/values';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\nimport type { MetricsTableSort } from '@/ds/components/MetricsTable';\n\n/** A view whose options passed its kind's schema. */\nexport type ResolvedView<Options> = DashboardWidgetView & { options: Options };\n\nexport type WidgetKindProps<Options> = {\n widget: DashboardWidget;\n /** The views at the page's scope, options parsed. Never empty. */\n views: [ResolvedView<Options>, ...ResolvedView<Options>[]];\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n /** Where a chart card expands to; see `DashboardExpand`. */\n expand?: DashboardExpand;\n /** A grip to drag the widget by, shown left of its title: the host is arranging the dashboard. */\n dragHandle?: MetricsCardDragHandleProps;\n /** Renames the widget from its title; see `StatelessWidgetProps['onTitleChange']`. */\n onTitleChange?: (title: string) => void;\n /**\n * The host's buttons, after the card's own (drilldown, alert): `MetricsCard.Action`s, each deciding\n * whether it waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n /** The card's Create alert button, for the open view: the host can turn views into alerts. */\n alert?: DashboardAlert;\n /** Whether the widget's queries can run on the page, and their page context once they can. */\n gate: ShownGate;\n /** What figures are compared against, e.g. `vs previous 24h`. */\n comparisonLabel: string;\n /** Display name for a project id, when the page spans several projects. */\n projectLabel?: (projectId: string) => string;\n /** What the user picked on the widget, held by the host. */\n state: WidgetState;\n /** Called with the whole next state when the user picks a view, sorts, or compares. */\n onStateChange: (next: WidgetState) => void;\n /** Answers to the kind's `discover` requests, in order. */\n discovered: (DashboardResult | undefined)[];\n /** Answers to the kind's `requests`, in order. */\n results: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n};\n\n/** What a card's Create alert button watches: its open view, with the page's filters applied. */\nexport type DashboardAlertTarget = {\n widget: DashboardWidget;\n view: DashboardWidgetView;\n /**\n * The view's queries with the page's filter bar ANDed in (`pageQuery`). They carry no time window:\n * the alert picks its own. As authored, so a scores query may lack `scorerId` (the card reads\n * every scorer); the host has to pick one or disable the button.\n */\n queries: DashboardQuery[];\n /**\n * Each distinct number the view shows, read straight from one query: a series, column or KPI, or,\n * for one combining several (a ratio, a sum), each part. Same order as the view's options.\n */\n sources: DashboardAlertSource[];\n};\n\n/** One number a view reads from one query, as a single alert could watch it. */\nexport type DashboardAlertSource = {\n /** The series, column or KPI it belongs to; a part of a combined value adds its query and ref. */\n label: string;\n /** The query, with the page's filters applied, as in `queries`. */\n query: DashboardQuery;\n /** Which of the query's numbers: a measure, a field, a percentile, or only some groups. */\n ref: DashboardAlertRef;\n};\n\nexport type DashboardAlertRef = Omit<ValueRef, 'query'>;\n\n/** Where the button opens the host's alert editor, or why the view can't become an alert. */\nexport type DashboardAlertAction = { href: string } | { disabled: string };\n\n/**\n * How a host turns a card's open view into an alert. `action` returns one action for the whole card,\n * `undefined` for no button, or an array aligned with `target.sources`: one action per source\n * (`undefined` leaves it out). A card with several sources the host can alert on opens a menu of them.\n * Links render through `LinkComponent`.\n */\nexport type DashboardAlert = {\n action: (target: DashboardAlertTarget) => DashboardAlertAction | (DashboardAlertAction | undefined)[] | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/** A widget's gate when it shows: waiting on, or ready to send, its requests. */\nexport type ShownGate = Exclude<WidgetGate, { status: 'hidden' }>;\n\n/**\n * What the user picked on a widget: the open view, and a table's sort and the value column its\n * % Change compares. Unset fields take the widget's defaults.\n */\nexport type WidgetState = { view?: number; sort?: MetricsTableSort; compared?: string };\n\n/** What a kind plans its requests from, once its gate is ready. */\nexport type WidgetPlanContext<Options> = {\n widget: DashboardWidget;\n views: WidgetKindProps<Options>['views'];\n page: DashboardPageContext;\n blocked: BlockedFields;\n state: WidgetState;\n};\n\n/** A kind's requests, in the order its answers come back; `undefined` slots aren't sent. */\nexport type WidgetRequests = (DashboardRequest | undefined)[];\n\n/**\n * Where a chart widget expands to (a host's query page), as the Gateway Overview's cards do: the card\n * gets an expand action linking there, and shows its first view under its plain title, in place of\n * its views menu, so the title stays editable with `onTitleChange`. `href` returns `undefined` for a\n * widget with nowhere to go; that card keeps its menu.\n */\nexport type DashboardExpand = {\n href: (widget: DashboardWidget) => string | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/**\n * One kind of widget, self-contained: the renderer only looks it up by name, checks each view's\n * options against `optionsSchema`, sends what `discover` then `requests` plan, and renders\n * `component` with the answers. A kind planning neither sends nothing; its component may still fetch\n * on its own (`ViewGate`, `useDashboardRequests`), but then only `DashboardRenderer` can host it.\n */\nexport type WidgetKind<Options = unknown> = {\n kind: string;\n /** Each view's `options`, parsed before the widget renders. */\n optionsSchema: z.ZodType<Options>;\n /** Further problems with a view, e.g. options naming a query the view doesn't have. */\n issues?: (view: ResolvedView<Options>) => string[];\n /**\n * Shows the widget even when a page filter can't apply to some of its queries: its views say so\n * on their own, checking `blocked` (a table's tabs).\n */\n partial?: boolean;\n /**\n * The queries the page's gates check, given what the user picked. Defaults to every view's, so\n * pick only the views the widget shows: a closed view's trace query mustn't hide an open metrics one.\n */\n gatedQueries?: (views: WidgetPlanContext<Options>['views'], state: WidgetState) => DashboardQuery[];\n /** Requests whose answers decide what `requests` asks (the scorers to chart, a table's opening tab). */\n discover?: (ctx: WidgetPlanContext<Options>) => WidgetRequests;\n /** The requests the widget renders from, given the answers to `discover`. */\n requests?: (ctx: WidgetPlanContext<Options>, discovered: (DashboardResult | undefined)[]) => WidgetRequests;\n component: ComponentType<WidgetKindProps<Options>>;\n};\n\n/** Keeps a kind's options type while it joins a list of kinds of different options. */\nexport const defineWidgetKind = <Options>(kind: WidgetKind<Options>): WidgetKind<Options> => kind;\n\n/** A registry entry, whatever its options. */\nexport type AnyWidgetKind = WidgetKind<any>;\n"],"mappings":";;;AA4JA,IAAa,oBAA6B,SAAmD"}
1
+ {"version":3,"file":"widget-kind.cjs.js","names":[],"sources":["../../../src/domains/dashboards/widget-kind.ts"],"sourcesContent":["import type { DashboardQuery, DashboardWidget, DashboardWidgetView } from '@mastra/client-js';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { z } from 'zod/v4';\nimport type { ChartCardProps } from '../metrics/components/chart-card';\nimport type { DashboardScope, OnDashboardDrilldown } from './lib/definition';\nimport type { BlockedFields, WidgetGate } from './lib/gate';\nimport type { DashboardPageContext, DashboardRequest, DashboardResult } from './lib/requests';\nimport type { ValueRef } from './lib/values';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\nimport type { MetricsTableSort } from '@/ds/components/MetricsTable';\n\n/** A view whose options passed its kind's schema. */\nexport type ResolvedView<Options> = DashboardWidgetView & { options: Options };\n\nexport type WidgetKindProps<Options> = {\n widget: DashboardWidget;\n /** The views at the page's scope, options parsed. Never empty. */\n views: [ResolvedView<Options>, ...ResolvedView<Options>[]];\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n /** Where a chart card expands to; see `DashboardExpand`. */\n expand?: DashboardExpand;\n /** A grip to drag the widget by, shown left of its title: the host is arranging the dashboard. */\n dragHandle?: MetricsCardDragHandleProps;\n /** Renames the widget from its title; see `StatelessWidgetProps['onTitleChange']`. */\n onTitleChange?: (title: string) => void;\n /**\n * The host's buttons, after the card's own (drilldown, alert): `MetricsCard.Action`s, each deciding\n * whether it waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n /** The card's Create alert button, for the open view: the host can turn views into alerts. */\n alert?: DashboardAlert;\n /** Whether the widget's queries can run on the page, and their page context once they can. */\n gate: ShownGate;\n /** What figures are compared against, e.g. `vs previous 24h`. */\n comparisonLabel: string;\n /** Display name for a project id, when the page spans several projects. */\n projectLabel?: (projectId: string) => string;\n /** What the user picked on the widget, held by the host. */\n state: WidgetState;\n /** Called with the whole next state when the user picks a view, sorts, or compares. */\n onStateChange: (next: WidgetState) => void;\n /** Answers to the kind's `discover` requests, in order. */\n discovered: (DashboardResult | undefined)[];\n /** Answers to the kind's `requests`, in order. */\n results: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n};\n\n/** What a card's Create alert button watches: its open view, with the page's filters applied. */\nexport type DashboardAlertTarget = {\n widget: DashboardWidget;\n view: DashboardWidgetView;\n /**\n * The view's queries with the page's filter bar ANDed in (`pageQuery`). They carry no time window:\n * the alert picks its own. As authored, so a scores query may lack `scorerId` (the card reads\n * every scorer); the host has to pick one or disable the button.\n */\n queries: DashboardQuery[];\n /**\n * Each distinct number the view shows, read straight from one query: a series, column or KPI, or,\n * for one combining several (a ratio, a sum), each part. Same order as the view's options.\n */\n sources: DashboardAlertSource[];\n};\n\n/** One number a view reads from one query, as a single alert could watch it. */\nexport type DashboardAlertSource = {\n /** The series, column or KPI it belongs to; a part of a combined value adds its query and ref. */\n label: string;\n /** The query, with the page's filters applied, as in `queries`. */\n query: DashboardQuery;\n /** Which of the query's numbers: a measure, a field, a percentile, or only some groups. */\n ref: DashboardAlertRef;\n};\n\nexport type DashboardAlertRef = Omit<ValueRef, 'query'>;\n\n/** Where the button opens the host's alert editor, or why the view can't become an alert. */\nexport type DashboardAlertAction = { href: string } | { disabled: string };\n\n/**\n * How a host turns a card's open view into an alert. `action` returns one action for the whole card,\n * `undefined` for no button, or an array aligned with `target.sources`: one action per source\n * (`undefined` leaves it out). A card with several sources the host can alert on opens a menu of them.\n * Links render through `LinkComponent`.\n */\nexport type DashboardAlert = {\n action: (target: DashboardAlertTarget) => DashboardAlertAction | (DashboardAlertAction | undefined)[] | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/** A widget's gate when it shows: waiting on, or ready to send, its requests. */\nexport type ShownGate = Exclude<WidgetGate, { status: 'hidden' }>;\n\n/**\n * What the user picked on a widget: the open view, and a table's sort and the value column its\n * % Change compares. Unset fields take the widget's defaults.\n */\nexport type WidgetState = { view?: number; sort?: MetricsTableSort; compared?: string };\n\n/** What a kind plans its requests from, once its gate is ready. */\nexport type WidgetPlanContext<Options> = {\n widget: DashboardWidget;\n views: WidgetKindProps<Options>['views'];\n page: DashboardPageContext;\n blocked: BlockedFields;\n state: WidgetState;\n};\n\n/** A kind's requests, in the order its answers come back; `undefined` slots aren't sent. */\nexport type WidgetRequests = (DashboardRequest | undefined)[];\n\n/**\n * Where a chart widget expands to (a host's query page), as the Gateway Overview's cards do: the card\n * gets an expand action linking there, and shows its first view under its title, without its view\n * tabs. `href` returns `undefined` for a widget with nowhere to go; that card keeps its tabs.\n */\nexport type DashboardExpand = {\n href: (widget: DashboardWidget) => string | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/**\n * One kind of widget, self-contained: the renderer only looks it up by name, checks each view's\n * options against `optionsSchema`, sends what `discover` then `requests` plan, and renders\n * `component` with the answers. A kind planning neither sends nothing; its component may still fetch\n * on its own (`ViewGate`, `useDashboardRequests`), but then only `DashboardRenderer` can host it.\n */\nexport type WidgetKind<Options = unknown> = {\n kind: string;\n /** Each view's `options`, parsed before the widget renders. */\n optionsSchema: z.ZodType<Options>;\n /** Further problems with a view, e.g. options naming a query the view doesn't have. */\n issues?: (view: ResolvedView<Options>) => string[];\n /**\n * Shows the widget even when a page filter can't apply to some of its queries: its views say so\n * on their own, checking `blocked` (a table's tabs).\n */\n partial?: boolean;\n /**\n * The queries the page's gates check, given what the user picked. Defaults to every view's, so\n * pick only the views the widget shows: a closed view's trace query mustn't hide an open metrics one.\n */\n gatedQueries?: (views: WidgetPlanContext<Options>['views'], state: WidgetState) => DashboardQuery[];\n /** Requests whose answers decide what `requests` asks (the scorers to chart, a table's opening tab). */\n discover?: (ctx: WidgetPlanContext<Options>) => WidgetRequests;\n /** The requests the widget renders from, given the answers to `discover`. */\n requests?: (ctx: WidgetPlanContext<Options>, discovered: (DashboardResult | undefined)[]) => WidgetRequests;\n component: ComponentType<WidgetKindProps<Options>>;\n};\n\n/** Keeps a kind's options type while it joins a list of kinds of different options. */\nexport const defineWidgetKind = <Options>(kind: WidgetKind<Options>): WidgetKind<Options> => kind;\n\n/** A registry entry, whatever its options. */\nexport type AnyWidgetKind = WidgetKind<any>;\n"],"mappings":";;;AA2JA,IAAa,oBAA6B,SAAmD"}
@@ -1 +1 @@
1
- {"version":3,"file":"widget-kind.es.js","names":[],"sources":["../../../src/domains/dashboards/widget-kind.ts"],"sourcesContent":["import type { DashboardQuery, DashboardWidget, DashboardWidgetView } from '@mastra/client-js';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { z } from 'zod/v4';\nimport type { ChartCardProps } from '../metrics/components/chart-card';\nimport type { DashboardScope, OnDashboardDrilldown } from './lib/definition';\nimport type { BlockedFields, WidgetGate } from './lib/gate';\nimport type { DashboardPageContext, DashboardRequest, DashboardResult } from './lib/requests';\nimport type { ValueRef } from './lib/values';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\nimport type { MetricsTableSort } from '@/ds/components/MetricsTable';\n\n/** A view whose options passed its kind's schema. */\nexport type ResolvedView<Options> = DashboardWidgetView & { options: Options };\n\nexport type WidgetKindProps<Options> = {\n widget: DashboardWidget;\n /** The views at the page's scope, options parsed. Never empty. */\n views: [ResolvedView<Options>, ...ResolvedView<Options>[]];\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n /** Where a chart card expands to; see `DashboardExpand`. */\n expand?: DashboardExpand;\n /** A grip to drag the widget by, shown left of its title: the host is arranging the dashboard. */\n dragHandle?: MetricsCardDragHandleProps;\n /** Renames the widget from its title; see `StatelessWidgetProps['onTitleChange']`. */\n onTitleChange?: (title: string) => void;\n /**\n * The host's buttons, after the card's own (drilldown, alert): `MetricsCard.Action`s, each deciding\n * whether it waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n /** The card's Create alert button, for the open view: the host can turn views into alerts. */\n alert?: DashboardAlert;\n /** Whether the widget's queries can run on the page, and their page context once they can. */\n gate: ShownGate;\n /** What figures are compared against, e.g. `vs previous 24h`. */\n comparisonLabel: string;\n /** Display name for a project id, when the page spans several projects. */\n projectLabel?: (projectId: string) => string;\n /** What the user picked on the widget, held by the host. */\n state: WidgetState;\n /** Called with the whole next state when the user picks a view, sorts, or compares. */\n onStateChange: (next: WidgetState) => void;\n /** Answers to the kind's `discover` requests, in order. */\n discovered: (DashboardResult | undefined)[];\n /** Answers to the kind's `requests`, in order. */\n results: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n};\n\n/** What a card's Create alert button watches: its open view, with the page's filters applied. */\nexport type DashboardAlertTarget = {\n widget: DashboardWidget;\n view: DashboardWidgetView;\n /**\n * The view's queries with the page's filter bar ANDed in (`pageQuery`). They carry no time window:\n * the alert picks its own. As authored, so a scores query may lack `scorerId` (the card reads\n * every scorer); the host has to pick one or disable the button.\n */\n queries: DashboardQuery[];\n /**\n * Each distinct number the view shows, read straight from one query: a series, column or KPI, or,\n * for one combining several (a ratio, a sum), each part. Same order as the view's options.\n */\n sources: DashboardAlertSource[];\n};\n\n/** One number a view reads from one query, as a single alert could watch it. */\nexport type DashboardAlertSource = {\n /** The series, column or KPI it belongs to; a part of a combined value adds its query and ref. */\n label: string;\n /** The query, with the page's filters applied, as in `queries`. */\n query: DashboardQuery;\n /** Which of the query's numbers: a measure, a field, a percentile, or only some groups. */\n ref: DashboardAlertRef;\n};\n\nexport type DashboardAlertRef = Omit<ValueRef, 'query'>;\n\n/** Where the button opens the host's alert editor, or why the view can't become an alert. */\nexport type DashboardAlertAction = { href: string } | { disabled: string };\n\n/**\n * How a host turns a card's open view into an alert. `action` returns one action for the whole card,\n * `undefined` for no button, or an array aligned with `target.sources`: one action per source\n * (`undefined` leaves it out). A card with several sources the host can alert on opens a menu of them.\n * Links render through `LinkComponent`.\n */\nexport type DashboardAlert = {\n action: (target: DashboardAlertTarget) => DashboardAlertAction | (DashboardAlertAction | undefined)[] | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/** A widget's gate when it shows: waiting on, or ready to send, its requests. */\nexport type ShownGate = Exclude<WidgetGate, { status: 'hidden' }>;\n\n/**\n * What the user picked on a widget: the open view, and a table's sort and the value column its\n * % Change compares. Unset fields take the widget's defaults.\n */\nexport type WidgetState = { view?: number; sort?: MetricsTableSort; compared?: string };\n\n/** What a kind plans its requests from, once its gate is ready. */\nexport type WidgetPlanContext<Options> = {\n widget: DashboardWidget;\n views: WidgetKindProps<Options>['views'];\n page: DashboardPageContext;\n blocked: BlockedFields;\n state: WidgetState;\n};\n\n/** A kind's requests, in the order its answers come back; `undefined` slots aren't sent. */\nexport type WidgetRequests = (DashboardRequest | undefined)[];\n\n/**\n * Where a chart widget expands to (a host's query page), as the Gateway Overview's cards do: the card\n * gets an expand action linking there, and shows its first view under its plain title, in place of\n * its views menu, so the title stays editable with `onTitleChange`. `href` returns `undefined` for a\n * widget with nowhere to go; that card keeps its menu.\n */\nexport type DashboardExpand = {\n href: (widget: DashboardWidget) => string | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/**\n * One kind of widget, self-contained: the renderer only looks it up by name, checks each view's\n * options against `optionsSchema`, sends what `discover` then `requests` plan, and renders\n * `component` with the answers. A kind planning neither sends nothing; its component may still fetch\n * on its own (`ViewGate`, `useDashboardRequests`), but then only `DashboardRenderer` can host it.\n */\nexport type WidgetKind<Options = unknown> = {\n kind: string;\n /** Each view's `options`, parsed before the widget renders. */\n optionsSchema: z.ZodType<Options>;\n /** Further problems with a view, e.g. options naming a query the view doesn't have. */\n issues?: (view: ResolvedView<Options>) => string[];\n /**\n * Shows the widget even when a page filter can't apply to some of its queries: its views say so\n * on their own, checking `blocked` (a table's tabs).\n */\n partial?: boolean;\n /**\n * The queries the page's gates check, given what the user picked. Defaults to every view's, so\n * pick only the views the widget shows: a closed view's trace query mustn't hide an open metrics one.\n */\n gatedQueries?: (views: WidgetPlanContext<Options>['views'], state: WidgetState) => DashboardQuery[];\n /** Requests whose answers decide what `requests` asks (the scorers to chart, a table's opening tab). */\n discover?: (ctx: WidgetPlanContext<Options>) => WidgetRequests;\n /** The requests the widget renders from, given the answers to `discover`. */\n requests?: (ctx: WidgetPlanContext<Options>, discovered: (DashboardResult | undefined)[]) => WidgetRequests;\n component: ComponentType<WidgetKindProps<Options>>;\n};\n\n/** Keeps a kind's options type while it joins a list of kinds of different options. */\nexport const defineWidgetKind = <Options>(kind: WidgetKind<Options>): WidgetKind<Options> => kind;\n\n/** A registry entry, whatever its options. */\nexport type AnyWidgetKind = WidgetKind<any>;\n"],"mappings":";;AA4JA,IAAa,oBAA6B,SAAmD"}
1
+ {"version":3,"file":"widget-kind.es.js","names":[],"sources":["../../../src/domains/dashboards/widget-kind.ts"],"sourcesContent":["import type { DashboardQuery, DashboardWidget, DashboardWidgetView } from '@mastra/client-js';\nimport type { ComponentType, ReactNode } from 'react';\nimport type { z } from 'zod/v4';\nimport type { ChartCardProps } from '../metrics/components/chart-card';\nimport type { DashboardScope, OnDashboardDrilldown } from './lib/definition';\nimport type { BlockedFields, WidgetGate } from './lib/gate';\nimport type { DashboardPageContext, DashboardRequest, DashboardResult } from './lib/requests';\nimport type { ValueRef } from './lib/values';\nimport type { MetricsCardDragHandleProps } from '@/ds/components/MetricsCard';\nimport type { MetricsTableSort } from '@/ds/components/MetricsTable';\n\n/** A view whose options passed its kind's schema. */\nexport type ResolvedView<Options> = DashboardWidgetView & { options: Options };\n\nexport type WidgetKindProps<Options> = {\n widget: DashboardWidget;\n /** The views at the page's scope, options parsed. Never empty. */\n views: [ResolvedView<Options>, ...ResolvedView<Options>[]];\n scope: DashboardScope;\n onDrilldown?: OnDashboardDrilldown;\n /** Where a chart card expands to; see `DashboardExpand`. */\n expand?: DashboardExpand;\n /** A grip to drag the widget by, shown left of its title: the host is arranging the dashboard. */\n dragHandle?: MetricsCardDragHandleProps;\n /** Renames the widget from its title; see `StatelessWidgetProps['onTitleChange']`. */\n onTitleChange?: (title: string) => void;\n /**\n * The host's buttons, after the card's own (drilldown, alert): `MetricsCard.Action`s, each deciding\n * whether it waits for the card's hover (e.g. `onCardHover`) or stays in view.\n */\n actions?: ReactNode;\n /** The card's Create alert button, for the open view: the host can turn views into alerts. */\n alert?: DashboardAlert;\n /** Whether the widget's queries can run on the page, and their page context once they can. */\n gate: ShownGate;\n /** What figures are compared against, e.g. `vs previous 24h`. */\n comparisonLabel: string;\n /** Display name for a project id, when the page spans several projects. */\n projectLabel?: (projectId: string) => string;\n /** What the user picked on the widget, held by the host. */\n state: WidgetState;\n /** Called with the whole next state when the user picks a view, sorts, or compares. */\n onStateChange: (next: WidgetState) => void;\n /** Answers to the kind's `discover` requests, in order. */\n discovered: (DashboardResult | undefined)[];\n /** Answers to the kind's `requests`, in order. */\n results: (DashboardResult | undefined)[];\n /** Asks the host to send the failed requests again. */\n onRetry: () => void;\n};\n\n/** What a card's Create alert button watches: its open view, with the page's filters applied. */\nexport type DashboardAlertTarget = {\n widget: DashboardWidget;\n view: DashboardWidgetView;\n /**\n * The view's queries with the page's filter bar ANDed in (`pageQuery`). They carry no time window:\n * the alert picks its own. As authored, so a scores query may lack `scorerId` (the card reads\n * every scorer); the host has to pick one or disable the button.\n */\n queries: DashboardQuery[];\n /**\n * Each distinct number the view shows, read straight from one query: a series, column or KPI, or,\n * for one combining several (a ratio, a sum), each part. Same order as the view's options.\n */\n sources: DashboardAlertSource[];\n};\n\n/** One number a view reads from one query, as a single alert could watch it. */\nexport type DashboardAlertSource = {\n /** The series, column or KPI it belongs to; a part of a combined value adds its query and ref. */\n label: string;\n /** The query, with the page's filters applied, as in `queries`. */\n query: DashboardQuery;\n /** Which of the query's numbers: a measure, a field, a percentile, or only some groups. */\n ref: DashboardAlertRef;\n};\n\nexport type DashboardAlertRef = Omit<ValueRef, 'query'>;\n\n/** Where the button opens the host's alert editor, or why the view can't become an alert. */\nexport type DashboardAlertAction = { href: string } | { disabled: string };\n\n/**\n * How a host turns a card's open view into an alert. `action` returns one action for the whole card,\n * `undefined` for no button, or an array aligned with `target.sources`: one action per source\n * (`undefined` leaves it out). A card with several sources the host can alert on opens a menu of them.\n * Links render through `LinkComponent`.\n */\nexport type DashboardAlert = {\n action: (target: DashboardAlertTarget) => DashboardAlertAction | (DashboardAlertAction | undefined)[] | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/** A widget's gate when it shows: waiting on, or ready to send, its requests. */\nexport type ShownGate = Exclude<WidgetGate, { status: 'hidden' }>;\n\n/**\n * What the user picked on a widget: the open view, and a table's sort and the value column its\n * % Change compares. Unset fields take the widget's defaults.\n */\nexport type WidgetState = { view?: number; sort?: MetricsTableSort; compared?: string };\n\n/** What a kind plans its requests from, once its gate is ready. */\nexport type WidgetPlanContext<Options> = {\n widget: DashboardWidget;\n views: WidgetKindProps<Options>['views'];\n page: DashboardPageContext;\n blocked: BlockedFields;\n state: WidgetState;\n};\n\n/** A kind's requests, in the order its answers come back; `undefined` slots aren't sent. */\nexport type WidgetRequests = (DashboardRequest | undefined)[];\n\n/**\n * Where a chart widget expands to (a host's query page), as the Gateway Overview's cards do: the card\n * gets an expand action linking there, and shows its first view under its title, without its view\n * tabs. `href` returns `undefined` for a widget with nowhere to go; that card keeps its tabs.\n */\nexport type DashboardExpand = {\n href: (widget: DashboardWidget) => string | undefined;\n LinkComponent: NonNullable<ChartCardProps['LinkComponent']>;\n};\n\n/**\n * One kind of widget, self-contained: the renderer only looks it up by name, checks each view's\n * options against `optionsSchema`, sends what `discover` then `requests` plan, and renders\n * `component` with the answers. A kind planning neither sends nothing; its component may still fetch\n * on its own (`ViewGate`, `useDashboardRequests`), but then only `DashboardRenderer` can host it.\n */\nexport type WidgetKind<Options = unknown> = {\n kind: string;\n /** Each view's `options`, parsed before the widget renders. */\n optionsSchema: z.ZodType<Options>;\n /** Further problems with a view, e.g. options naming a query the view doesn't have. */\n issues?: (view: ResolvedView<Options>) => string[];\n /**\n * Shows the widget even when a page filter can't apply to some of its queries: its views say so\n * on their own, checking `blocked` (a table's tabs).\n */\n partial?: boolean;\n /**\n * The queries the page's gates check, given what the user picked. Defaults to every view's, so\n * pick only the views the widget shows: a closed view's trace query mustn't hide an open metrics one.\n */\n gatedQueries?: (views: WidgetPlanContext<Options>['views'], state: WidgetState) => DashboardQuery[];\n /** Requests whose answers decide what `requests` asks (the scorers to chart, a table's opening tab). */\n discover?: (ctx: WidgetPlanContext<Options>) => WidgetRequests;\n /** The requests the widget renders from, given the answers to `discover`. */\n requests?: (ctx: WidgetPlanContext<Options>, discovered: (DashboardResult | undefined)[]) => WidgetRequests;\n component: ComponentType<WidgetKindProps<Options>>;\n};\n\n/** Keeps a kind's options type while it joins a list of kinds of different options. */\nexport const defineWidgetKind = <Options>(kind: WidgetKind<Options>): WidgetKind<Options> => kind;\n\n/** A registry entry, whatever its options. */\nexport type AnyWidgetKind = WidgetKind<any>;\n"],"mappings":";;AA2JA,IAAa,oBAA6B,SAAmD"}
@@ -13,9 +13,9 @@ const require_domains_dashboards_hooks_use_widget_views = require("./dashboards/
13
13
  const require_domains_dashboards_kinds_kpis_options = require("./dashboards/kinds/kpis/options.cjs.js");
14
14
  const require_domains_dashboards_kinds_kpis = require("./dashboards/kinds/kpis.cjs.js");
15
15
  const require_domains_dashboards_kinds_scores_options = require("./dashboards/kinds/scores/options.cjs.js");
16
+ const require_domains_dashboards_lib_plan_widget = require("./dashboards/lib/plan-widget.cjs.js");
16
17
  const require_domains_dashboards_kinds_scores = require("./dashboards/kinds/scores.cjs.js");
17
18
  const require_domains_dashboards_lib_table = require("./dashboards/lib/table.cjs.js");
18
- const require_domains_dashboards_lib_plan_widget = require("./dashboards/lib/plan-widget.cjs.js");
19
19
  const require_domains_dashboards_kinds_table = require("./dashboards/kinds/table.cjs.js");
20
20
  const require_domains_dashboards_lib_timeseries = require("./dashboards/lib/timeseries.cjs.js");
21
21
  const require_domains_dashboards_kinds_timeseries = require("./dashboards/kinds/timeseries.cjs.js");
@@ -12,9 +12,9 @@ import { hasDrilldownAction, useDrilldown, useViewMenu, viewMenu } from "./dashb
12
12
  import { KPI_ICONS, kpiItemSchema, kpisOptionsSchema } from "./dashboards/kinds/kpis/options.es.js";
13
13
  import { kpisKind } from "./dashboards/kinds/kpis.es.js";
14
14
  import { scoresOptionsSchema } from "./dashboards/kinds/scores/options.es.js";
15
+ import { planWidget } from "./dashboards/lib/plan-widget.es.js";
15
16
  import { scoresKind } from "./dashboards/kinds/scores.es.js";
16
17
  import { tableColumnOptionsSchema, tableOptionsSchema } from "./dashboards/lib/table.es.js";
17
- import { planWidget } from "./dashboards/lib/plan-widget.es.js";
18
18
  import { tableKind } from "./dashboards/kinds/table.es.js";
19
19
  import { timeseriesOptionsSchema, timeseriesSeriesSchema } from "./dashboards/lib/timeseries.es.js";
20
20
  import { timeseriesKind } from "./dashboards/kinds/timeseries.es.js";
@@ -56,12 +56,12 @@ function BreakdownTable({ tab, groupBy, window, aggregate, totals, spans, resour
56
56
  totals,
57
57
  spans
58
58
  ].filter((q) => q !== void 0);
59
- if (current.some((q) => q.isError)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_metrics_components_breakdown_breakdown_frame.BreakdownFrame, {
59
+ const isLoading = current.some((q) => q.isLoading);
60
+ if (!current.some((q) => q.isFetching) && current.some((q) => q.isError)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_metrics_components_breakdown_breakdown_frame.BreakdownFrame, {
60
61
  ...frame,
61
62
  tab,
62
63
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_metrics_components_chart_card_error.ChartCardError, { onRetry: () => current.forEach((q) => q.isError && void q.refetch()) })
63
64
  });
64
- const isLoading = current.some((q) => q.isLoading);
65
65
  const errors = require_domains_metrics_lib_breakdown.hasErrors(tab);
66
66
  const usage = totals !== void 0;
67
67
  const project = require_domains_metrics_lib_breakdown_table.showsProject(tab, frame.byProject);
@@ -1 +1 @@
1
- {"version":3,"file":"breakdown-table.cjs.js","names":["useMetricsScope","useState","isChangeMetric","BreakdownFrame","ChartCardError","hasErrors","showsProject","buildBreakdownRows","threadResources","previousFigures","tableRows","volumeLabel","rowChange","BreakdownRowName","BreakdownText","BreakdownFigure","formatPercent","formatDuration","formatCount","BreakdownCostCell","countDescription","BreakdownChangeDescription","comparedLabel","BreakdownChangeCell","ChartArea","MetricsTable","drilldownFor","Txt"],"sources":["../../../../../src/domains/metrics/components/breakdown/breakdown-table.tsx"],"sourcesContent":["import type { AggregateTracesResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMetricsScope } from '../../hooks/use-metrics-scope';\nimport type { useMetricsUsageTotals } from '../../hooks/use-metrics-usage-totals';\nimport { buildBreakdownRows, hasErrors, previousFigures, rowChange, threadResources } from '../../lib/breakdown';\nimport type { BreakdownRow, BreakdownTab, ChangeMetric } from '../../lib/breakdown';\nimport {\n DASH,\n comparedLabel,\n countDescription,\n drilldownFor,\n isChangeMetric,\n showsProject,\n tableRows,\n volumeLabel,\n} from '../../lib/breakdown-table';\nimport { formatCount, formatDuration, formatPercent } from '../../lib/chart-format';\nimport { ChartArea } from '../chart-area';\nimport { ChartCardError } from '../chart-card-error';\nimport { BreakdownChangeCell } from './breakdown-change-cell';\nimport { BreakdownChangeDescription } from './breakdown-change-description';\nimport { BreakdownCostCell } from './breakdown-cost-cell';\nimport { BreakdownFigure } from './breakdown-figure';\nimport { BreakdownFrame } from './breakdown-frame';\nimport type { BreakdownFrameProps } from './breakdown-frame';\nimport { BreakdownRowName } from './breakdown-row-name';\nimport { BreakdownText } from './breakdown-text';\nimport { MetricsTable } from '@/ds/components/MetricsTable';\nimport type { MetricsTableColumn, MetricsTableSort } from '@/ds/components/MetricsTable';\nimport { Txt } from '@/ds/components/Txt';\n\ntype UsageTotals = ReturnType<typeof useMetricsUsageTotals>;\n\nconst PAGE_SIZE = 10;\n\n/** Busiest first; where a third click on a column's header returns to. */\nconst DEFAULT_SORT: MetricsTableSort = { column: 'count', direction: 'desc' };\n\n/** The first column's header: what each row is. */\nconst NAME_HEADER: Record<BreakdownTab, string> = {\n projects: 'Project',\n agents: 'Agent',\n workflows: 'Workflow',\n tools: 'Tool',\n models: 'Model',\n threads: 'Thread',\n environments: 'Environment',\n};\n\nconst EMPTY: Record<BreakdownTab, string> = {\n projects: 'No traces in this range.',\n agents: 'No agent runs in this range.',\n workflows: 'No workflow runs in this range.',\n tools: 'No tool calls in this range.',\n models: 'No model usage in this range.',\n threads: 'No traces with a thread in this range.',\n environments: 'No traces in this range.',\n};\n\nexport type BreakdownTableProps = BreakdownFrameProps & {\n tab: BreakdownTab;\n groupBy: string[];\n window: { start: Date; end: Date };\n aggregate?: UseQueryResult<AggregateTracesResponse>;\n /** Tokens and cost per row. */\n totals?: UsageTotals;\n /** Model spans per row (Models tab). */\n spans?: UsageTotals;\n /** Rows naming each thread's resource (Threads tab). */\n resources?: UseQueryResult<AggregateTracesResponse>;\n previousAggregate?: UseQueryResult<AggregateTracesResponse>;\n previousUsage?: UsageTotals;\n previousSpans?: UsageTotals;\n /** The server's row cap, named when it truncates. */\n limit: number;\n};\n\n/** One tab's sortable table, with % Change against the previous window. */\nexport function BreakdownTable({\n tab,\n groupBy,\n window,\n aggregate,\n totals,\n spans,\n resources,\n previousAggregate,\n previousUsage,\n previousSpans,\n limit,\n ...frame\n}: BreakdownTableProps) {\n const scope = useMetricsScope();\n const [sort, setSort] = useState<MetricsTableSort>(DEFAULT_SORT);\n const [metric, setMetric] = useState<ChangeMetric>('count');\n const onSortChange = (next = DEFAULT_SORT) => {\n setSort(next);\n if (isChangeMetric(next.column)) setMetric(next.column);\n };\n\n const current = [aggregate, totals, spans].filter(q => q !== undefined);\n if (current.some(q => q.isError)) {\n return (\n <BreakdownFrame {...frame} tab={tab}>\n <ChartCardError onRetry={() => current.forEach(q => q.isError && void q.refetch())} />\n </BreakdownFrame>\n );\n }\n\n const isLoading = current.some(q => q.isLoading);\n const errors = hasErrors(tab);\n const usage = totals !== undefined;\n const project = showsProject(tab, frame.byProject);\n const truncated = aggregate?.data?.truncated === true;\n const built = isLoading\n ? []\n : buildBreakdownRows({\n tab,\n groupBy,\n aggregateRows: aggregate?.data?.rows,\n usageGroups: totals?.data?.groups,\n spanGroups: spans?.data?.groups,\n // The resource is a nicety: the table doesn't wait for it, and shows a dash without it.\n resources: resources?.data ? threadResources(resources.data.rows) : undefined,\n });\n // The previous window never holds the table up: until it answers, or if it fails, Change shows a dash.\n const previousSettled = [previousAggregate, previousUsage, previousSpans].every(\n q => !q || (!q.isLoading && !q.isError),\n );\n const previous =\n previousSettled && !isLoading\n ? previousFigures({\n tab,\n groupBy,\n aggregateRows: previousAggregate?.data?.rows,\n usageGroups: previousUsage?.data?.groups,\n spanGroups: previousSpans?.data?.groups,\n })\n : undefined;\n const rows = tableRows({ tab, built, previous, truncated, groupBy, usage });\n const volume = volumeLabel(tab);\n\n const changeOf = (row: BreakdownRow) => (previous ? rowChange(row, previous.get(row.key), metric) : undefined);\n const projectName = (row: BreakdownRow) => {\n if (!row.projectId) return DASH;\n return scope.projectLabel?.(row.projectId) ?? row.projectId;\n };\n\n const nameColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'name',\n header: NAME_HEADER[tab],\n width: 'minmax(12rem,3fr)',\n cell: row => <BreakdownRowName tab={tab} row={row} />,\n };\n const projectColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'project',\n header: 'Project',\n width: 'minmax(8rem,2fr)',\n cell: row => <BreakdownText text={projectName(row)} />,\n };\n const resourceColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'resource',\n header: 'Resource',\n width: 'minmax(6rem,1fr)',\n cell: row => <BreakdownText text={row.resource ?? DASH} />,\n };\n const errorColumns: MetricsTableColumn<BreakdownRow>[] = [\n {\n id: 'errorRate',\n header: 'Errors',\n align: 'end',\n sortValue: row => row.errorRate,\n cell: row => (\n <BreakdownFigure muted>{row.errorRate === undefined ? DASH : formatPercent(row.errorRate)}</BreakdownFigure>\n ),\n },\n {\n id: 'p95',\n header: 'P95 latency',\n align: 'end',\n sortValue: row => row.p95,\n cell: row => <BreakdownFigure muted>{row.p95 === undefined ? DASH : formatDuration(row.p95)}</BreakdownFigure>,\n },\n ];\n const usageColumns: MetricsTableColumn<BreakdownRow>[] = [\n {\n id: 'tokens',\n header: 'Tokens',\n align: 'end',\n sortValue: row => row.tokens,\n cell: row => <BreakdownFigure muted>{row.tokens === undefined ? DASH : formatCount(row.tokens)}</BreakdownFigure>,\n },\n {\n id: 'cost',\n header: 'Cost',\n align: 'end',\n sortValue: row => row.cost,\n cell: row => (\n <BreakdownFigure muted>\n <BreakdownCostCell row={row} />\n </BreakdownFigure>\n ),\n },\n ];\n const countColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'count',\n header: volume,\n align: 'end',\n description: countDescription(tab),\n sortValue: row => row.count,\n cell: row => <BreakdownFigure>{formatCount(row.count)}</BreakdownFigure>,\n };\n const changeColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'change',\n header: '% Change',\n align: 'end',\n description: <BreakdownChangeDescription window={window} label={comparedLabel(tab, metric)} />,\n // Sorted by the change shown: biggest rise first, biggest fall first the other way. New rows\n // have no change to rank, so they sort last.\n sortValue: row => changeOf(row)?.change,\n cell: row => (\n <BreakdownFigure>\n <BreakdownChangeCell change={changeOf(row)} metric={metric} />\n </BreakdownFigure>\n ),\n };\n const columns = [\n nameColumn,\n ...(project ? [projectColumn] : []),\n ...(tab === 'threads' ? [resourceColumn] : []),\n ...(errors ? errorColumns : []),\n ...(usage ? usageColumns : []),\n countColumn,\n changeColumn,\n ];\n\n return (\n <BreakdownFrame {...frame} tab={tab} isUpdating={aggregate?.isPlaceholderData}>\n <ChartArea>\n <MetricsTable\n key={tab}\n aria-label={`${NAME_HEADER[tab]} breakdown`}\n columns={columns}\n rows={rows}\n getRowKey={row => row.key}\n sort={sort}\n defaultSort={DEFAULT_SORT}\n onSortChange={onSortChange}\n onRowClick={frame.onRowClick && (row => frame.onRowClick?.(drilldownFor(tab, row)))}\n pageSize={PAGE_SIZE}\n isLoading={isLoading}\n empty={EMPTY[tab]}\n />\n {!isLoading && truncated && (\n <Txt variant=\"caption\" tone=\"muted\" className=\"pt-2\">\n Showing the {formatCount(limit)} busiest; sorting covers only these.\n </Txt>\n )}\n </ChartArea>\n </BreakdownFrame>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkCA,IAAM,YAAY;;AAGlB,IAAM,eAAiC;CAAE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;GAC7B;EAEE,CAAA,CAAA,EAAA,CAAA;CACG,CAAA;AAEpB"}
1
+ {"version":3,"file":"breakdown-table.cjs.js","names":["useMetricsScope","useState","isChangeMetric","BreakdownFrame","ChartCardError","hasErrors","showsProject","buildBreakdownRows","threadResources","previousFigures","tableRows","volumeLabel","rowChange","BreakdownRowName","BreakdownText","BreakdownFigure","formatPercent","formatDuration","formatCount","BreakdownCostCell","countDescription","BreakdownChangeDescription","comparedLabel","BreakdownChangeCell","ChartArea","MetricsTable","drilldownFor","Txt"],"sources":["../../../../../src/domains/metrics/components/breakdown/breakdown-table.tsx"],"sourcesContent":["import type { AggregateTracesResponse } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useState } from 'react';\nimport { useMetricsScope } from '../../hooks/use-metrics-scope';\nimport type { useMetricsUsageTotals } from '../../hooks/use-metrics-usage-totals';\nimport { buildBreakdownRows, hasErrors, previousFigures, rowChange, threadResources } from '../../lib/breakdown';\nimport type { BreakdownRow, BreakdownTab, ChangeMetric } from '../../lib/breakdown';\nimport {\n DASH,\n comparedLabel,\n countDescription,\n drilldownFor,\n isChangeMetric,\n showsProject,\n tableRows,\n volumeLabel,\n} from '../../lib/breakdown-table';\nimport { formatCount, formatDuration, formatPercent } from '../../lib/chart-format';\nimport { ChartArea } from '../chart-area';\nimport { ChartCardError } from '../chart-card-error';\nimport { BreakdownChangeCell } from './breakdown-change-cell';\nimport { BreakdownChangeDescription } from './breakdown-change-description';\nimport { BreakdownCostCell } from './breakdown-cost-cell';\nimport { BreakdownFigure } from './breakdown-figure';\nimport { BreakdownFrame } from './breakdown-frame';\nimport type { BreakdownFrameProps } from './breakdown-frame';\nimport { BreakdownRowName } from './breakdown-row-name';\nimport { BreakdownText } from './breakdown-text';\nimport { MetricsTable } from '@/ds/components/MetricsTable';\nimport type { MetricsTableColumn, MetricsTableSort } from '@/ds/components/MetricsTable';\nimport { Txt } from '@/ds/components/Txt';\n\ntype UsageTotals = ReturnType<typeof useMetricsUsageTotals>;\n\nconst PAGE_SIZE = 10;\n\n/** Busiest first; where a third click on a column's header returns to. */\nconst DEFAULT_SORT: MetricsTableSort = { column: 'count', direction: 'desc' };\n\n/** The first column's header: what each row is. */\nconst NAME_HEADER: Record<BreakdownTab, string> = {\n projects: 'Project',\n agents: 'Agent',\n workflows: 'Workflow',\n tools: 'Tool',\n models: 'Model',\n threads: 'Thread',\n environments: 'Environment',\n};\n\nconst EMPTY: Record<BreakdownTab, string> = {\n projects: 'No traces in this range.',\n agents: 'No agent runs in this range.',\n workflows: 'No workflow runs in this range.',\n tools: 'No tool calls in this range.',\n models: 'No model usage in this range.',\n threads: 'No traces with a thread in this range.',\n environments: 'No traces in this range.',\n};\n\nexport type BreakdownTableProps = BreakdownFrameProps & {\n tab: BreakdownTab;\n groupBy: string[];\n window: { start: Date; end: Date };\n aggregate?: UseQueryResult<AggregateTracesResponse>;\n /** Tokens and cost per row. */\n totals?: UsageTotals;\n /** Model spans per row (Models tab). */\n spans?: UsageTotals;\n /** Rows naming each thread's resource (Threads tab). */\n resources?: UseQueryResult<AggregateTracesResponse>;\n previousAggregate?: UseQueryResult<AggregateTracesResponse>;\n previousUsage?: UsageTotals;\n previousSpans?: UsageTotals;\n /** The server's row cap, named when it truncates. */\n limit: number;\n};\n\n/** One tab's sortable table, with % Change against the previous window. */\nexport function BreakdownTable({\n tab,\n groupBy,\n window,\n aggregate,\n totals,\n spans,\n resources,\n previousAggregate,\n previousUsage,\n previousSpans,\n limit,\n ...frame\n}: BreakdownTableProps) {\n const scope = useMetricsScope();\n const [sort, setSort] = useState<MetricsTableSort>(DEFAULT_SORT);\n const [metric, setMetric] = useState<ChangeMetric>('count');\n const onSortChange = (next = DEFAULT_SORT) => {\n setSort(next);\n if (isChangeMetric(next.column)) setMetric(next.column);\n };\n\n const current = [aggregate, totals, spans].filter(q => q !== undefined);\n const isLoading = current.some(q => q.isLoading);\n // One request failing says nothing about the others, which may still be running: report the\n // failure only once they have all settled, or Retry — which re-sends only the failed ones —\n // cannot recover a card whose remaining request is still in flight. A new scope keeps the\n // previous answer on screen, so `isLoading` is false there while `isFetching` is not.\n if (!current.some(q => q.isFetching) && current.some(q => q.isError)) {\n return (\n <BreakdownFrame {...frame} tab={tab}>\n <ChartCardError onRetry={() => current.forEach(q => q.isError && void q.refetch())} />\n </BreakdownFrame>\n );\n }\n\n const errors = hasErrors(tab);\n const usage = totals !== undefined;\n const project = showsProject(tab, frame.byProject);\n const truncated = aggregate?.data?.truncated === true;\n const built = isLoading\n ? []\n : buildBreakdownRows({\n tab,\n groupBy,\n aggregateRows: aggregate?.data?.rows,\n usageGroups: totals?.data?.groups,\n spanGroups: spans?.data?.groups,\n // The resource is a nicety: the table doesn't wait for it, and shows a dash without it.\n resources: resources?.data ? threadResources(resources.data.rows) : undefined,\n });\n // The previous window never holds the table up: until it answers, or if it fails, Change shows a dash.\n const previousSettled = [previousAggregate, previousUsage, previousSpans].every(\n q => !q || (!q.isLoading && !q.isError),\n );\n const previous =\n previousSettled && !isLoading\n ? previousFigures({\n tab,\n groupBy,\n aggregateRows: previousAggregate?.data?.rows,\n usageGroups: previousUsage?.data?.groups,\n spanGroups: previousSpans?.data?.groups,\n })\n : undefined;\n const rows = tableRows({ tab, built, previous, truncated, groupBy, usage });\n const volume = volumeLabel(tab);\n\n const changeOf = (row: BreakdownRow) => (previous ? rowChange(row, previous.get(row.key), metric) : undefined);\n const projectName = (row: BreakdownRow) => {\n if (!row.projectId) return DASH;\n return scope.projectLabel?.(row.projectId) ?? row.projectId;\n };\n\n const nameColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'name',\n header: NAME_HEADER[tab],\n width: 'minmax(12rem,3fr)',\n cell: row => <BreakdownRowName tab={tab} row={row} />,\n };\n const projectColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'project',\n header: 'Project',\n width: 'minmax(8rem,2fr)',\n cell: row => <BreakdownText text={projectName(row)} />,\n };\n const resourceColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'resource',\n header: 'Resource',\n width: 'minmax(6rem,1fr)',\n cell: row => <BreakdownText text={row.resource ?? DASH} />,\n };\n const errorColumns: MetricsTableColumn<BreakdownRow>[] = [\n {\n id: 'errorRate',\n header: 'Errors',\n align: 'end',\n sortValue: row => row.errorRate,\n cell: row => (\n <BreakdownFigure muted>{row.errorRate === undefined ? DASH : formatPercent(row.errorRate)}</BreakdownFigure>\n ),\n },\n {\n id: 'p95',\n header: 'P95 latency',\n align: 'end',\n sortValue: row => row.p95,\n cell: row => <BreakdownFigure muted>{row.p95 === undefined ? DASH : formatDuration(row.p95)}</BreakdownFigure>,\n },\n ];\n const usageColumns: MetricsTableColumn<BreakdownRow>[] = [\n {\n id: 'tokens',\n header: 'Tokens',\n align: 'end',\n sortValue: row => row.tokens,\n cell: row => <BreakdownFigure muted>{row.tokens === undefined ? DASH : formatCount(row.tokens)}</BreakdownFigure>,\n },\n {\n id: 'cost',\n header: 'Cost',\n align: 'end',\n sortValue: row => row.cost,\n cell: row => (\n <BreakdownFigure muted>\n <BreakdownCostCell row={row} />\n </BreakdownFigure>\n ),\n },\n ];\n const countColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'count',\n header: volume,\n align: 'end',\n description: countDescription(tab),\n sortValue: row => row.count,\n cell: row => <BreakdownFigure>{formatCount(row.count)}</BreakdownFigure>,\n };\n const changeColumn: MetricsTableColumn<BreakdownRow> = {\n id: 'change',\n header: '% Change',\n align: 'end',\n description: <BreakdownChangeDescription window={window} label={comparedLabel(tab, metric)} />,\n // Sorted by the change shown: biggest rise first, biggest fall first the other way. New rows\n // have no change to rank, so they sort last.\n sortValue: row => changeOf(row)?.change,\n cell: row => (\n <BreakdownFigure>\n <BreakdownChangeCell change={changeOf(row)} metric={metric} />\n </BreakdownFigure>\n ),\n };\n const columns = [\n nameColumn,\n ...(project ? [projectColumn] : []),\n ...(tab === 'threads' ? [resourceColumn] : []),\n ...(errors ? errorColumns : []),\n ...(usage ? usageColumns : []),\n countColumn,\n changeColumn,\n ];\n\n return (\n <BreakdownFrame {...frame} tab={tab} isUpdating={aggregate?.isPlaceholderData}>\n <ChartArea>\n <MetricsTable\n key={tab}\n aria-label={`${NAME_HEADER[tab]} breakdown`}\n columns={columns}\n rows={rows}\n getRowKey={row => row.key}\n sort={sort}\n defaultSort={DEFAULT_SORT}\n onSortChange={onSortChange}\n onRowClick={frame.onRowClick && (row => frame.onRowClick?.(drilldownFor(tab, row)))}\n pageSize={PAGE_SIZE}\n isLoading={isLoading}\n empty={EMPTY[tab]}\n />\n {!isLoading && truncated && (\n <Txt variant=\"caption\" tone=\"muted\" className=\"pt-2\">\n Showing the {formatCount(limit)} busiest; sorting covers only these.\n </Txt>\n )}\n </ChartArea>\n </BreakdownFrame>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkCA,IAAM,YAAY;;AAGlB,IAAM,eAAiC;CAAE,QAAQ;CAAS,WAAW;AAAO;;AAG5E,IAAM,cAA4C;CAChD,UAAU;CACV,QAAQ;CACR,WAAW;CACX,OAAO;CACP,QAAQ;CACR,SAAS;CACT,cAAc;AAChB;AAEA,IAAM,QAAsC;CAC1C,UAAU;CACV,QAAQ;CACR,WAAW;CACX,OAAO;CACP,QAAQ;CACR,SAAS;CACT,cAAc;AAChB;;AAqBA,SAAgB,eAAe,EAC7B,KACA,SACA,QACA,WACA,QACA,OACA,WACA,mBACA,eACA,eACA,OACA,GAAG,SACmB;CACtB,MAAM,QAAQA,gDAAAA,gBAAgB;CAC9B,MAAM,CAAC,MAAM,YAAA,GAAWC,MAAAA,SAAAA,CAA2B,YAAY;CAC/D,MAAM,CAAC,QAAQ,cAAA,GAAaA,MAAAA,SAAAA,CAAuB,OAAO;CAC1D,MAAM,gBAAgB,OAAO,iBAAiB;EAC5C,QAAQ,IAAI;EACZ,IAAIC,4CAAAA,eAAe,KAAK,MAAM,GAAG,UAAU,KAAK,MAAM;CACxD;CAEA,MAAM,UAAU;EAAC;EAAW;EAAQ;CAAK,CAAC,CAAC,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,OACE,iBAAA,GAAA,kBAAA,IAAA,CAACpB,6DAAAA,gBAAD;EAAgB,GAAI;EAAY;EAAK,YAAY,WAAW;EAC1D,UAAA,iBAAA,GAAA,kBAAA,KAAA,CAACqB,8CAAAA,WAAD,EAAA,UAAA,CACE,iBAAA,GAAA,kBAAA,IAAA,CAACC,qBAAAA,cAAD;GAEE,cAAY,GAAG,YAAY,KAAK;GACvB;GACH;GACN,YAAW,QAAO,IAAI;GAChB;GACN,aAAa;GACC;GACd,YAAY,MAAM,gBAAe,QAAO,MAAM,aAAaC,4CAAAA,aAAa,KAAK,GAAG,CAAC;GACjF,UAAU;GACC;GACX,OAAO,MAAM;EACd,GAZM,GAYN,GACA,CAAC,aAAa,aACb,iBAAA,GAAA,kBAAA,KAAA,CAACC,YAAAA,KAAD;GAAK,SAAQ;GAAU,MAAK;GAAQ,WAAU;GAA9C,UAAA;IAAqD;IACtCT,yCAAAA,YAAY,KAAK;IAAE;GAC7B;EAEE,CAAA,CAAA,EAAA,CAAA;CACG,CAAA;AAEpB"}
@@ -55,12 +55,12 @@ function BreakdownTable({ tab, groupBy, window, aggregate, totals, spans, resour
55
55
  totals,
56
56
  spans
57
57
  ].filter((q) => q !== void 0);
58
- if (current.some((q) => q.isError)) return /* @__PURE__ */ jsx(BreakdownFrame, {
58
+ const isLoading = current.some((q) => q.isLoading);
59
+ if (!current.some((q) => q.isFetching) && current.some((q) => q.isError)) return /* @__PURE__ */ jsx(BreakdownFrame, {
59
60
  ...frame,
60
61
  tab,
61
62
  children: /* @__PURE__ */ jsx(ChartCardError, { onRetry: () => current.forEach((q) => q.isError && void q.refetch()) })
62
63
  });
63
- const isLoading = current.some((q) => q.isLoading);
64
64
  const errors = hasErrors(tab);
65
65
  const usage = totals !== void 0;
66
66
  const project = showsProject(tab, frame.byProject);