Skip to content

The only tool you need to know what is happening and how to fix it.

feat: added gauge metric component (#267)

narrow-adventure915fdd77c54d
diff --git a/CLAUDE.md b/CLAUDE.md
index 5f08fefc..aec16f7b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1252,38 +1252,53 @@ traceway.Init(appName, connectionString,
### Data Format (Frame)
-The SDK sends data as gzipped JSON:
+The SDK sends data as gzipped JSON. The wire shape is `ReportRequest` in `backend/app/controllers/clientcontrollers/client.controller.go` wrapping `CollectionFrame` from `backend/app/models/clientmodels/`:
+
```json
{
- "app": "myapp",
- "transactions": [
- {
- "trace_id": "abc123",
- "endpoint": "GET /api/users",
- "duration_ms": 45.2,
- "status_code": 200,
- "timestamp": "2024-01-15T10:30:00Z"
- }
- ],
- "exceptions": [
+ "appVersion": "1.2.3",
+ "serverName": "myapp-host-1",
+ "collectionFrames": [
{
- "type": "RuntimeError",
- "value": "connection refused",
- "stacktrace": "...",
- "tags": {"user_id": "123"},
- "timestamp": "2024-01-15T10:30:00Z"
- }
- ],
- "metrics": [
- {
- "name": "cpu.used_pcnt",
- "value": 45.2,
- "timestamp": "2024-01-15T10:30:00Z"
+ "traces": [
+ {
+ "id": "5b8e1a2f-3c4d-4e5f-8a9b-0c1d2e3f4a5b",
+ "endpoint": "GET /api/users",
+ "duration": 45200000,
+ "statusCode": 200,
+ "recordedAt": "2024-01-15T10:30:00Z",
+ "isTask": false,
+ "attributes": {},
+ "spans": []
+ }
+ ],
+ "stackTraces": [
+ {
+ "stackTrace": "RuntimeError: connection refused\n at ...",
+ "recordedAt": "2024-01-15T10:30:00Z",
+ "attributes": {"user_id": "123"},
+ "isMessage": false,
+ "isTask": false
+ }
+ ],
+ "metrics": [
+ {
+ "name": "cpu.used_pcnt",
+ "value": 45.2,
+ "recordedAt": "2024-01-15T10:30:00Z",
+ "tags": {}
+ }
+ ]
}
]
}
```
+Notes:
+- Timestamps are `recordedAt` (RFC 3339), never `timestamp`. `duration` is a Go `time.Duration`, i.e. integer nanoseconds (45200000 = 45.2ms).
+- Endpoints vs tasks share the `traces` array, split by `isTask`. `CollectionFrame` also carries `sessionRecordings` and `sessions`.
+- **Unknown fields are silently ignored**: a payload in the wrong shape (e.g. top-level `metrics`) still returns 200 but inserts nothing. When hand-crafting test payloads, confirm ingestion landed via `POST /api/metrics/query` (or the relevant list endpoint) instead of trusting the status code.
+
---
## Common Patterns
diff --git a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
index 3adaa033..9c1835b5 100644
--- a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
@@ -30,6 +30,9 @@ func (r *metricPointRepository) InsertAsync(ctx context.Context, points []models
func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId uuid.UUID, name string, from, to time.Time, intervalMinutes int, aggregation string, tagFilters map[string]string, groupBy string) (map[string][]models.TimeSeriesPoint, error) {
table := selectTable(to.Sub(from))
+ if aggregation == "last" {
+ table = "metric_points"
+ }
aggFunc := aggregationFunc(aggregation, table)
@@ -162,6 +165,8 @@ func aggregationFunc(agg string, table string) string {
return "sum(value)"
case "count":
return "toFloat64(count())"
+ case "last":
+ return "argMax(value, recorded_at)"
default:
return "avg(value)"
}
diff --git a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
index 2a3262e3..5eeba426 100644
--- a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
@@ -304,6 +304,8 @@ func duckdbAggregationFunc(agg string) string {
return "sum(value)"
case "count":
return "CAST(COUNT(*) AS DOUBLE)"
+ case "last":
+ return "arg_max(value, recorded_at)"
default:
return "avg(value)"
}
diff --git a/backend/app/repositories/telemetry/metric_point_repository_test.go b/backend/app/repositories/telemetry/metric_point_repository_test.go
index df1e8adf..082d465b 100644
--- a/backend/app/repositories/telemetry/metric_point_repository_test.go
+++ b/backend/app/repositories/telemetry/metric_point_repository_test.go
@@ -336,3 +336,65 @@ func TestMetricPointRepository_QueryTimeSeries_Aggregations(t *testing.T) {
series = result["__all__"]
assertApproxEqual(t, "sum", series[0].Value, 600.0, 0.1)
}
+
+func TestMetricPointRepository_QueryTimeSeries_LastAggregation(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour)
+
+ points := []models.MetricPoint{
+ makeMetricPoint(projectId, "response_time", 100.0, nil, base),
+ makeMetricPoint(projectId, "response_time", 300.0, nil, base.Add(time.Minute)),
+ makeMetricPoint(projectId, "response_time", 250.0, nil, base.Add(2*time.Minute)),
+ }
+
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ from := base.Add(-time.Minute)
+ to := base.Add(time.Hour)
+
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "response_time", from, to, 60, "last", nil, "")
+ if err != nil {
+ t.Fatalf("QueryTimeSeries last failed: %v", err)
+ }
+ series := result["__all__"]
+ if len(series) != 1 {
+ t.Fatalf("expected 1 bucket, got %d", len(series))
+ }
+ assertApproxEqual(t, "last", series[0].Value, 250.0, 0.1)
+}
+
+func TestMetricPointRepository_QueryTimeSeries_LastAggregationWithGroupBy(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour)
+
+ points := []models.MetricPoint{
+ makeMetricPoint(projectId, "disk.used", 10.0, map[string]string{"disk": "sda"}, base),
+ makeMetricPoint(projectId, "disk.used", 50.0, map[string]string{"disk": "sda"}, base.Add(time.Minute)),
+ makeMetricPoint(projectId, "disk.used", 40.0, map[string]string{"disk": "sda"}, base.Add(2*time.Minute)),
+ makeMetricPoint(projectId, "disk.used", 90.0, map[string]string{"disk": "sdb"}, base.Add(time.Minute)),
+ makeMetricPoint(projectId, "disk.used", 70.0, map[string]string{"disk": "sdb"}, base.Add(3*time.Minute)),
+ }
+
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ from := base.Add(-time.Minute)
+ to := base.Add(time.Hour)
+
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "disk.used", from, to, 60, "last", nil, "disk")
+ if err != nil {
+ t.Fatalf("QueryTimeSeries last with groupBy failed: %v", err)
+ }
+ if len(result["sda"]) != 1 || len(result["sdb"]) != 1 {
+ t.Fatalf("expected 1 bucket per group, got sda=%d sdb=%d", len(result["sda"]), len(result["sdb"]))
+ }
+ assertApproxEqual(t, "last sda", result["sda"][0].Value, 40.0, 0.1)
+ assertApproxEqual(t, "last sdb", result["sdb"][0].Value, 70.0, 0.1)
+}
diff --git a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
index acae1f93..20a4606f 100644
--- a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
@@ -72,12 +72,17 @@ func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId u
secs := intervalMinutes * 60
aggFunc := sqliteAggregationFunc(aggregation)
hasGroupBy := groupBy != ""
+ isLast := aggregation == "last"
selectClause := fmt.Sprintf("SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') AS bucket", secs, secs)
if hasGroupBy {
selectClause += ", json_extract(tags, '$.\"' || :group_by || '\"') AS group_key"
}
- selectClause += ", " + aggFunc + " AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
+ selectClause += ", " + aggFunc + " AS agg_value"
+ if isLast {
+ selectClause += ", max(recorded_at) AS last_ts"
+ }
+ selectClause += " FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
params := lit.P{
"project_id": projectId,
@@ -119,20 +124,23 @@ func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId u
for rows.Next() {
var bucketStr string
var value float64
+ var groupKeyNullable *string
+ var lastTs string
groupKey := "__all__"
+ targets := []any{&bucketStr}
if hasGroupBy {
- var groupKeyNullable *string
- if err := rows.Scan(&bucketStr, &groupKeyNullable, &value); err != nil {
- return nil, err
- }
- if groupKeyNullable != nil {
- groupKey = *groupKeyNullable
- }
- } else {
- if err := rows.Scan(&bucketStr, &value); err != nil {
- return nil, err
- }
+ targets = append(targets, &groupKeyNullable)
+ }
+ targets = append(targets, &value)
+ if isLast {
+ targets = append(targets, &lastTs)
+ }
+ if err := rows.Scan(targets...); err != nil {
+ return nil, err
+ }
+ if groupKeyNullable != nil {
+ groupKey = *groupKeyNullable
}
bucket, err := time.Parse("2006-01-02 15:04:05", bucketStr)
@@ -328,6 +336,8 @@ func sqliteAggregationFunc(agg string) string {
return "sum(value)"
case "count":
return "CAST(COUNT(*) AS REAL)"
+ case "last":
+ return "value"
default:
return "avg(value)"
}
diff --git a/frontend/src/lib/components/dashboard/d3-gauge.svelte b/frontend/src/lib/components/dashboard/d3-gauge.svelte
new file mode 100644
index 00000000..ce80b24c
--- /dev/null
+++ b/frontend/src/lib/components/dashboard/d3-gauge.svelte
@@ -0,0 +1,143 @@
+<script lang="ts">
+ import { arc } from 'd3-shape';
+ import {
+ activeThresholdColor,
+ thresholdBandSegments,
+ type ThresholdStep
+ } from './gauge-thresholds';
+
+ let {
+ value,
+ min = 0,
+ max = 100,
+ baseColor = 'green',
+ thresholds = [],
+ formatValue = (v: number) => v.toString()
+ } = $props<{
+ value: number;
+ min?: number;
+ max?: number;
+ baseColor?: string;
+ thresholds?: ThresholdStep[];
+ formatValue?: (v: number) => string;
+ }>();
+
+ let containerRef = $state<HTMLDivElement | null>(null);
+ let width = $state(0);
+ let height = $state(0);
+
+ $effect(() => {
+ if (!containerRef) return;
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ width = entry.contentRect.width;
+ height = entry.contentRect.height;
+ }
+ });
+ observer.observe(containerRef);
+ return () => observer.disconnect();
+ });
+
+ const START_ANGLE = (-3 * Math.PI) / 4;
+ const END_ANGLE = (3 * Math.PI) / 4;
+
+ const safeMax = $derived(max > min ? max : min + 1);
+
+ const radius = $derived(Math.max(0, Math.min((width - 16) / 2, (height - 34) / 1.71)));
+ const contentHeight = $derived(radius * 1.71 + 34);
+ const cx = $derived(width / 2);
+ const cy = $derived(radius + 6 + Math.max(0, (height - contentHeight) / 2));
+
+ const bandWidth = $derived(Math.max(3, radius * 0.06));
+ const arcWidth = $derived(Math.max(8, radius * 0.17));
+ const trackOuter = $derived(radius - bandWidth - 2);
+ const trackInner = $derived(Math.max(0, trackOuter - arcWidth));
+
+ function angleFor(v: number): number {
+ const t = (Math.min(Math.max(v, min), safeMax) - min) / (safeMax - min);
+ return START_ANGLE + t * (END_ANGLE - START_ANGLE);
+ }
+
+ const trackPath = $derived(
+ arc()({
+ innerRadius: trackInner,
+ outerRadius: trackOuter,
+ startAngle: START_ANGLE,
+ endAngle: END_ANGLE
+ }) ?? ''
+ );
+
+ const valuePath = $derived(
+ arc()({
+ innerRadius: trackInner,
+ outerRadius: trackOuter,
+ startAngle: START_ANGLE,
+ endAngle: angleFor(value)
+ }) ?? ''
+ );
+
+ const bandPaths = $derived(
+ thresholdBandSegments(min, safeMax, baseColor, thresholds).map((seg) => ({
+ color: seg.color,
+ path:
+ arc()({
+ innerRadius: radius - bandWidth,
+ outerRadius: radius,
+ startAngle: angleFor(seg.from),
+ endAngle: angleFor(seg.to)
+ }) ?? ''
+ }))
+ );
+
+ const valueColor = $derived(activeThresholdColor(value, baseColor, thresholds));
+ const valueLabel = $derived(formatValue(value));
+
+ const valueFontSize = $derived.by(() => {
+ const fit = (trackInner * 1.8) / Math.max(valueLabel.length * 0.58, 1);
+ return Math.max(12, Math.min(radius * 0.34, fit));
+ });
+
+ const endX = $derived(((trackInner + trackOuter) / 2) * Math.SQRT1_2);
+ const endY = $derived(trackOuter * Math.SQRT1_2 + 18);
+</script>
+
+<div bind:this={containerRef} class="h-full w-full">
+ {#if radius > 20}
+ <svg {width} {height}>
+ <g transform="translate({cx}, {cy})">
+ {#each bandPaths as seg}
+ <path d={seg.path} fill={seg.color} />
+ {/each}
+ <path d={trackPath} fill="var(--muted)" />
+ <path d={valuePath} fill={valueColor} />
+ <text
+ text-anchor="middle"
+ dominant-baseline="middle"
+ font-size={valueFontSize}
+ font-weight="700"
+ fill={valueColor}
+ >
+ {valueLabel}
+ </text>
+ <text
+ x={-endX}
+ y={endY}
+ text-anchor="middle"
+ font-size="11"
+ fill="var(--muted-foreground)"
+ >
+ {formatValue(min)}
+ </text>
+ <text
+ x={endX}
+ y={endY}
+ text-anchor="middle"
+ font-size="11"
+ fill="var(--muted-foreground)"
+ >
+ {formatValue(max)}
+ </text>
+ </g>
+ </svg>
+ {/if}
+</div>
diff --git a/frontend/src/lib/components/dashboard/gauge-thresholds.ts b/frontend/src/lib/components/dashboard/gauge-thresholds.ts
new file mode 100644
index 00000000..a18427e9
--- /dev/null
+++ b/frontend/src/lib/components/dashboard/gauge-thresholds.ts
@@ -0,0 +1,54 @@
+export type ThresholdStep = { value: number; color: string };
+
+export const THRESHOLD_COLORS: Record<string, string> = {
+ green: 'var(--ok)',
+ yellow: '#eab308',
+ orange: '#f97316',
+ red: 'var(--crit)',
+ blue: 'var(--blue)'
+};
+
+export const THRESHOLD_COLOR_NAMES = Object.keys(THRESHOLD_COLORS);
+
+export function resolveThresholdColor(color: string): string {
+ return THRESHOLD_COLORS[color] ?? color;
+}
+
+export function sortThresholdSteps(steps: ThresholdStep[] | undefined): ThresholdStep[] {
+ return [...(steps ?? [])].sort((a, b) => a.value - b.value);
+}
+
+export function activeThresholdColor(
+ value: number,
+ baseColor: string | undefined,
+ steps: ThresholdStep[] | undefined
+): string {
+ let color = baseColor || 'green';
+ for (const step of sortThresholdSteps(steps)) {
+ if (value >= step.value) color = step.color;
+ }
+ return resolveThresholdColor(color);
+}
+
+export function thresholdBandSegments(
+ min: number,
+ max: number,
+ baseColor: string | undefined,
+ steps: ThresholdStep[] | undefined
+): Array<{ from: number; to: number; color: string }> {
+ const segments: Array<{ from: number; to: number; color: string }> = [];
+ let cursor = min;
+ let color = baseColor || 'green';
+ for (const step of sortThresholdSteps(steps)) {
+ const bounded = Math.min(Math.max(step.value, min), max);
+ if (bounded > cursor) {
+ segments.push({ from: cursor, to: bounded, color: resolveThresholdColor(color) });
+ cursor = bounded;
+ }
+ color = step.color;
+ }
+ if (cursor < max) {
+ segments.push({ from: cursor, to: max, color: resolveThresholdColor(color) });
+ }
+ return segments;
+}
diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
index 82facf82..d5651db9 100644
--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte
+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
@@ -3,12 +3,12 @@
import { Input } from '$lib/components/ui/input';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as Select from '$lib/components/ui/select';
- import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import * as Sheet from '$lib/components/ui/sheet';
import TagFilter from './tag-filter.svelte';
+ import { THRESHOLD_COLOR_NAMES, resolveThresholdColor } from './gauge-thresholds';
import { api } from '$lib/api';
import { projectsState } from '$lib/state/projects.svelte';
- import { Plus, Check, CircleAlert } from 'lucide-svelte';
- import * as Alert from '$lib/components/ui/alert';
+ import { Plus, Check, X } from 'lucide-svelte';
import { ErrorAlert } from '$lib/components/ui/error-alert';
import type { DiscoveredMetric } from '$lib/types/dashboard';
@@ -29,6 +29,20 @@
return 'auto';
}
+ function thresholdsFromConfig(
+ config: any,
+ savedType: string | undefined
+ ): Array<{ value: string; color: string }> {
+ if (Array.isArray(config?.thresholds) && config.thresholds.length > 0) {
+ return config.thresholds.map((t: { value: number; color: string }) => ({
+ value: String(t.value),
+ color: t.color
+ }));
+ }
+ if (savedType === 'single_value') return [];
+ return [{ value: '80', color: 'red' }];
+ }
+
let {
open = $bindable(false),
widget = null,
@@ -54,6 +68,12 @@
);
let legend = $state<'auto' | 'on' | 'off'>(legendFromConfig(widget?.config));
let showSparkline = $state(!!widget?.config?.showSparkline);
+ let gaugeMin = $state(widget?.config?.min != null ? String(widget.config.min) : '0');
+ let gaugeMax = $state(widget?.config?.max != null ? String(widget.config.max) : '100');
+ let baseColor = $state(widget?.config?.baseColor ?? 'green');
+ let thresholds = $state<Array<{ value: string; color: string }>>(
+ thresholdsFromConfig(widget?.config, widget?.widgetType)
+ );
$effect(() => {
if (open) {
@@ -66,9 +86,43 @@
: [{ type: 'metric', name: '', aggregation: 'avg' }];
legend = legendFromConfig(widget?.config);
showSparkline = !!widget?.config?.showSparkline;
+ gaugeMin = widget?.config?.min != null ? String(widget.config.min) : '0';
+ gaugeMax = widget?.config?.max != null ? String(widget.config.max) : '100';
+ baseColor = widget?.config?.baseColor ?? 'green';
+ thresholds = thresholdsFromConfig(widget?.config, widget?.widgetType);
}
});
+ function addThreshold() {
+ const values = thresholds
+ .map((t) => parseFloat(t.value))
+ .filter((v) => Number.isFinite(v));
+ const nextValue = values.length > 0 ? Math.max(...values) + 10 : 80;
+ const usedColors = new Set(thresholds.map((t) => t.color));
+ const nextColor =
+ ['red', 'yellow', 'orange', 'blue', 'green'].find((c) => !usedColors.has(c)) ?? 'red';
+ thresholds = [...thresholds, { value: String(nextValue), color: nextColor }];
+ }
+
+ function removeThreshold(index: number) {
+ thresholds = thresholds.filter((_, i) => i !== index);
+ }
+
+ function handleTypeChange(newType: string) {
+ const wasValueType = widgetType === 'gauge' || widgetType === 'single_value';
+ const isValueType = newType === 'gauge' || newType === 'single_value';
+ widgetType = newType;
+ if (isValueType && !wasValueType) {
+ for (const s of sources) {
+ if (s.aggregation === 'avg') s.aggregation = 'last';
+ }
+ } else if (!isValueType && wasValueType) {
+ for (const s of sources) {
+ if (s.aggregation === 'last') s.aggregation = 'avg';
+ }
+ }
+ }
+
function getMetricTagKeys(metricName: string): string[] {
const m = availableMetrics.find((m: DiscoveredMetric) => m.name === metricName);
return m?.tagKeys ?? [];
@@ -112,6 +166,20 @@
if (widget?.config?.size != null) config.size = widget.config.size;
if (CHART_TYPES.includes(widgetType) && legend !== 'auto') config.showLegend = legend === 'on';
if (widgetType === 'single_value' && showSparkline) config.showSparkline = true;
+ if (widgetType === 'gauge') {
+ const minValue = parseFloat(gaugeMin);
+ const maxValue = parseFloat(gaugeMax);
+ config.min = Number.isFinite(minValue) ? minValue : 0;
+ config.max = Number.isFinite(maxValue) ? maxValue : 100;
+ }
+ if (widgetType === 'gauge' || widgetType === 'single_value') {
+ if (baseColor !== 'green') config.baseColor = baseColor;
+ const steps = thresholds
+ .map((t) => ({ value: parseFloat(t.value), color: t.color }))
+ .filter((t) => Number.isFinite(t.value))
+ .sort((a, b) => a.value - b.value);
+ if (steps.length > 0) config.thresholds = steps;
+ }
onSave({
title: displayTitle,
widgetType,
@@ -125,13 +193,18 @@
}
</script>
-<AlertDialog.Root bind:open>
- <AlertDialog.Content class="max-w-xl" interactOutsideBehavior="close">
- <AlertDialog.Header>
- <AlertDialog.Title>{widget?.id ? 'Edit Widget' : 'New Widget'}</AlertDialog.Title>
- </AlertDialog.Header>
- <ErrorAlert {error} />
- <div class="space-y-4">
+<Sheet.Root
+ bind:open
+ onOpenChange={(v) => {
+ if (!v) onCancel();
+ }}
+>
+ <Sheet.Content side="right" class="w-full gap-0 sm:max-w-[520px]">
+ <Sheet.Header class="border-b px-6">
+ <Sheet.Title>{widget?.id ? 'Edit Widget' : 'New Widget'}</Sheet.Title>
+ </Sheet.Header>
+ <div class="flex-1 space-y-4 overflow-y-auto px-6 py-4">
+ <ErrorAlert {error} />
<div>
<label class="text-sm font-medium" for="widget-title">Title (optional)</label>
<Input id="widget-title" bind:value={title} placeholder="Defaults to metric name" />
@@ -143,11 +216,11 @@
type="single"
value={widgetType}
onValueChange={(v) => {
- if (v) widgetType = v;
+ if (v) handleTypeChange(v);
}}
>
<Select.Trigger>
- {({ line_chart: 'Line Chart', area_chart: 'Area Chart', stacked_area: 'Stacked Area', bar_chart: 'Bar Chart', single_value: 'Single Value', table: 'Table' } as Record<string, string>)[widgetType] ?? widgetType}
+ {({ line_chart: 'Line Chart', area_chart: 'Area Chart', stacked_area: 'Stacked Area', bar_chart: 'Bar Chart', single_value: 'Single Value', gauge: 'Gauge', table: 'Table' } as Record<string, string>)[widgetType] ?? widgetType}
</Select.Trigger>
<Select.Content>
<Select.Item value="line_chart">Line Chart</Select.Item>
@@ -155,6 +228,7 @@
<Select.Item value="stacked_area">Stacked Area</Select.Item>
<Select.Item value="bar_chart">Bar Chart</Select.Item>
<Select.Item value="single_value">Single Value</Select.Item>
+ <Select.Item value="gauge">Gauge</Select.Item>
<Select.Item value="table">Table</Select.Item>
</Select.Content>
</Select.Root>
@@ -199,6 +273,78 @@
</div>
{/if}
+ {#if widgetType === 'gauge'}
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <label class="text-sm font-medium" for="gauge-min">Min</label>
+ <Input id="gauge-min" type="number" bind:value={gaugeMin} />
+ </div>
+ <div>
+ <label class="text-sm font-medium" for="gauge-max">Max</label>
+ <Input id="gauge-max" type="number" bind:value={gaugeMax} />
+ </div>
+ </div>
+ {/if}
+
+ {#if widgetType === 'gauge' || widgetType === 'single_value'}
+ <div>
+ <span class="text-sm font-medium">Thresholds</span>
+ <p class="text-xs text-muted-foreground mb-2">
+ The value takes the color of the highest threshold it crosses
+ </p>
+ <div class="space-y-2">
+ {#each thresholds as threshold, i}
+ <div class="flex items-center gap-2">
+ <Input
+ type="number"
+ bind:value={thresholds[i].value}
+ class="h-8 w-28 text-xs"
+ />
+ <div class="flex items-center gap-1.5">
+ {#each THRESHOLD_COLOR_NAMES as colorName}
+ <button
+ type="button"
+ class="h-5 w-5 cursor-pointer rounded-full transition-transform {threshold.color === colorName ? 'ring-2 ring-ring ring-offset-2 ring-offset-background' : 'opacity-50 hover:opacity-100'}"
+ style="background-color: {resolveThresholdColor(colorName)};"
+ aria-label={colorName}
+ title={colorName}
+ onclick={() => (thresholds[i].color = colorName)}
+ ></button>
+ {/each}
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ class="h-8 w-8"
+ aria-label="Remove threshold"
+ onclick={() => removeThreshold(i)}
+ >
+ <X class="h-4 w-4" />
+ </Button>
+ </div>
+ {/each}
+ <div class="flex items-center gap-2">
+ <span class="w-28 px-3 text-xs text-muted-foreground">Base</span>
+ <div class="flex items-center gap-1.5">
+ {#each THRESHOLD_COLOR_NAMES as colorName}
+ <button
+ type="button"
+ class="h-5 w-5 cursor-pointer rounded-full transition-transform {baseColor === colorName ? 'ring-2 ring-ring ring-offset-2 ring-offset-background' : 'opacity-50 hover:opacity-100'}"
+ style="background-color: {resolveThresholdColor(colorName)};"
+ aria-label={colorName}
+ title={colorName}
+ onclick={() => (baseColor = colorName)}
+ ></button>
+ {/each}
+ </div>
+ </div>
+ </div>
+ <Button variant="outline" size="sm" class="mt-2" onclick={addThreshold}>
+ <Plus class="mr-1 h-3.5 w-3.5" /> Add Threshold
+ </Button>
+ </div>
+ {/if}
+
<div>
<label class="text-sm font-medium" for="widget-unit">Unit (optional)</label>
<Input
@@ -237,6 +383,7 @@
>
<Select.Trigger class="w-20">{source.aggregation}</Select.Trigger>
<Select.Content>
+ <Select.Item value="last">last</Select.Item>
<Select.Item value="avg">avg</Select.Item>
<Select.Item value="min">min</Select.Item>
<Select.Item value="max">max</Select.Item>
@@ -289,11 +436,11 @@
</div>
{/each}
</div>
- <AlertDialog.Footer>
+ <Sheet.Footer class="flex-row justify-end border-t px-6">
<Button variant="outline" onclick={handleClose}>Cancel</Button>
<Button variant={widget?.id ? 'default' : 'success'} onclick={handleSave}>
{#if widget?.id}<Check class="mr-1 h-4 w-4" /> Update Widget{:else}<Plus class="mr-1 h-4 w-4" /> New Widget{/if}
</Button>
- </AlertDialog.Footer>
- </AlertDialog.Content>
-</AlertDialog.Root>
+ </Sheet.Footer>
+ </Sheet.Content>
+</Sheet.Root>
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index 5f28f726..c6ed9186 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -2,8 +2,10 @@
import D3LineChart from './d3-line-chart.svelte';
import D3HorizontalBarChart from './d3-horizontal-bar-chart.svelte';
import D3StackedAreaChart from './d3-stacked-area-chart.svelte';
+ import D3Gauge from './d3-gauge.svelte';
import WidgetTable from './widget-table.svelte';
import Sparkline from './sparkline.svelte';
+ import { activeThresholdColor, type ThresholdStep } from './gauge-thresholds';
import { SvelteSet } from 'svelte/reactivity';
import { api } from '$lib/api';
import { projectsState } from '$lib/state/projects.svelte';
@@ -28,6 +30,10 @@
colSpan?: 1 | 2 | 3;
size?: 'sm' | 'md' | 'lg';
showSparkline?: boolean;
+ min?: number;
+ max?: number;
+ baseColor?: string;
+ thresholds?: ThresholdStep[];
};
let {
@@ -71,6 +77,24 @@
chartAreaHeight > 0 ? chartAreaHeight : (chartHeights[widget.config.size ?? 'sm'] ?? 200)
);
+ function reduceSeries(points: MetricTrendPoint[], aggregation: string): number | null {
+ if (points.length === 0) return null;
+ const values = points.map((p) => p.value);
+ switch (aggregation) {
+ case 'max':
+ return Math.max(...values);
+ case 'min':
+ return Math.min(...values);
+ case 'sum':
+ case 'count':
+ return values.reduce((a, b) => a + b, 0);
+ case 'avg':
+ return values.reduce((a, b) => a + b, 0) / values.length;
+ default:
+ return values[values.length - 1];
+ }
+ }
+
let hiddenSeries = new SvelteSet<string>();
const visibleSeries = $derived(series.filter((s) => !hiddenSeries.has(s.key)));
@@ -82,6 +106,14 @@
}
}
+ const singleValueColor = $derived(
+ widget.widgetType === 'single_value' &&
+ singleValue !== null &&
+ (widget.config.thresholds?.length || widget.config.baseColor)
+ ? activeThresholdColor(singleValue, widget.config.baseColor, widget.config.thresholds)
+ : null
+ );
+
const legendVisible = $derived(
['line_chart', 'area_chart', 'stacked_area'].includes(widget.widgetType) &&
series.length > 0 &&
@@ -141,11 +173,9 @@
resolvedUnit = units.size === 1 ? [...units][0] : '';
series = newSeries;
- if (widget.widgetType === 'single_value') {
- singleValue =
- newSeries.length > 0 && newSeries[0].data.length > 0
- ? newSeries[0].data[newSeries[0].data.length - 1].value
- : null;
+ if (widget.widgetType === 'single_value' || widget.widgetType === 'gauge') {
+ const aggregation = widget.config.sources?.[0]?.aggregation || 'avg';
+ singleValue = newSeries.length > 0 ? reduceSeries(newSeries[0].data, aggregation) : null;
}
} catch {
// keep empty
@@ -211,15 +241,30 @@
</div>
{:else if widget.widgetType === 'single_value'}
<div class="flex h-full flex-col items-center justify-center gap-2">
- <span class="text-3xl font-bold">
+ <span class="text-3xl font-bold" style={singleValueColor ? `color: ${singleValueColor};` : ''}>
{singleValue !== null ? formatMetricLabel(singleValue, effectiveUnit) : '-'}
</span>
{#if widget.config.showSparkline && series[0]?.data && series[0].data.length > 1}
<div class="w-full px-6">
- <Sparkline data={series[0].data} color={series[0].color} />
+ <Sparkline data={series[0].data} color={singleValueColor ?? series[0].color} />
</div>
{/if}
</div>
+ {:else if widget.widgetType === 'gauge'}
+ {#if singleValue !== null}
+ <D3Gauge
+ value={singleValue}
+ min={widget.config.min ?? 0}
+ max={widget.config.max ?? 100}
+ baseColor={widget.config.baseColor}
+ thresholds={widget.config.thresholds}
+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
+ />
+ {:else}
+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">
+ No data
+ </div>
+ {/if}
{:else if widget.widgetType === 'bar_chart'}
{#if barData.length > 0}
<D3HorizontalBarChart data={barData} height={chartHeight} unit={effectiveUnit} formatValue={(v) => formatMetricLabel(v, effectiveUnit)} />
diff --git a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-content.svelte b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-content.svelte
index 4ab2be0f..a82c1ec5 100644
--- a/frontend/src/lib/components/ui/alert-dialog/alert-dialog-content.svelte
+++ b/frontend/src/lib/components/ui/alert-dialog/alert-dialog-content.svelte
@@ -24,7 +24,7 @@
bind:ref
data-slot="alert-dialog-content"
class={cn(
- 'fixed top-1/2 left-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:rounded-md',
+ 'fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto border bg-background p-6 shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:rounded-md',
className
)}
{...restProps}