The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
segments added, server name added
ddux26e173dbee4a
diff --git a/Dockerfile b/Dockerfileindex 87f42b38..de7cc231 100644--- a/Dockerfile+++ b/Dockerfile@@ -18,6 +18,10 @@ RUN npm ci# Copy source and buildCOPY frontend/ ./++# Set the API URL for the frontend build (baked in at build time)+ENV VITE_API_URL=https://tracewayapp.com+RUN npm run build# ==============================================================================diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.goindex 766e7c6b..040346f0 100644--- a/backend/app/controllers/clientcontrollers/client.controller.go+++ b/backend/app/controllers/clientcontrollers/client.controller.go@@ -36,11 +36,19 @@ func (e clientController) Report(c *gin.Context) {transactionsToInsert := []models.Transaction{}exceptionStackTraceToInsert := []models.ExceptionStackTrace{}metricRecordsToInsert := []models.MetricRecord{}+ segmentsToInsert := []models.Segment{}for _, cf := range request.CollectionFrames {for _, ct := range cf.Transactions {t := ct.ToTransaction(request.AppVersion, request.ServerName)t.ProjectId = projectIdtransactionsToInsert = append(transactionsToInsert, t)++ // Extract segments from transaction+ for _, cs := range ct.Segments {+ seg := cs.ToSegment(ct.Id)+ seg.ProjectId = projectId+ segmentsToInsert = append(segmentsToInsert, seg)+ }}for _, cst := range cf.StackTraces {@@ -50,7 +58,7 @@ func (e clientController) Report(c *gin.Context) {}for _, cm := range cf.Metrics {- mr := cm.ToMetricRecord()+ mr := cm.ToMetricRecord(request.ServerName)mr.ProjectId = projectIdmetricRecordsToInsert = append(metricRecordsToInsert, mr)}@@ -74,6 +82,12 @@ func (e clientController) Report(c *gin.Context) {panic(err)}+ err = repositories.SegmentRepository.InsertAsync(c, segmentsToInsert)++ if err != nil {+ panic(err)+ }+c.JSON(http.StatusOK, gin.H{})}diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.goindex f484370a..362fb59d 100644--- a/backend/app/controllers/dashboard.controller.go+++ b/backend/app/controllers/dashboard.controller.go@@ -4,6 +4,8 @@ import ("backend/app/models""backend/app/repositories""net/http"+ "sort"+ "strings""time""github.com/gin-gonic/gin"@@ -42,6 +44,13 @@ func (d dashboardController) GetDashboardOverview(c *gin.Context) {func (d dashboardController) GetDashboard(c *gin.Context) {projectId := c.Query("projectId")+ serversParam := c.Query("servers")++ // Parse selected servers+ var selectedServers []string+ if serversParam != "" {+ selectedServers = strings.Split(serversParam, ",")+ }now := time.Now()var start, end time.Time@@ -76,6 +85,12 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// Calculate aggregation interval based on time rangeintervalMinutes := calculateIntervalMinutes(duration)+ // Get available servers in the time range+ availableServers, err := repositories.MetricRecordRepository.GetDistinctServers(c, projectId, start, end)+ if err != nil {+ availableServers = []string{}+ }+metrics := make([]models.DashboardMetric, 0, 11)// 1. Requests count@@ -117,76 +132,72 @@ func (d dashboardController) GetDashboard(c *gin.Context) {metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))// 5. CPU Usage- cpuTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes)+ cpuPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- cpuCurrent := getLastValue(cpuTrend)cpuPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, prevStart, prevEnd)- metrics = append(metrics, buildMetric("cpu_usage", "CPU Usage", cpuCurrent, "%", cpuTrend, cpuPrev, "cpu"))+ metrics = append(metrics, buildMetricWithServers("cpu_usage", "CPU Usage", "%", cpuPerServer, cpuPrev, "cpu"))// 6. Memory Usage (MB)- memTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes)+ memPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- memCurrent := getLastValue(memTrend)memPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, prevStart, prevEnd)- metrics = append(metrics, buildMetric("memory_usage", "Memory Usage", memCurrent, "MB", memTrend, memPrev, "memory"))+ metrics = append(metrics, buildMetricWithServers("memory_usage", "Memory Usage", "MB", memPerServer, memPrev, "memory"))// 7. Total System Memory (MB)- memTotalTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes)+ memTotalPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- memTotalCurrent := getLastValue(memTotalTrend)memTotalPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryTotal, prevStart, prevEnd)- metrics = append(metrics, buildMetric("memory_total", "Total Memory", memTotalCurrent, "MB", memTotalTrend, memTotalPrev, "memory_total"))+ metrics = append(metrics, buildMetricWithServers("memory_total", "Total Memory", "MB", memTotalPerServer, memTotalPrev, "memory_total"))// 8. Go Routines- goRoutinesTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes)+ goRoutinesPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- goRoutinesCurrent := getLastValue(goRoutinesTrend)goRoutinesPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameGoRoutines, prevStart, prevEnd)- metrics = append(metrics, buildMetric("go_routines", "Go Routines", goRoutinesCurrent, "", goRoutinesTrend, goRoutinesPrev, "go_routines"))+ metrics = append(metrics, buildMetricWithServers("go_routines", "Go Routines", "", goRoutinesPerServer, goRoutinesPrev, "go_routines"))// 9. Heap Objects- heapObjectsTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes)+ heapObjectsPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- heapObjectsCurrent := getLastValue(heapObjectsTrend)heapObjectsPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameHeapObjects, prevStart, prevEnd)- metrics = append(metrics, buildMetric("heap_objects", "Heap Objects", heapObjectsCurrent, "", heapObjectsTrend, heapObjectsPrev, "heap_objects"))+ metrics = append(metrics, buildMetricWithServers("heap_objects", "Heap Objects", "", heapObjectsPerServer, heapObjectsPrev, "heap_objects"))// 10. Num GC- numGCTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes)+ numGCPerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- numGCCurrent := getLastValue(numGCTrend)numGCPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameNumGC, prevStart, prevEnd)- metrics = append(metrics, buildMetric("num_gc", "GC Cycles", numGCCurrent, "", numGCTrend, numGCPrev, "num_gc"))+ metrics = append(metrics, buildMetricWithServers("num_gc", "GC Cycles", "", numGCPerServer, numGCPrev, "num_gc"))// 11. GC Pause Total (convert from nanoseconds to milliseconds)- gcPauseTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes)+ gcPausePerServer, err := repositories.MetricRecordRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes, selectedServers)if err != nil {panic(err)}- // Convert nanoseconds to milliseconds for display- for i := range gcPauseTrend {- gcPauseTrend[i].Value = gcPauseTrend[i].Value / 1_000_000+ // Convert nanoseconds to milliseconds for each server's data+ for serverName, points := range gcPausePerServer {+ for i := range points {+ gcPausePerServer[serverName][i].Value = points[i].Value / 1_000_000+ }}- gcPauseCurrent := getLastValue(gcPauseTrend)gcPausePrevRaw, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameGCPauseTotal, prevStart, prevEnd)gcPausePrev := gcPausePrevRaw / 1_000_000- metrics = append(metrics, buildMetric("gc_pause", "GC Pause", gcPauseCurrent, "ms", gcPauseTrend, gcPausePrev, "gc_pause"))+ metrics = append(metrics, buildMetricWithServers("gc_pause", "GC Pause", "ms", gcPausePerServer, gcPausePrev, "gc_pause"))c.JSON(http.StatusOK, models.DashboardResponse{- Metrics: metrics,- LastUpdated: now,+ Metrics: metrics,+ AvailableServers: availableServers,+ LastUpdated: now,})}@@ -220,6 +231,92 @@ func buildMetric(id, name string, current float64, unit string, trend []models.T}}+func buildMetricWithServers(id, name, unit string, serverData map[string][]models.TimeSeriesPoint, prev float64, metricType string) models.DashboardMetric {+ servers := make([]models.ServerMetricTrend, 0, len(serverData))+ var aggregateValue float64+ var aggregateTrend []models.DashboardTrendPoint++ // Build server-level data+ serverNames := make([]string, 0, len(serverData))+ for serverName := range serverData {+ serverNames = append(serverNames, serverName)+ }+ sort.Strings(serverNames)++ // Merge all timestamps for aggregate trend+ timestampValues := make(map[time.Time][]float64)++ for _, serverName := range serverNames {+ trend := serverData[serverName]+ trendPoints := make([]models.DashboardTrendPoint, len(trend))+ var lastValue float64++ for i, p := range trend {+ trendPoints[i] = models.DashboardTrendPoint{+ Timestamp: p.Timestamp,+ Value: p.Value,+ }+ lastValue = p.Value+ timestampValues[p.Timestamp] = append(timestampValues[p.Timestamp], p.Value)+ }++ servers = append(servers, models.ServerMetricTrend{+ ServerName: serverName,+ Value: lastValue,+ Trend: trendPoints,+ })+ }++ // Calculate aggregate value (average of last values across servers)+ if len(servers) > 0 {+ for _, s := range servers {+ aggregateValue += s.Value+ }+ aggregateValue /= float64(len(servers))+ }++ // Build aggregate trend (average at each timestamp)+ timestamps := make([]time.Time, 0, len(timestampValues))+ for ts := range timestampValues {+ timestamps = append(timestamps, ts)+ }+ sort.Slice(timestamps, func(i, j int) bool {+ return timestamps[i].Before(timestamps[j])+ })++ for _, ts := range timestamps {+ values := timestampValues[ts]+ var sum float64+ for _, v := range values {+ sum += v+ }+ aggregateTrend = append(aggregateTrend, models.DashboardTrendPoint{+ Timestamp: ts,+ Value: sum / float64(len(values)),+ })+ }++ // Calculate percentage change+ var change24h float64+ if prev > 0 {+ change24h = ((aggregateValue - prev) / prev) * 100+ }++ // Determine status based on metric type+ status := calculateStatus(aggregateValue, metricType)++ return models.DashboardMetric{+ ID: id,+ Name: name,+ Value: aggregateValue,+ Unit: unit,+ Trend: aggregateTrend,+ Servers: servers,+ Change24h: change24h,+ Status: status,+ }+}+func calculateStatus(value float64, metricType string) string {switch metricType {case "requests":diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 60c97fca..a651074f 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -39,6 +39,7 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/transactions", middleware.UseAppAuth, TransactionController.FindAllTransactions)router.POST("/transactions/grouped", middleware.UseAppAuth, TransactionController.FindGroupedByEndpoint)router.POST("/transactions/endpoint", middleware.UseAppAuth, TransactionController.FindByEndpoint)+ router.POST("/transactions/:transactionId", middleware.UseAppAuth, TransactionDetailController.GetTransactionDetail)router.POST("/exception-stack-traces", middleware.UseAppAuth, ExceptionStackTraceController.FindGrouppedExceptionStackTraces)router.POST("/exception-stack-traces/archive", middleware.UseAppAuth, ExceptionStackTraceController.ArchiveExceptions)router.POST("/exception-stack-traces/unarchive", middleware.UseAppAuth, ExceptionStackTraceController.UnarchiveExceptions)diff --git a/backend/app/controllers/transaction_detail.controller.go b/backend/app/controllers/transaction_detail.controller.gonew file mode 100644index 00000000..b7ac3fc6--- /dev/null+++ b/backend/app/controllers/transaction_detail.controller.go@@ -0,0 +1,56 @@+package controllers++import (+ "backend/app/models"+ "backend/app/repositories"+ "net/http"++ "github.com/gin-gonic/gin"+)++type transactionDetailController struct{}++type TransactionDetailRequest struct {+ ProjectId string `json:"projectId"`+}++type TransactionDetailResponse struct {+ Transaction *models.Transaction `json:"transaction"`+ Segments []models.Segment `json:"segments"`+ HasSegments bool `json:"hasSegments"`+}++func (c transactionDetailController) GetTransactionDetail(ctx *gin.Context) {+ transactionId := ctx.Param("transactionId")+ if transactionId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "transactionId is required"})+ return+ }++ var request TransactionDetailRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Get transaction+ transaction, err := repositories.TransactionRepository.FindById(ctx, request.ProjectId, transactionId)+ if err != nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Transaction not found"})+ return+ }++ // Get segments (flat list ordered by start_time)+ segments, err := repositories.SegmentRepository.FindByTransactionId(ctx, request.ProjectId, transactionId)+ if err != nil {+ panic(err)+ }++ ctx.JSON(http.StatusOK, TransactionDetailResponse{+ Transaction: transaction,+ Segments: segments,+ HasSegments: len(segments) > 0,+ })+}++var TransactionDetailController = transactionDetailController{}diff --git a/backend/app/migrations/ch/0018_add_server_name_to_metric_records.up.sql b/backend/app/migrations/ch/0018_add_server_name_to_metric_records.up.sqlnew file mode 100644index 00000000..f590982e--- /dev/null+++ b/backend/app/migrations/ch/0018_add_server_name_to_metric_records.up.sql@@ -0,0 +1 @@+ALTER TABLE metric_records ADD COLUMN server_name String DEFAULT ''diff --git a/backend/app/migrations/ch/0019_create_segments.up.sql b/backend/app/migrations/ch/0019_create_segments.up.sqlnew file mode 100644index 00000000..f35f9f7d--- /dev/null+++ b/backend/app/migrations/ch/0019_create_segments.up.sql@@ -0,0 +1,11 @@+CREATE TABLE IF NOT EXISTS segments (+ id String,+ transaction_id String,+ project_id String,+ name String,+ start_time DateTime64(6),+ duration Int64,+ recorded_at DateTime+) ENGINE = MergeTree()+PARTITION BY toYYYYMM(recorded_at)+ORDER BY (project_id, transaction_id, start_time)diff --git a/backend/app/models/clientmodels/clientmodels.model.go b/backend/app/models/clientmodels/clientmodels.model.goindex 098aff7d..ed79f6ad 100644--- a/backend/app/models/clientmodels/clientmodels.model.go+++ b/backend/app/models/clientmodels/clientmodels.model.go@@ -32,11 +32,12 @@ type ClientMetricRecord struct {RecordedAt time.Time `json:"recordedAt"`}-func (c *ClientMetricRecord) ToMetricRecord() models.MetricRecord {+func (c *ClientMetricRecord) ToMetricRecord(serverName string) models.MetricRecord {return models.MetricRecord{Name: c.Name,Value: c.Value,RecordedAt: c.RecordedAt,+ ServerName: serverName,}}@@ -49,6 +50,7 @@ type ClientTransaction struct {BodySize int `json:"bodySize"`ClientIP string `json:"clientIP"`Scope map[string]string `json:"scope"`+ Segments []*ClientSegment `json:"segments"`}func (c *ClientTransaction) ToTransaction(appVersion, serverName string) models.Transaction {@@ -66,6 +68,24 @@ func (c *ClientTransaction) ToTransaction(appVersion, serverName string) models.}}+type ClientSegment struct {+ Id string `json:"id"`+ Name string `json:"name"`+ StartTime time.Time `json:"startTime"`+ Duration time.Duration `json:"duration"`+}++func (c *ClientSegment) ToSegment(transactionId string) models.Segment {+ return models.Segment{+ Id: c.Id,+ TransactionId: transactionId,+ Name: c.Name,+ StartTime: c.StartTime,+ Duration: c.Duration,+ RecordedAt: time.Now(),+ }+}+type CollectionFrame struct {StackTraces []*ClientExceptionStackTrace `json:"stackTraces"`Metrics []*ClientMetricRecord `json:"metrics"`diff --git a/backend/app/models/dashboard.model.go b/backend/app/models/dashboard.model.goindex 472f815a..36b7ca94 100644--- a/backend/app/models/dashboard.model.go+++ b/backend/app/models/dashboard.model.go@@ -7,19 +7,28 @@ type DashboardTrendPoint struct {Value float64 `json:"value"`}+// ServerMetricTrend represents trend data for a single server+type ServerMetricTrend struct {+ ServerName string `json:"serverName"`+ Value float64 `json:"value"`+ Trend []DashboardTrendPoint `json:"trend"`+}+type DashboardMetric struct {ID string `json:"id"`Name string `json:"name"`Value float64 `json:"value"`Unit string `json:"unit"`Trend []DashboardTrendPoint `json:"trend"`+ Servers []ServerMetricTrend `json:"servers,omitempty"`Change24h float64 `json:"change24h"`Status string `json:"status"`}type DashboardResponse struct {- Metrics []DashboardMetric `json:"metrics"`- LastUpdated time.Time `json:"lastUpdated"`+ Metrics []DashboardMetric `json:"metrics"`+ AvailableServers []string `json:"availableServers"`+ LastUpdated time.Time `json:"lastUpdated"`}// TimeSeriesPoint is used internally for querying time-bucketed datadiff --git a/backend/app/models/metric_record.model.go b/backend/app/models/metric_record.model.goindex b65c08a9..22109f24 100644--- a/backend/app/models/metric_record.model.go+++ b/backend/app/models/metric_record.model.go@@ -7,6 +7,7 @@ type MetricRecord struct {Name string `json:"name" ch:"name"`Value float64 `json:"value" ch:"value"`RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ ServerName string `json:"serverName" ch:"server_name"`}const (diff --git a/backend/app/models/segment.model.go b/backend/app/models/segment.model.gonew file mode 100644index 00000000..006c3299--- /dev/null+++ b/backend/app/models/segment.model.go@@ -0,0 +1,13 @@+package models++import "time"++type Segment struct {+ Id string `json:"id" ch:"id"`+ TransactionId string `json:"transactionId" ch:"transaction_id"`+ ProjectId string `json:"projectId" ch:"project_id"`+ Name string `json:"name" ch:"name"`+ StartTime time.Time `json:"startTime" ch:"start_time"`+ Duration time.Duration `json:"duration" ch:"duration"`+ RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+}diff --git a/backend/app/repositories/metric_record.repository.go b/backend/app/repositories/metric_record.repository.goindex 8a188bb4..a8b8ae48 100644--- a/backend/app/repositories/metric_record.repository.go+++ b/backend/app/repositories/metric_record.repository.go@@ -10,12 +10,12 @@ import (type metricRecordRepository struct{}func (e *metricRecordRepository) InsertAsync(ctx context.Context, lines []models.MetricRecord) error {- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO metric_records (project_id, name, value, recorded_at)")+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO metric_records (project_id, name, value, recorded_at, server_name)")if err != nil {return err}for _, m := range lines {- if err := batch.Append(m.ProjectId, m.Name, m.Value, m.RecordedAt); err != nil {+ if err := batch.Append(m.ProjectId, m.Name, m.Value, m.RecordedAt, m.ServerName); err != nil {return err}}@@ -84,4 +84,70 @@ func (e *metricRecordRepository) GetAverageByInterval(ctx context.Context, projereturn points, nil}+// GetDistinctServers returns all unique server names with data in the time range+func (e *metricRecordRepository) GetDistinctServers(ctx context.Context, projectId string, start, end time.Time) ([]string, error) {+ query := `SELECT DISTINCT server_name FROM metric_records+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ AND server_name != ''+ ORDER BY server_name ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var servers []string+ for rows.Next() {+ var s string+ if err := rows.Scan(&s); err != nil {+ return nil, err+ }+ servers = append(servers, s)+ }+ return servers, nil+}++// GetAverageByIntervalPerServer returns metric averages grouped by interval and server+func (e *metricRecordRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId string, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,+ server_name,+ avg(value) as avg_value+ FROM metric_records+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?`++ args := []interface{}{intervalMinutes, projectId, name, start, end}++ if len(servers) > 0 {+ query += " AND server_name IN (?)"+ args = append(args, servers)+ } else {+ query += " AND server_name != ''"+ }++ query += " GROUP BY bucket, server_name ORDER BY bucket ASC, server_name ASC"++ rows, err := (*chdb.Conn).Query(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.TimeSeriesPoint)+ for rows.Next() {+ var bucket time.Time+ var serverName string+ var value float64+ if err := rows.Scan(&bucket, &serverName, &value); err != nil {+ return nil, err+ }+ result[serverName] = append(result[serverName], models.TimeSeriesPoint{+ Timestamp: bucket,+ Value: value,+ })+ }+ return result, nil+}+var MetricRecordRepository = metricRecordRepository{}diff --git a/backend/app/repositories/segment.repository.go b/backend/app/repositories/segment.repository.gonew file mode 100644index 00000000..e1928bff--- /dev/null+++ b/backend/app/repositories/segment.repository.go@@ -0,0 +1,67 @@+package repositories++import (+ "backend/app/chdb"+ "backend/app/models"+ "context"+)++type segmentRepository struct{}++func (r *segmentRepository) InsertAsync(ctx context.Context, segments []models.Segment) error {+ if len(segments) == 0 {+ return nil+ }++ batch, err := (*chdb.Conn).PrepareBatch(ctx,+ "INSERT INTO segments (id, transaction_id, project_id, name, start_time, duration, recorded_at)")+ if err != nil {+ return err+ }++ for _, s := range segments {+ if err := batch.Append(+ s.Id,+ s.TransactionId,+ s.ProjectId,+ s.Name,+ s.StartTime,+ s.Duration,+ s.RecordedAt,+ ); err != nil {+ return err+ }+ }++ return batch.Send()+}++func (r *segmentRepository) FindByTransactionId(ctx context.Context, projectId, transactionId string) ([]models.Segment, error) {+ query := `SELECT+ id, transaction_id, project_id, name, start_time, duration, recorded_at+ FROM segments+ WHERE project_id = ? AND transaction_id = ?+ ORDER BY start_time ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, transactionId)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var segments []models.Segment+ for rows.Next() {+ var s models.Segment+ if err := rows.Scan(+ &s.Id, &s.TransactionId, &s.ProjectId,+ &s.Name, &s.StartTime, &s.Duration, &s.RecordedAt,+ ); err != nil {+ return nil, err+ }+ segments = append(segments, s)+ }++ return segments, nil+}++var SegmentRepository = segmentRepository{}diff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/transaction.repository.goindex 9a20cea2..2078163a 100644--- a/backend/app/repositories/transaction.repository.go+++ b/backend/app/repositories/transaction.repository.go@@ -199,6 +199,34 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId streturn transactions, int64(count), nil}+// FindById returns a single transaction by ID+func (e *transactionRepository) FindById(ctx context.Context, projectId, transactionId string) (*models.Transaction, error) {+ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope, app_version, server_name+ FROM transactions+ WHERE project_id = ? AND id = ?+ LIMIT 1`++ var t models.Transaction+ var scopeJSON string++ err := (*chdb.Conn).QueryRow(ctx, query, projectId, transactionId).Scan(+ &t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt,+ &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName)++ if err != nil {+ return nil, err+ }++ // Parse scope JSON+ if scopeJSON != "" && scopeJSON != "{}" {+ if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {+ t.Scope = nil+ }+ }++ return &t, nil+}+// CountByHour returns transaction counts grouped by hourfunc (e *transactionRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTdiff --git a/backend/backend b/backend/backendindex 80b2a17f..718d5891 100755Binary files a/backend/backend and b/backend/backend differdiff --git a/clients/go-client/devtesting/devtesting.go b/clients/go-client/devtesting/devtesting.goindex 816977f2..e9dc5fcf 100644--- a/clients/go-client/devtesting/devtesting.go+++ b/clients/go-client/devtesting/devtesting.go@@ -56,6 +56,33 @@ func testGin() {})})+ // Example: Capturing segments within a transaction+ router.GET("/test-segments", func(ctx *gin.Context) {+ dbAndCacheSeg := traceway.StartSegment(ctx, "db.and.cache")++ // Start a segment for database operation+ seg := traceway.StartSegment(ctx, "db.query")+ time.Sleep(time.Duration(50+rand.IntN(100)) * time.Millisecond)+ seg.End()++ // Start a segment for cache operation+ seg = traceway.StartSegment(ctx, "cache.set")+ time.Sleep(time.Duration(10+rand.IntN(30)) * time.Millisecond)+ seg.End()++ // Start a segment for an HTTP call+ seg = traceway.StartSegment(ctx, "http.external_api")+ time.Sleep(time.Duration(100+rand.IntN(200)) * time.Millisecond)+ seg.End()++ dbAndCacheSeg.End()++ ctx.JSON(200, gin.H{+ "status": "ok",+ "message": "Segments captured",+ })+ })+router.GET("/metrics", func(ctx *gin.Context) {traceway.PrintCollectionFrameMetrics()})diff --git a/clients/go-client/traceway.go b/clients/go-client/traceway.goindex 39a03eac..c2e8f6dd 100644--- a/clients/go-client/traceway.go+++ b/clients/go-client/traceway.go@@ -19,13 +19,14 @@ import ("traceway/metrics/mem""github.com/gin-gonic/gin"+ "github.com/google/uuid")// Context key for scopetype tracewayContextKey stringconst CtxScopeKey tracewayContextKey = "TRACEWAY_SCOPE"-const CtxTransactionIdKey tracewayContextKey = "TRACEWAY_TRANSACTION_ID"+const CtxTransactionKey tracewayContextKey = "TRACEWAY_TRANSACTION"// Scope holds contextual data for exceptions and transactionstype Scope struct {@@ -79,6 +80,27 @@ func (s *Scope) Clear() {// Global default scopevar defaultScope = NewScope()+// TransactionContext holds transaction data including segments+type TransactionContext struct {+ Id string+ Segments []Segment+ mu sync.Mutex+}++// AddSegment adds a segment to the transaction context+func (t *TransactionContext) AddSegment(seg Segment) {+ t.mu.Lock()+ defer t.mu.Unlock()+ t.Segments = append(t.Segments, seg)+}++// GetSegments returns a copy of segments+func (t *TransactionContext) GetSegments() []Segment {+ t.mu.Lock()+ defer t.mu.Unlock()+ return t.Segments+}+// ConfigureScope modifies the global default scope (persistent changes)func ConfigureScope(fn func(*Scope)) {fn(defaultScope)@@ -113,13 +135,21 @@ func GetScopeFromGin(c *gin.Context) *Scope {return GetScopeFromContext(c.Request.Context())}-func GetTransactionIdFromContext(ctx context.Context) *string {- if val, ok := ctx.Value(string(CtxTransactionIdKey)).(*string); ok {+// GetTransactionFromContext retrieves the transaction context+func GetTransactionFromContext(ctx context.Context) *TransactionContext {+ if val, ok := ctx.Value(string(CtxTransactionKey)).(*TransactionContext); ok {return val}return nil}+func GetTransactionIdFromContext(ctx context.Context) *string {+ if txn := GetTransactionFromContext(ctx); txn != nil {+ return &txn.Id+ }+ return nil+}+// GetHostname returns the hostname, cached for efficiencyvar cachedHostname stringvar hostnameOnce sync.Once@@ -234,6 +264,41 @@ type Transaction struct {BodySize int `json:"bodySize"`ClientIP string `json:"clientIP"`Scope map[string]string `json:"scope,omitempty"`+ Segments []Segment `json:"segments,omitempty"`+}++// Segment represents a timed slice within a transaction+type Segment struct {+ Id string `json:"id"`+ Name string `json:"name"`+ StartTime time.Time `json:"startTime"`+ Duration time.Duration `json:"duration"`+}++// ActiveSegment is a running segment that can be ended+type ActiveSegment struct {+ segment Segment+ txn *TransactionContext+ startedAt time.Time+ ended bool+ mu sync.Mutex+}++// End completes the segment and records its duration+func (s *ActiveSegment) End() {+ if s == nil || s.txn == nil {+ return+ }+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.ended {+ return // Already ended+ }++ s.ended = true+ s.segment.Duration = time.Since(s.startedAt)+ s.txn.AddSegment(s.segment)}type CollectionFrame struct {@@ -617,19 +682,19 @@ func CaptureMetric(name string, value float64) {// CaptureTransaction captures a transaction without scope (backward compatible)func CaptureTransaction(- transactionId string,+ txn *TransactionContext,endpoint string,d time.Duration,startedAt time.Time,statusCode, bodySize int,clientIP string,) {- CaptureTransactionWithScope(transactionId, endpoint, d, startedAt, statusCode, bodySize, clientIP, nil)+ CaptureTransactionWithScope(txn, endpoint, d, startedAt, statusCode, bodySize, clientIP, nil)}// CaptureTransactionWithScope captures a transaction with scopefunc CaptureTransactionWithScope(- transactionId string,+ txn *TransactionContext,endpoint string,d time.Duration,startedAt time.Time,@@ -637,10 +702,13 @@ func CaptureTransactionWithScope(clientIP string,scope map[string]string,) {+ if txn == nil {+ return+ }collectionFrameStore.messageQueue <- CollectionFrameMessage{msgType: CollectionFrameMessageTypeTransaction,transaction: &Transaction{- Id: transactionId,+ Id: txn.Id,Endpoint: endpoint,Duration: d,RecordedAt: startedAt,@@ -648,7 +716,26 @@ func CaptureTransactionWithScope(BodySize: bodySize,ClientIP: clientIP,Scope: scope,+ Segments: txn.GetSegments(),+ },+ }+}++// StartSegment starts a segment using transaction ID from context+func StartSegment(ctx context.Context, name string) *ActiveSegment {+ txn := GetTransactionFromContext(ctx)+ if txn == nil {+ return nil+ }+ now := time.Now()+ return &ActiveSegment{+ segment: Segment{+ Id: uuid.NewString(),+ Name: name,+ StartTime: now,},+ txn: txn,+ startedAt: now,}}diff --git a/clients/go-client/traceway_gin/traceway_gin.go b/clients/go-client/traceway_gin/traceway_gin.goindex 072555d9..ee6b865e 100644--- a/clients/go-client/traceway_gin/traceway_gin.go+++ b/clients/go-client/traceway_gin/traceway_gin.go@@ -60,20 +60,21 @@ func New(connectionString string, options ...func(*traceway.TracewayOptions)) gimethod := c.Request.MethodclientIP := c.ClientIP()- transactionId := uuid.NewString()++ // Create transaction context+ txn := &traceway.TransactionContext{+ Id: uuid.NewString(),+ }// Create request-scoped scope with defaultsscope := traceway.NewScope()- // We won't store tags by default for now- // scope.SetTag("server_name", cachedHostname)- // scope.SetTag("environment", cachedEnvironment)-- // Store scope in both gin.Context and request context+ // Store scope and transaction in both gin.Context and request contextctx := context.WithValue(c.Request.Context(), string(traceway.CtxScopeKey), scope)+ ctx = context.WithValue(ctx, string(traceway.CtxTransactionKey), txn)c.Request = c.Request.WithContext(ctx)c.Set(string(traceway.CtxScopeKey), scope)- c.Set(string(traceway.CtxTransactionIdKey), &transactionId)+ c.Set(string(traceway.CtxTransactionKey), txn)stackTraceFormatted := wrapAndExecute(c)@@ -98,12 +99,12 @@ func New(connectionString string, options ...func(*traceway.TracewayOptions)) gidefer recover()// Capture transaction with scope- traceway.CaptureTransactionWithScope(transactionId, transactionEndpoint, duration, start, statusCode, bodySize, clientIP, scope.GetTags())+ traceway.CaptureTransactionWithScope(txn, transactionEndpoint, duration, start, statusCode, bodySize, clientIP, scope.GetTags())if stackTraceFormatted != nil {exceptionTags := scope.GetTags()exceptionTags["user_agent"] = c.Request.UserAgent() // we'll only store the user agent IF an exception happens- traceway.CaptureTransactionExceptionWithScope(transactionId, *stackTraceFormatted, exceptionTags)+ traceway.CaptureTransactionExceptionWithScope(txn.Id, *stackTraceFormatted, exceptionTags)}}}diff --git a/frontend/.env.example b/frontend/.env.examplenew file mode 100644index 00000000..bf2e66a6--- /dev/null+++ b/frontend/.env.example@@ -0,0 +1,2 @@+# Backend API URL (used for the connection string display and vite proxy in dev)+VITE_API_URL=http://localhost:8082diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.tsindex da08e6da..0deed93c 100644--- a/frontend/src/app.d.ts+++ b/frontend/src/app.d.ts@@ -10,4 +10,14 @@ declare global {}}+/// <reference types="vite/client" />++interface ImportMetaEnv {+ readonly VITE_API_URL: string;+}++interface ImportMeta {+ readonly env: ImportMetaEnv;+}+export {};diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex 9c6660cd..540e9864 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -5,6 +5,8 @@import { LayoutDashboard } from "@lucide/svelte";import { page } from '$app/state';+ // Pages that share time range params+ const timeRangePages = ['/metrics', '/transactions'];const sidebarItems = [{Icon: LayoutDashboard, href: "/", title: "Dashboard"},@@ -14,6 +16,41 @@{Icon: Link2, href: "/connection", title: "Connection"},]+ // Build href with time range params preserved between metrics and transactions+ function getHref(baseHref: string): string {+ const currentPath = page.url.pathname;++ // Only preserve params when navigating between time range pages+ const isCurrentTimeRangePage = timeRangePages.some(p => currentPath.startsWith(p));+ const isTargetTimeRangePage = timeRangePages.includes(baseHref);++ if (isCurrentTimeRangePage && isTargetTimeRangePage) {+ // Preserve preset, from, to params+ const params = new URLSearchParams();+ const preset = page.url.searchParams.get('preset');+ const from = page.url.searchParams.get('from');+ const to = page.url.searchParams.get('to');++ if (preset) {+ params.set('preset', preset);+ } else if (from && to) {+ params.set('from', from);+ params.set('to', to);+ }++ // Also preserve servers param for metrics page+ if (baseHref === '/metrics') {+ const servers = page.url.searchParams.get('servers');+ if (servers) params.set('servers', servers);+ }++ const queryString = params.toString();+ return queryString ? `${baseHref}?${queryString}` : baseHref;+ }++ return baseHref;+ }+</script><Sidebar.Sidebar>@@ -30,8 +67,8 @@<Sidebar.SidebarMenu>{#each sidebarItems as sidebarItem}<Sidebar.SidebarMenuItem>- <a href={sidebarItem.href}>- <Sidebar.SidebarMenuButton isActive={page.url.pathname === sidebarItem.href}>+ <a href={getHref(sidebarItem.href)}>+ <Sidebar.SidebarMenuButton isActive={page.url.pathname === sidebarItem.href || page.url.pathname.startsWith(sidebarItem.href + '/')}><sidebarItem.Icon /><span>{sidebarItem.title}</span></Sidebar.SidebarMenuButton>diff --git a/frontend/src/lib/components/dashboard/metric-card.svelte b/frontend/src/lib/components/dashboard/metric-card.svelteindex 7dbc4af8..5bda635e 100644--- a/frontend/src/lib/components/dashboard/metric-card.svelte+++ b/frontend/src/lib/components/dashboard/metric-card.svelte@@ -4,16 +4,22 @@import { TrendingUp, TrendingDown, Minus } from 'lucide-svelte';import { LineChart, Points } from 'layerchart';import { scaleUtc } from 'd3-scale';- import type { DashboardMetric, MetricTrendPoint } from '$lib/types/dashboard';+ import type { DashboardMetric, MetricTrendPoint, ServerMetricTrend } from '$lib/types/dashboard';import { min, max } from 'd3-array';import MetricChartOverlay from './metric-chart-overlay.svelte';- let { metric, timeDomain = null, onRangeSelect } = $props<{+ let { metric, timeDomain = null, onRangeSelect, serverColorMap = {} } = $props<{metric: DashboardMetric;timeDomain?: [Date, Date] | null;onRangeSelect?: (from: Date, to: Date) => void;+ serverColorMap?: Record<string, string>;}>();+ // Check if we have multi-server data+ const hasMultiServerData = $derived(+ metric.servers && metric.servers.length > 1+ );+const statusColors: Record<string, string> = {healthy: 'bg-green-500',warning: 'bg-yellow-500',@@ -74,13 +80,43 @@: 'text-muted-foreground');- const chartConfig = {- value: { label: "Value", color: "var(--chart-1)" },- } satisfies Chart.ChartConfig;+ // Generate chart config based on servers or single value+ const chartConfig = $derived(() => {+ if (hasMultiServerData && metric.servers) {+ const config: Chart.ChartConfig = {};+ for (const server of metric.servers) {+ config[server.serverName] = {+ label: server.serverName,+ color: serverColorMap[server.serverName] || 'var(--chart-1)'+ };+ }+ return config;+ }+ return {+ value: { label: "Value", color: "var(--chart-1)" }+ } satisfies Chart.ChartConfig;+ });- const yMin = $derived(min(metric.trend, (d: MetricTrendPoint) => d.value) ?? 0);- const yMax = $derived(max(metric.trend, (d: MetricTrendPoint) => d.value) ?? 0);- const padding = $derived((yMax - yMin) * 0.1 || 1);+ // Calculate yMin/yMax considering multi-server data+ const yMin = $derived((): number => {+ if (hasMultiServerData && metric.servers) {+ const allValues = metric.servers.flatMap((s: ServerMetricTrend) => s.trend.map((t: MetricTrendPoint) => t.value));+ const minVal = min(allValues);+ return typeof minVal === 'number' ? minVal : 0;+ }+ const minVal = min(metric.trend, (d: MetricTrendPoint) => d.value);+ return typeof minVal === 'number' ? minVal : 0;+ });+ const yMax = $derived((): number => {+ if (hasMultiServerData && metric.servers) {+ const allValues = metric.servers.flatMap((s: ServerMetricTrend) => s.trend.map((t: MetricTrendPoint) => t.value));+ const maxVal = max(allValues);+ return typeof maxVal === 'number' ? maxVal : 0;+ }+ const maxVal = max(metric.trend, (d: MetricTrendPoint) => d.value);+ return typeof maxVal === 'number' ? maxVal : 0;+ });+ const padding = $derived((yMax() - yMin()) * 0.1 || 1);// Calculate X domain from timeDomain or dataconst xDomainValue = $derived(() => {@@ -153,7 +189,47 @@return isolated;});- const hasData = $derived(metric.trend.length > 0 && metric.trend.some((d: MetricTrendPoint) => d.value !== 0));+ const hasData = $derived(() => {+ if (hasMultiServerData && metric.servers) {+ return metric.servers.some((s: ServerMetricTrend) => s.trend.length > 0 && s.trend.some((t: MetricTrendPoint) => t.value !== 0));+ }+ return metric.trend.length > 0 && metric.trend.some((d: MetricTrendPoint) => d.value !== 0);+ });++ // Build merged data and series for multi-server charts+ const multiServerChartData = $derived(() => {+ if (!hasMultiServerData || !metric.servers) return [];++ // Merge all server data by timestamp+ const timeMap = new Map<number, Record<string, number>>();++ for (const server of metric.servers) {+ for (const point of server.trend) {+ const timestamp = point.timestamp.getTime();+ if (!timeMap.has(timestamp)) {+ timeMap.set(timestamp, { timestamp } as any);+ }+ timeMap.get(timestamp)![server.serverName] = point.value;+ }+ }++ // Convert to sorted array+ return Array.from(timeMap.values())+ .map(entry => ({+ timestamp: new Date(entry.timestamp as unknown as number),+ ...entry+ }))+ .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());+ });++ const multiServerSeries = $derived(() => {+ if (!hasMultiServerData || !metric.servers) return [];+ return metric.servers.map((server: ServerMetricTrend) => ({+ key: server.serverName,+ label: server.serverName,+ color: serverColorMap[server.serverName] || 'var(--chart-1)'+ }));+ });</script><Card.Root class="gap-3">@@ -198,48 +274,71 @@unit={metric.unit}formatValue={(v) => metric.formatValue ? metric.formatValue(v) : formatMetricValue(v, metric.unit)}>- <Chart.Container config={chartConfig}>- {#if hasData}- <LineChart- data={metric.trend}- x="timestamp"- xScale={scaleUtc()}- xDomain={xDomainValue()}- series={[- {- key: "value",- label: "Value",- color: chartConfig.value.color,- },- ]}- yDomain={[Math.max(0, yMin - padding), yMax + padding]}- seriesLayout="stack"- props={{- xAxis: {- format: () => ""- },- yAxis: {- format: (a: number) => a > 999 ? (a/1000).toFixed(0) + "k" : `${a}`,- },- spline: {- defined: isDefined- }- }}- tooltip={false}- >- {#snippet aboveMarks()}- <!-- Isolated points (dots only where no line) -->- {#if isolatedPoints().length > 0}- <Points- data={isolatedPoints()}- x="timestamp"- y="value"- r={2}- fill={chartConfig.value.color}- />- {/if}- {/snippet}- </LineChart>+ <Chart.Container config={chartConfig()}>+ {#if hasData()}+ {#if hasMultiServerData}+ <!-- Multi-server chart with separate lines per server -->+ <LineChart+ data={multiServerChartData()}+ x="timestamp"+ xScale={scaleUtc()}+ xDomain={xDomainValue()}+ series={multiServerSeries()}+ yDomain={[Math.max(0, yMin() - padding), yMax() + padding]}+ seriesLayout="overlap"+ props={{+ xAxis: {+ format: () => ""+ },+ yAxis: {+ format: (a: number) => a > 999 ? (a/1000).toFixed(0) + "k" : `${a}`,+ }+ }}+ tooltip={false}+ />+ {:else}+ <!-- Single series chart (original behavior) -->+ <LineChart+ data={metric.trend}+ x="timestamp"+ xScale={scaleUtc()}+ xDomain={xDomainValue()}+ series={[+ {+ key: "value",+ label: "Value",+ color: "var(--chart-1)",+ },+ ]}+ yDomain={[Math.max(0, yMin() - padding), yMax() + padding]}+ seriesLayout="stack"+ props={{+ xAxis: {+ format: () => ""+ },+ yAxis: {+ format: (a: number) => a > 999 ? (a/1000).toFixed(0) + "k" : `${a}`,+ },+ spline: {+ defined: isDefined+ }+ }}+ tooltip={false}+ >+ {#snippet aboveMarks()}+ <!-- Isolated points (dots only where no line) -->+ {#if isolatedPoints().length > 0}+ <Points+ data={isolatedPoints()}+ x="timestamp"+ y="value"+ r={2}+ fill="var(--chart-1)"+ />+ {/if}+ {/snippet}+ </LineChart>+ {/if}{:else}<div class="flex h-[100px] items-center justify-center text-sm text-muted-foreground">No data in this perioddiff --git a/frontend/src/lib/components/dashboard/server-filter.svelte b/frontend/src/lib/components/dashboard/server-filter.sveltenew file mode 100644index 00000000..f3a6b31f--- /dev/null+++ b/frontend/src/lib/components/dashboard/server-filter.svelte@@ -0,0 +1,136 @@+<script lang="ts">+ import { Button } from '$lib/components/ui/button';+ import * as Popover from '$lib/components/ui/popover';+ import { Checkbox } from '$lib/components/ui/checkbox';+ import { Server, ChevronDown } from 'lucide-svelte';+ import { getServerColor } from '$lib/utils/server-colors';++ interface Props {+ availableServers: string[];+ selectedServers: string[];+ onSelectionChange?: (servers: string[]) => void;+ }++ let {+ availableServers,+ selectedServers = $bindable([]),+ onSelectionChange+ }: Props = $props();++ let isOpen = $state(false);+ let tempSelectedServers = $state<Set<string>>(new Set(selectedServers));++ // Sync temp state when popover opens+ $effect(() => {+ if (isOpen) {+ tempSelectedServers = new Set(selectedServers);+ }+ });++ // Computed states+ const allSelected = $derived(tempSelectedServers.size === availableServers.length);+ const noneSelected = $derived(tempSelectedServers.size === 0);++ // Display label for the trigger button+ const displayLabel = $derived(() => {+ if (selectedServers.length === 0 || selectedServers.length === availableServers.length) {+ return 'All servers';+ }+ if (selectedServers.length === 1) {+ return selectedServers[0];+ }+ return `${selectedServers.length} servers`;+ });++ function toggleServer(serverName: string) {+ const newSet = new Set(tempSelectedServers);+ if (newSet.has(serverName)) {+ newSet.delete(serverName);+ } else {+ newSet.add(serverName);+ }+ tempSelectedServers = newSet;+ }++ function selectAll() {+ tempSelectedServers = new Set(availableServers);+ }++ function clearAll() {+ tempSelectedServers = new Set();+ }++ function handleOpenChange(open: boolean) {+ if (!open) {+ // Apply selection when closing+ const newSelection = Array.from(tempSelectedServers);+ selectedServers = newSelection;+ onSelectionChange?.(newSelection);+ }+ isOpen = open;+ }++ function isSelected(serverName: string): boolean {+ return tempSelectedServers.has(serverName);+ }+</script>++<Popover.Root bind:open={isOpen} onOpenChange={handleOpenChange}>+ <Popover.Trigger>+ <Button variant="outline" class="h-9 justify-between gap-2 font-normal">+ <span class="flex items-center gap-2">+ <Server class="h-4 w-4 text-muted-foreground" />+ <span class="truncate">{displayLabel()}</span>+ </span>+ <ChevronDown class="h-4 w-4 text-muted-foreground" />+ </Button>+ </Popover.Trigger>+ <Popover.Content class="w-[220px] p-0" align="start">+ <div class="p-3 border-b">+ <div class="flex items-center justify-between">+ <span class="text-sm font-medium">Servers</span>+ <div class="flex items-center gap-2">+ <button+ class="text-xs text-primary hover:underline disabled:text-muted-foreground disabled:no-underline"+ onclick={selectAll}+ disabled={allSelected}+ >+ All+ </button>+ <span class="text-muted-foreground">|</span>+ <button+ class="text-xs text-primary hover:underline disabled:text-muted-foreground disabled:no-underline"+ onclick={clearAll}+ disabled={noneSelected}+ >+ Clear+ </button>+ </div>+ </div>+ </div>+ <div class="max-h-[280px] overflow-y-auto py-2">+ {#each availableServers.sort() as serverName}+ {@const color = getServerColor(serverName, availableServers)}+ <button+ class="w-full px-3 py-1.5 text-left text-sm hover:bg-muted/50 flex items-center gap-3 transition-colors"+ onclick={() => toggleServer(serverName)}+ >+ <Checkbox+ checked={isSelected(serverName)}+ aria-label={`Select ${serverName}`}+ />+ <span+ class="w-3 h-3 rounded-full flex-shrink-0"+ style="background-color: {color};"+ ></span>+ <span class="truncate">{serverName}</span>+ </button>+ {/each}+ </div>+ <div class="p-3 border-t">+ <Button size="sm" class="w-full" onclick={() => isOpen = false}>+ Apply+ </Button>+ </div>+ </Popover.Content>+</Popover.Root>diff --git a/frontend/src/lib/components/segments/segment-empty-state.svelte b/frontend/src/lib/components/segments/segment-empty-state.sveltenew file mode 100644index 00000000..df87be81--- /dev/null+++ b/frontend/src/lib/components/segments/segment-empty-state.svelte@@ -0,0 +1,155 @@+<script lang="ts">+ import { ExternalLink, Code } from 'lucide-svelte';+ import type { Framework } from '$lib/state/projects.svelte';+ import Highlight from 'svelte-highlight';+ import go from 'svelte-highlight/languages/go';+ import { themeState } from '$lib/state/theme.svelte';+ import 'svelte-highlight/styles/github-dark.css';++ type Props = {+ framework: Framework;+ };++ let { framework }: Props = $props();++ // TODO: Replace with actual documentation URLs when docs are built+ function getDocsUrl(fw: Framework): string {+ switch (fw) {+ case 'gin':+ return 'https://docs.traceway.io/go/gin/segments';+ case 'fiber':+ return 'https://docs.traceway.io/go/fiber/segments';+ case 'chi':+ return 'https://docs.traceway.io/go/chi/segments';+ case 'fasthttp':+ return 'https://docs.traceway.io/go/fasthttp/segments';+ case 'stdlib':+ return 'https://docs.traceway.io/go/stdlib/segments';+ default:+ return 'https://docs.traceway.io/go/segments';+ }+ }++ function getCodeExample(fw: Framework): string {+ switch (fw) {+ case 'gin':+ return `// In your Gin handler+func MyHandler(c *gin.Context) {+ // Start a segment for database operation+ seg := traceway.StartSegment(c.Request.Context(), "db.query")+ defer seg.End()++ // Your database operation here+ result, err := db.Query("SELECT * FROM users")++ // Another segment for cache+ cacheSeg := traceway.StartSegment(c.Request.Context(), "cache.set")+ cache.Set("users", result)+ cacheSeg.End()+}`;+ case 'fiber':+ return `// In your Fiber handler+func MyHandler(c *fiber.Ctx) error {+ // Start a segment for database operation+ seg := traceway.StartSegment(c.UserContext(), "db.query")+ defer seg.End()++ // Your database operation here+ result, err := db.Query("SELECT * FROM users")++ // Another segment for cache+ cacheSeg := traceway.StartSegment(c.UserContext(), "cache.set")+ cache.Set("users", result)+ cacheSeg.End()++ return c.JSON(result)+}`;+ default:+ return `seg := traceway.StartSegment(ctx, "db.load")+// perform your operations here+seg.End()`;+ }+ }++ const docsUrl = $derived(getDocsUrl(framework));+ const codeExample = $derived(getCodeExample(framework));+</script>++<div class="flex flex-col items-center justify-center py-8 text-center">+ <div class="bg-muted mb-4 rounded-full p-3">+ <Code class="text-muted-foreground h-6 w-6" />+ </div>+ <h3 class="mb-2 text-lg font-semibold">No Segments Recorded</h3>+ <p class="text-muted-foreground mb-4 max-w-md text-sm">+ Segments allow you to track the timing of individual operations within a transaction, such as+ database queries, HTTP calls, or cache operations.+ </p>++ <div class="mb-4 w-full max-w-xl text-left">+ <p class="text-muted-foreground mb-2 text-xs">Example usage:</p>+ <div class="rounded-lg overflow-hidden text-sm {themeState.isDark ? 'dark-code' : 'light-code'}">+ <Highlight language={go} code={codeExample} />+ </div>+ </div>++ <!-- TODO: After we add the docs we should update this :/ -->+ <!-- <a+ href={docsUrl}+ target="_blank"+ rel="noopener noreferrer"+ class="text-primary inline-flex items-center gap-2 text-sm hover:underline"+ >+ View Documentation+ <ExternalLink class="h-4 w-4" />+ </a> -->+</div>++<style>+ /* Light theme - override dark theme defaults */+ :global(.light-code .hljs) {+ background: #f6f8fa;+ color: #24292e;+ }+ :global(.light-code .hljs-keyword),+ :global(.light-code .hljs-selector-tag) {+ color: #d73a49;+ }+ :global(.light-code .hljs-string),+ :global(.light-code .hljs-attr) {+ color: #032f62;+ }+ :global(.light-code .hljs-function),+ :global(.light-code .hljs-title) {+ color: #6f42c1;+ }+ :global(.light-code .hljs-comment) {+ color: #6a737d;+ }+ :global(.light-code .hljs-built_in) {+ color: #005cc5;+ }++ /* Dark theme - ensure dark styles apply */+ :global(.dark-code .hljs) {+ background: #0d1117;+ color: #c9d1d9;+ }+ :global(.dark-code .hljs-keyword),+ :global(.dark-code .hljs-selector-tag) {+ color: #ff7b72;+ }+ :global(.dark-code .hljs-string),+ :global(.dark-code .hljs-attr) {+ color: #a5d6ff;+ }+ :global(.dark-code .hljs-function),+ :global(.dark-code .hljs-title) {+ color: #d2a8ff;+ }+ :global(.dark-code .hljs-comment) {+ color: #8b949e;+ }+ :global(.dark-code .hljs-built_in) {+ color: #79c0ff;+ }+</style>diff --git a/frontend/src/lib/components/segments/segment-row.svelte b/frontend/src/lib/components/segments/segment-row.sveltenew file mode 100644index 00000000..808610b6--- /dev/null+++ b/frontend/src/lib/components/segments/segment-row.svelte@@ -0,0 +1,124 @@+<script lang="ts">+ import type { Segment } from '$lib/types/segments';+ import { cn } from '$lib/utils';++ type Props = {+ segment: Segment;+ transactionStart: number;+ transactionDuration: number;+ isOdd: boolean;+ };++ let { segment, transactionStart, transactionDuration, isOdd }: Props = $props();++ const segmentStartMs = $derived(new Date(segment.startTime).getTime() - transactionStart);+ const segmentDurationMs = $derived(segment.duration / 1_000_000);+ const transactionDurationMs = $derived(transactionDuration / 1_000_000);++ // Calculate position and width as percentages+ const leftPercent = $derived(Math.max(0, (segmentStartMs / transactionDurationMs) * 100));+ const widthPercent = $derived(+ Math.min(100 - leftPercent, (segmentDurationMs / transactionDurationMs) * 100)+ );++ // 14 segment colors based on name prefix+ function getSegmentColor(name: string): { bg: string; ring: string } {+ if (name.startsWith('db.')) return { bg: 'bg-blue-400', ring: 'ring-blue-500' };+ if (name.startsWith('http.')) return { bg: 'bg-green-400', ring: 'ring-green-500' };+ if (name.startsWith('cache.')) return { bg: 'bg-purple-400', ring: 'ring-purple-500' };+ if (name.startsWith('queue.')) return { bg: 'bg-orange-400', ring: 'ring-orange-500' };+ if (name.startsWith('auth.')) return { bg: 'bg-red-400', ring: 'ring-red-500' };+ if (name.startsWith('file.')) return { bg: 'bg-amber-400', ring: 'ring-amber-500' };+ if (name.startsWith('grpc.')) return { bg: 'bg-cyan-400', ring: 'ring-cyan-500' };+ if (name.startsWith('email.')) return { bg: 'bg-pink-400', ring: 'ring-pink-500' };+ if (name.startsWith('search.')) return { bg: 'bg-indigo-400', ring: 'ring-indigo-500' };+ if (name.startsWith('redis.')) return { bg: 'bg-teal-400', ring: 'ring-teal-500' };+ if (name.startsWith('kafka.')) return { bg: 'bg-lime-400', ring: 'ring-lime-500' };+ if (name.startsWith('graphql.')) return { bg: 'bg-rose-400', ring: 'ring-rose-500' };+ if (name.startsWith('s3.')) return { bg: 'bg-sky-400', ring: 'ring-sky-500' };+ return { bg: 'bg-slate-400', ring: 'ring-slate-500' };+ }++ const segmentColor = $derived(getSegmentColor(segment.name));++ function formatDuration(nanoseconds: number): string {+ const ms = nanoseconds / 1_000_000;+ if (ms < 1) return `${(nanoseconds / 1000).toFixed(0)}µs`;+ if (ms < 1000) return `${ms.toFixed(1)}ms`;+ return `${(ms / 1000).toFixed(2)}s`;+ }++ // Tooltip state+ let isHovered = $state(false);+ let tooltipX = $state(0);+ let tooltipY = $state(0);+ let barElement: HTMLDivElement;++ function handleMouseEnter(e: MouseEvent) {+ isHovered = true;+ updateTooltipPosition(e);+ }++ function handleMouseMove(e: MouseEvent) {+ if (isHovered) {+ updateTooltipPosition(e);+ }+ }++ function handleMouseLeave() {+ isHovered = false;+ }++ function updateTooltipPosition(e: MouseEvent) {+ const rect = barElement.getBoundingClientRect();+ tooltipX = rect.left + rect.width / 2;+ tooltipY = rect.top - 8;+ }+</script>++<div class={cn('border-border flex items-center border-b last:border-b-0', isOdd ? 'bg-muted/40' : '')}>+ <!-- Segment name -->+ <div+ class="border-border w-[180px] flex-shrink-0 truncate border-r px-3 py-1.5 font-mono text-xs"+ title={segment.name}+ >+ {segment.name}+ </div>++ <!-- Timeline bar -->+ <div class="relative flex-1">+ <div class="relative mx-2 h-4">+ <div+ bind:this={barElement}+ class={cn(+ 'absolute h-full rounded transition-all',+ segmentColor.bg,+ isHovered && `ring-2 ring-offset-1 ${segmentColor.ring}`+ )}+ style="left: {leftPercent}%; width: {Math.max(widthPercent, 1)}%"+ onmouseenter={handleMouseEnter}+ onmousemove={handleMouseMove}+ onmouseleave={handleMouseLeave}+ role="presentation"+ ></div>+ </div>+ </div>++ <!-- Duration -->+ <div class="text-muted-foreground border-border w-[100px] flex-shrink-0 border-l px-3 py-1.5 text-right font-mono text-xs">+ {formatDuration(segment.duration)}+ </div>++ <!-- Portal tooltip (inside row to preserve :last-child, but uses fixed positioning) -->+ {#if isHovered}+ <div+ class="fixed z-[9999] -translate-x-1/2 -translate-y-full pointer-events-none"+ style="left: {tooltipX}px; top: {tooltipY}px;"+ >+ <div class="bg-popover text-popover-foreground whitespace-nowrap rounded-md border px-2 py-1 text-xs shadow-md">+ <div class="font-medium">{segment.name}</div>+ <div class="text-muted-foreground">{formatDuration(segment.duration)}</div>+ </div>+ </div>+ {/if}+</div>diff --git a/frontend/src/lib/components/segments/segment-waterfall.svelte b/frontend/src/lib/components/segments/segment-waterfall.sveltenew file mode 100644index 00000000..b409aa41--- /dev/null+++ b/frontend/src/lib/components/segments/segment-waterfall.svelte@@ -0,0 +1,48 @@+<script lang="ts">+ import type { Segment } from '$lib/types/segments';+ import SegmentRow from './segment-row.svelte';++ type Props = {+ segments: Segment[];+ transactionDuration: number;+ transactionStartTime: string;+ };++ let { segments, transactionDuration, transactionStartTime }: Props = $props();++ // Calculate the time scale for the waterfall+ // Use the earliest segment's start time as reference since transaction.recordedAt may be truncated+ const transactionStart = $derived(+ segments.length === 0+ ? new Date(transactionStartTime).getTime()+ : segments.reduce((earliest, seg) => {+ const segTime = new Date(seg.startTime).getTime();+ return segTime < earliest ? segTime : earliest;+ }, new Date(segments[0].startTime).getTime())+ );+ const durationMs = $derived(transactionDuration / 1_000_000);+</script>++<div class="border-border overflow-hidden rounded-lg border">+ <!-- Header -->+ <div class="bg-muted/30 border-border flex border-b">+ <div class="border-border w-[180px] flex-shrink-0 border-r px-3 py-1.5 text-xs font-medium">+ Segment Name+ </div>+ <div class="flex-1 px-3 py-1.5">+ <div class="text-muted-foreground flex justify-between text-xs">+ <span>0ms</span>+ <span>{(durationMs / 2).toFixed(0)}ms</span>+ <span>{durationMs.toFixed(0)}ms</span>+ </div>+ </div>+ <div class="border-border w-[100px] flex-shrink-0 border-l px-3 py-1.5 text-right text-xs font-medium">+ Duration+ </div>+ </div>++ <!-- Segments -->+ {#each segments as segment, i}+ <SegmentRow {segment} {transactionStart} {transactionDuration} isOdd={i % 2 === 1} />+ {/each}+</div>diff --git a/frontend/src/lib/components/ui/button/button.svelte b/frontend/src/lib/components/ui/button/button.svelteindex a8296aed..5c50ff5b 100644--- a/frontend/src/lib/components/ui/button/button.svelte+++ b/frontend/src/lib/components/ui/button/button.svelte@@ -4,7 +4,7 @@import { type VariantProps, tv } from "tailwind-variants";export const buttonVariants = tv({- base: "focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ base: "cursor-pointer focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",variants: {variant: {default: "bg-primary text-primary-foreground hover:bg-primary/90 shadow-xs",diff --git a/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte b/frontend/src/lib/components/ui/loading-circle/loading-circle.svelteindex f5d73349..8bc9f25a 100644--- a/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte+++ b/frontend/src/lib/components/ui/loading-circle/loading-circle.svelte@@ -8,7 +8,8 @@sm: "h-4 w-4",default: "h-6 w-6",md: "h-8 w-8",- lg: "h-12 w-12"+ lg: "h-12 w-12",+ xlg: "h-18 w-18"}},defaultVariants: {diff --git a/frontend/src/lib/types/dashboard.ts b/frontend/src/lib/types/dashboard.tsindex 166fa4d6..2a51fadd 100644--- a/frontend/src/lib/types/dashboard.ts+++ b/frontend/src/lib/types/dashboard.ts@@ -5,6 +5,12 @@ export type MetricTrendPoint = {value: number;};+export type ServerMetricTrend = {+ serverName: string;+ value: number;+ trend: MetricTrendPoint[];+};+export type DashboardMetric = {id: string;name: string;@@ -14,9 +20,11 @@ export type DashboardMetric = {change24h: number; // Percentage change (e.g., 5.2 or -3.1)status: MetricStatus;formatValue?: (value: number) => string;+ servers?: ServerMetricTrend[]; // Per-server breakdown for multi-server metrics};export type DashboardData = {metrics: DashboardMetric[];lastUpdated: Date;+ availableServers?: string[]; // List of servers with data in the time range};diff --git a/frontend/src/lib/types/segments.ts b/frontend/src/lib/types/segments.tsnew file mode 100644index 00000000..9528d2ba--- /dev/null+++ b/frontend/src/lib/types/segments.ts@@ -0,0 +1,29 @@+export type Segment = {+ id: string;+ transactionId: string;+ projectId: string;+ name: string;+ startTime: string; // ISO datetime+ duration: number; // nanoseconds+ recordedAt: string;+};++export type TransactionDetail = {+ id: string;+ projectId: string;+ endpoint: string;+ duration: number;+ recordedAt: string;+ statusCode: number;+ bodySize: number;+ clientIP: string;+ scope: Record<string, string> | null;+ appVersion: string;+ serverName: string;+};++export type TransactionDetailResponse = {+ transaction: TransactionDetail;+ segments: Segment[];+ hasSegments: boolean;+};diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.tsnew file mode 100644index 00000000..11a0c918--- /dev/null+++ b/frontend/src/lib/utils/navigation.ts@@ -0,0 +1,18 @@+import { goto } from '$app/navigation';++/**+ * Handles row click with support for ctrl/cmd+click to open in new tab.+ * Returns an onclick handler for use in table rows.+ */+export function createRowClickHandler(href: string) {+ return (event: MouseEvent) => {+ // Check for ctrl (Windows/Linux) or cmd (Mac) key+ if (event.ctrlKey || event.metaKey) {+ // Open in new tab+ window.open(href, '_blank');+ } else {+ // Normal navigation+ goto(href);+ }+ };+}diff --git a/frontend/src/lib/utils/server-colors.ts b/frontend/src/lib/utils/server-colors.tsnew file mode 100644index 00000000..91c69d11--- /dev/null+++ b/frontend/src/lib/utils/server-colors.ts@@ -0,0 +1,25 @@+export const SERVER_COLORS = [+ 'var(--chart-1)',+ 'var(--chart-2)',+ 'var(--chart-3)',+ 'var(--chart-4)',+ 'var(--chart-5)',+ 'oklch(0.7 0.15 300)', // Purple+ 'oklch(0.7 0.15 120)', // Green+ 'oklch(0.65 0.2 0)' // Red+] as const;++export function getServerColor(serverName: string, allServers: string[]): string {+ const sortedServers = [...allServers].sort();+ const index = sortedServers.indexOf(serverName);+ return SERVER_COLORS[index % SERVER_COLORS.length];+}++export function getServerColorMap(servers: string[]): Record<string, string> {+ const map: Record<string, string> = {};+ const sortedServers = [...servers].sort();+ sortedServers.forEach((server, index) => {+ map[server] = SERVER_COLORS[index % SERVER_COLORS.length];+ });+ return map;+}diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex fa15e505..ff496917 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -1,10 +1,10 @@<script lang="ts">import { onMount } from 'svelte';- import { goto } from '$app/navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';import { LoadingCircle } from '$lib/components/ui/loading-circle';import * as Table from '$lib/components/ui/table';import * as Tooltip from '$lib/components/ui/tooltip';- import { ArrowRight, Info, Gauge, Bug, CircleQuestionMark } from 'lucide-svelte';+ import { ArrowRight, Info, Gauge, Bug, CircleQuestionMark, TriangleAlert } from 'lucide-svelte';import { api } from '$lib/api';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';@@ -84,31 +84,15 @@}}- // Calculate impact score based on call volume and response time variance- // Returns: { score: number, level: 'critical' | 'high' | 'medium' | 'low' }- function calculateImpact(count: number, p50: number, p95: number): { score: number; level: 'critical' | 'high' | 'medium' | 'low' } {- const varianceMs = (p95 - p50) / 1_000_000; // Convert to ms+ // Calculate impact level based on call volume and response time variance+ // Returns: 'critical' | 'high' | 'medium' | null (null = not significant)+ function getImpactLevel(count: number, p50: number, p95: number): 'critical' | 'high' | 'medium' | null {+ const varianceMs = (p95 - p50) / 1_000_000;const score = count * varianceMs;-- // Thresholds based on score (calls * variance_ms)- // Critical: >100 (e.g., 10 calls * 10ms variance)- // High: >10 (e.g., 10 calls * 1ms variance)- // Medium: >1 (e.g., 1 call * 1ms variance)- // Low: no meaningful variance- if (score > 100) return { score, level: 'critical' };- if (score > 10) return { score, level: 'high' };- if (score > 1) return { score, level: 'medium' };- return { score, level: 'low' };- }-- function getImpactIndicator(count: number, p50: number, p95: number): { text: string; class: string } {- const { level } = calculateImpact(count, p50, p95);- switch (level) {- case 'critical': return { text: '!!!', class: 'text-red-500 font-bold' };- case 'high': return { text: '!!', class: 'text-orange-500 font-bold' };- case 'medium': return { text: '!', class: 'text-yellow-500 font-bold' };- default: return { text: '-', class: 'text-muted-foreground' };- }+ if (score > 100) return 'critical';+ if (score > 10) return 'high';+ if (score > 1) return 'medium';+ return null;}function truncateStackTrace(stackTrace: string): string {@@ -132,7 +116,7 @@{#if loading}<div class="flex justify-center items-center py-20">- <LoadingCircle size="lg" />+ <LoadingCircle size="xlg" /></div>{:else if !error}<div class="space-y-8">@@ -226,9 +210,10 @@</Table.Header><Table.Body>{#each data.worstEndpoints as endpoint}+ {@const impactLevel = getImpactLevel(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}<Table.Rowclass="cursor-pointer hover:bg-muted/50"- onclick={() => goto(`/transactions/${encodeURIComponent(endpoint.endpoint)}`)}+ onclick={createRowClickHandler(`/transactions/${encodeURIComponent(endpoint.endpoint)}`)}><Table.Cell class="py-3 font-mono text-sm truncate max-w-[300px]" title={endpoint.endpoint}>{endpoint.endpoint}@@ -242,15 +227,28 @@<Table.Cell class="py-3 text-right font-mono text-sm tabular-nums">{formatDuration(endpoint.p95Duration)}</Table.Cell>- {@const impact = getImpactIndicator(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}- <Table.Cell class="py-3 text-right font-mono text-sm tabular-nums">- <span class={impact.class}>{impact.text}</span>+ <Table.Cell class="py-3 text-right">+ {#if impactLevel === 'critical'}+ <span class="inline-flex items-center gap-1 rounded-full bg-red-500/15 px-2 py-0.5 text-xs font-medium text-red-600 dark:text-red-400">+ <TriangleAlert class="h-3 w-3" />+ Critical+ </span>+ {:else if impactLevel === 'high'}+ <span class="inline-flex items-center gap-1 rounded-full bg-orange-500/15 px-2 py-0.5 text-xs font-medium text-orange-600 dark:text-orange-400">+ <TriangleAlert class="h-3 w-3" />+ High+ </span>+ {:else if impactLevel === 'medium'}+ <span class="inline-flex items-center gap-1 rounded-full bg-yellow-500/15 px-2 py-0.5 text-xs font-medium text-yellow-600 dark:text-yellow-500">+ Medium+ </span>+ {/if}</Table.Cell></Table.Row>{/each}<Table.Rowclass="cursor-pointer bg-muted/50 hover:bg-muted"- onclick={() => goto('/transactions')}+ onclick={createRowClickHandler('/transactions')}><Table.Cell colspan={5} class="py-2 text-center text-sm text-muted-foreground">View all transactions <ArrowRight class="inline h-3.5 w-3.5" />@@ -336,7 +334,7 @@{#each data.recentIssues as issue}<Table.Rowclass="cursor-pointer hover:bg-muted/50"- onclick={() => goto(`/issues/${issue.exceptionHash}`)}+ onclick={createRowClickHandler(`/issues/${issue.exceptionHash}`)}><Table.Cell class="py-3 font-mono text-sm" title={issue.stackTrace}>{truncateStackTrace(issue.stackTrace)}@@ -351,7 +349,7 @@{/each}<Table.Rowclass="cursor-pointer bg-muted/50 hover:bg-muted"- onclick={() => goto('/issues')}+ onclick={createRowClickHandler('/issues')}><Table.Cell colspan={3} class="py-2 text-center text-sm text-muted-foreground">View all issues <ArrowRight class="inline h-3.5 w-3.5" />diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelteindex bd984cc8..5c4fff3b 100644--- a/frontend/src/routes/connection/+page.svelte+++ b/frontend/src/routes/connection/+page.svelte@@ -55,7 +55,8 @@// Framework-specific code snippetsfunction getFrameworkCode(framework: Framework, token: string): string {- const connectionString = token ? `${token}@http://localhost:8082/api/client/report` : 'YOUR_TOKEN@http://localhost:8082/api/client/report';+ const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8082';+ const connectionString = token ? `${token}@${apiUrl}/api/client/report` : `YOUR_TOKEN@${apiUrl}/api/client/report`;switch (framework) {case 'gin':diff --git a/frontend/src/routes/issues/+page.svelte b/frontend/src/routes/issues/+page.svelteindex 36a189fa..f5fb1868 100644--- a/frontend/src/routes/issues/+page.svelte+++ b/frontend/src/routes/issues/+page.svelte@@ -1,6 +1,6 @@<script lang="ts">import { onMount } from 'svelte';- import { goto } from '$app/navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';import { api } from '$lib/api';import * as Table from "$lib/components/ui/table";import { Input } from "$lib/components/ui/input";@@ -11,6 +11,8 @@import { projectsState } from '$lib/state/projects.svelte';import IssueTrendChart from '$lib/components/issue-trend-chart.svelte';import Archive from "@lucide/svelte/icons/archive";+ import { CircleHelp } from "@lucide/svelte";+ import * as Tooltip from "$lib/components/ui/tooltip";type ExceptionTrendPoint = {timestamp: string;@@ -242,7 +244,7 @@<Table.Row><Table.Cell colspan={5} class="h-48"><div class="flex justify-center items-center h-full">- <LoadingCircle size="lg" />+ <LoadingCircle size="xlg" /></div></Table.Cell></Table.Row>@@ -273,10 +275,58 @@aria-label="Select all"/></Table.Head>- <Table.Head>Issue</Table.Head>- <Table.Head class="w-[190px]">Trend</Table.Head>- <Table.Head class="w-[80px] text-right">Events</Table.Head>- <Table.Head class="w-[180px]">Last Seen</Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Issue+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">The error message or exception that occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head class="w-[190px]">+ <span class="flex items-center gap-1.5">+ Trend+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Hourly occurrence pattern over the last 24h</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head class="w-[80px] text-right">+ <span class="flex items-center justify-end gap-1.5">+ Events+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Total number of times this issue occurred in the selected range</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head class="w-[180px]">+ <span class="flex items-center gap-1.5">+ Last Seen+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">When this issue last occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head></Table.Row></Table.Header><Table.Body>@@ -295,22 +345,22 @@<Table.Cellclass="font-mono text-sm truncate max-w-[400px]"title={exception.stackTrace}- onclick={() => goto(`/issues/${exception.exceptionHash}`)}+ onclick={createRowClickHandler(`/issues/${exception.exceptionHash}`)}><span class="text-foreground">{exception.stackTrace.split('\n')[0]}</span></Table.Cell>- <Table.Cell onclick={() => goto(`/issues/${exception.exceptionHash}`)}>+ <Table.Cell onclick={createRowClickHandler(`/issues/${exception.exceptionHash}`)}><IssueTrendChart trend={exception.hourlyTrend || []} /></Table.Cell><Table.Cellclass="text-right tabular-nums font-medium"- onclick={() => goto(`/issues/${exception.exceptionHash}`)}+ onclick={createRowClickHandler(`/issues/${exception.exceptionHash}`)}>{exception.count.toLocaleString()}</Table.Cell><Table.Cellclass="text-muted-foreground"- onclick={() => goto(`/issues/${exception.exceptionHash}`)}+ onclick={createRowClickHandler(`/issues/${exception.exceptionHash}`)}>{new Date(exception.lastSeen).toLocaleString()}</Table.Cell>diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelteindex d4d6e5f9..47b63a7a 100644--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte@@ -2,6 +2,7 @@import { onMount } from 'svelte';import { page } from '$app/state';import { goto } from '$app/navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';import { api } from '$lib/api';import { Button } from "$lib/components/ui/button";import * as Card from "$lib/components/ui/card";@@ -9,7 +10,8 @@import { Skeleton } from "$lib/components/ui/skeleton";import { ErrorDisplay } from "$lib/components/ui/error-display";import { projectsState } from '$lib/state/projects.svelte';- import { ArrowRight } from "lucide-svelte";+ import { ArrowRight, CircleHelp } from "lucide-svelte";+ import * as Tooltip from "$lib/components/ui/tooltip";type ExceptionGroup = {exceptionHash: string;@@ -28,6 +30,7 @@appVersion: string;serverName: string;isMessage: boolean;+ endpoint: string;};let group = $state<ExceptionGroup | null>(null);@@ -197,33 +200,92 @@{#if occurrences.length > 0}<Table.Header><Table.Row>- <Table.Head>Recorded At</Table.Head>- <Table.Head>Transaction ID</Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Recorded At+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">When this occurrence was recorded</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Server+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Server instance where error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Version+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Application version when error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Endpoint+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">The API route where this error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head></Table.Row></Table.Header>{/if}<Table.Body>{#if occurrences.length === 0}<Table.Row>- <Table.Cell colspan={2} class="h-24 text-center">+ <Table.Cell colspan={4} class="h-24 text-center">No occurrences found.</Table.Cell></Table.Row>{:else}{#each occurrences as occurrence}- <Table.Row>+ <Table.Row+ class={occurrence.endpoint ? "cursor-pointer hover:bg-muted/50" : ""}+ onclick={occurrence.endpoint ? createRowClickHandler(`/transactions/${encodeURIComponent(occurrence.endpoint)}`) : undefined}+ ><Table.Cell>{new Date(occurrence.recordedAt).toLocaleString()}</Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.appVersion || '-'}+ </Table.Cell><Table.Cell class="font-mono text-sm">- {occurrence.transactionId || '-'}+ {occurrence.endpoint || '-'}</Table.Cell></Table.Row>{/each}{#if hasMoreOccurrences}<Table.Rowclass="cursor-pointer bg-muted/50 hover:bg-muted"- onclick={() => goto(`/issues/${page.params.exceptionHash}/events`)}+ onclick={createRowClickHandler(`/issues/${page.params.exceptionHash}/events`)}>- <Table.Cell colspan={2} class="py-2 text-center text-sm text-muted-foreground">+ <Table.Cell colspan={4} class="py-2 text-center text-sm text-muted-foreground">View all {total} events <ArrowRight class="inline h-3.5 w-3.5" /></Table.Cell></Table.Row>diff --git a/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/events/+page.svelteindex 30f80f0f..7db2e6d8 100644--- a/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte@@ -2,6 +2,7 @@import { onMount } from 'svelte';import { page } from '$app/state';import { goto } from '$app/navigation';+ import { createRowClickHandler } from '$lib/utils/navigation';import { api } from '$lib/api';import { Button } from "$lib/components/ui/button";import * as Card from "$lib/components/ui/card";@@ -10,6 +11,8 @@import { Skeleton } from "$lib/components/ui/skeleton";import { ErrorDisplay } from "$lib/components/ui/error-display";import { projectsState } from '$lib/state/projects.svelte';+ import { CircleHelp } from "lucide-svelte";+ import * as Tooltip from "$lib/components/ui/tooltip";type ExceptionGroup = {exceptionHash: string;@@ -24,6 +27,9 @@exceptionHash: string;stackTrace: string;recordedAt: string;+ serverName: string;+ appVersion: string;+ endpoint: string;};let group = $state<ExceptionGroup | null>(null);@@ -162,8 +168,58 @@{#if loading || occurrences.length > 0}<Table.Header><Table.Row>- <Table.Head>Recorded At</Table.Head>- <Table.Head>Transaction ID</Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Recorded At+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">When this occurrence was recorded</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Server+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Server instance where error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Version+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Application version when error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Endpoint+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">The API route where this error occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head></Table.Row></Table.Header>{/if}@@ -172,24 +228,32 @@{#each Array(5) as _}<Table.Row><Table.Cell><Skeleton class="h-4 w-[150px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[100px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell><Table.Cell><Skeleton class="h-4 w-[200px]" /></Table.Cell></Table.Row>{/each}{:else if occurrences.length === 0}<Table.Row>- <Table.Cell colspan={2} class="h-24 text-center">+ <Table.Cell colspan={4} class="h-24 text-center">No events found.</Table.Cell></Table.Row>{:else}{#each occurrences as occurrence}<Table.Row- class="cursor-pointer hover:bg-muted/50"- onclick={() => goto(`/issues/${page.params.exceptionHash}`)}+ class={occurrence.endpoint ? "cursor-pointer hover:bg-muted/50" : ""}+ onclick={occurrence.endpoint ? createRowClickHandler(`/transactions/${encodeURIComponent(occurrence.endpoint)}`) : undefined}><Table.Cell>{new Date(occurrence.recordedAt).toLocaleString()}</Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {occurrence.appVersion || '-'}+ </Table.Cell><Table.Cell class="font-mono text-sm">- {occurrence.transactionId || '-'}+ {occurrence.endpoint || '-'}</Table.Cell></Table.Row>{/each}diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.svelteindex 9f3536bb..98153996 100644--- a/frontend/src/routes/metrics/+page.svelte+++ b/frontend/src/routes/metrics/+page.svelte@@ -5,19 +5,28 @@import { LoadingCircle } from '$lib/components/ui/loading-circle';import { RefreshCw } from 'lucide-svelte';import MetricCard from '$lib/components/dashboard/metric-card.svelte';- import type { DashboardData, DashboardMetric } from '$lib/types/dashboard';+ import ServerFilter from '$lib/components/dashboard/server-filter.svelte';+ import type { DashboardData, DashboardMetric, ServerMetricTrend, MetricTrendPoint } from '$lib/types/dashboard';import { Card, CardContent } from '$lib/components/ui/card';import { api } from '$lib/api';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';import { CalendarDate } from '@internationalized/date';+ import { getServerColorMap } from '$lib/utils/server-colors';let dashboardData = $state<DashboardData | null>(null);let loading = $state(true);let error = $state('');let errorStatus = $state<number>(0);+ // Server filtering state+ let availableServers = $state<string[]>([]);+ let selectedServers = $state<string[]>([]);++ // Compute server color map for consistent colors across all charts+ const serverColorMap = $derived(getServerColorMap(availableServers));+// Preset definitions (must match TimeRangePicker)const presetMinutes: Record<string, number> = {'30m': 30,@@ -41,16 +50,20 @@}// Parse URL params- function parseUrlParams(): { preset: string | null; from: Date | null; to: Date | null } {- if (!browser) return { preset: '6h', from: null, to: null };+ function parseUrlParams(): { preset: string | null; from: Date | null; to: Date | null; servers: string[] } {+ if (!browser) return { preset: '6h', from: null, to: null, servers: [] };const params = new URLSearchParams(window.location.search);const presetParam = params.get('preset');const fromParam = params.get('from');const toParam = params.get('to');+ const serversParam = params.get('servers');++ // Parse servers from URL+ const servers = serversParam ? serversParam.split(',').filter(s => s.length > 0) : [];// If preset is specified, use itif (presetParam && presetMinutes[presetParam]) {- return { preset: presetParam, from: null, to: null };+ return { preset: presetParam, from: null, to: null, servers };}// If custom from/to specified@@ -58,12 +71,12 @@const from = new Date(fromParam);const to = new Date(toParam);if (!isNaN(from.getTime()) && !isNaN(to.getTime())) {- return { preset: null, from, to };+ return { preset: null, from, to, servers };}}// Default to 6h preset- return { preset: '6h', from: null, to: null };+ return { preset: '6h', from: null, to: null, servers };}function dateToCalendarDate(date: Date): CalendarDate {@@ -87,7 +100,7 @@let toTime = $state(dateToTimeString(initialRange.to));let sharedTimeDomain = $state<[Date, Date] | null>(null);- // Update URL with current time range+ // Update URL with current time range and server selectionfunction updateUrl(pushState = true) {if (!browser) return;@@ -104,6 +117,11 @@params.set('to', toDateTime.toISOString());}+ // Store server selection in URL (only if not all servers selected)+ if (selectedServers.length > 0 && selectedServers.length < availableServers.length) {+ params.set('servers', selectedServers.join(','));+ }+const newUrl = `${window.location.pathname}?${params.toString()}`;if (pushState) {@@ -132,6 +150,9 @@toTime = dateToTimeString(urlParams.to);}+ // Update selected servers from URL+ selectedServers = urlParams.servers;+loadDashboard(false); // Don't push to history on popstate}@@ -155,6 +176,11 @@loadDashboard();}+ function handleServerSelectionChange(servers: string[]) {+ selectedServers = servers;+ loadDashboard();+ }+// Handle drag-to-zoom selection from chart overlayfunction handleChartRangeSelect(from: Date, to: Date) {selectedPreset = null; // Chart selection is always custom@@ -180,12 +206,21 @@// Store shared time domain for chartssharedTimeDomain = [fromDateTime, toDateTime];- // Build query params for date range- const dateParams = `fromDate=${fromDateTime.toISOString()}&toDate=${toDateTime.toISOString()}`;- const response = await api.get(`/dashboard?${dateParams}`, {+ // Build query params for date range and server selection+ let queryParams = `fromDate=${fromDateTime.toISOString()}&toDate=${toDateTime.toISOString()}`;+ if (selectedServers.length > 0 && selectedServers.length < availableServers.length) {+ queryParams += `&servers=${selectedServers.join(',')}`;+ }++ const response = await api.get(`/dashboard?${queryParams}`, {projectId: projectsState.currentProjectId ?? undefined});+ // Update available servers from API response+ if (response.availableServers) {+ availableServers = response.availableServers;+ }+// Transform the API response to match the DashboardData type// Convert timestamp strings to Date objectsconst metrics: DashboardMetric[] = response.metrics.map((m: any) => ({@@ -198,12 +233,22 @@value: t.value})),change24h: m.change24h,- status: m.status+ status: m.status,+ // Include per-server data if available+ servers: m.servers?.map((s: any): ServerMetricTrend => ({+ serverName: s.serverName,+ value: s.value,+ trend: s.trend.map((t: any): MetricTrendPoint => ({+ timestamp: new Date(t.timestamp),+ value: t.value+ }))+ }))}));dashboardData = {metrics,- lastUpdated: new Date(response.lastUpdated)+ lastUpdated: new Date(response.lastUpdated),+ availableServers: response.availableServers};} catch (e: any) {errorStatus = e.status || 0;@@ -248,6 +293,13 @@{/if}</div><div class="flex items-center gap-2">+ {#if availableServers.length > 1}+ <ServerFilter+ {availableServers}+ bind:selectedServers+ onSelectionChange={handleServerSelectionChange}+ />+ {/if}<TimeRangePickerbind:fromDatebind:toDate@@ -276,11 +328,11 @@<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">{#if loading}<div class="col-span-full flex justify-center items-center py-20">- <LoadingCircle size="lg" />+ <LoadingCircle size="xlg" /></div>{:else if dashboardData}{#each dashboardData.metrics as metric (metric.id)}- <MetricCard {metric} timeDomain={sharedTimeDomain} onRangeSelect={handleChartRangeSelect} />+ <MetricCard {metric} timeDomain={sharedTimeDomain} onRangeSelect={handleChartRangeSelect} {serverColorMap} />{/each}{/if}</div>diff --git a/frontend/src/routes/transactions/+page.svelte b/frontend/src/routes/transactions/+page.svelteindex d0ee8bf3..c4409306 100644--- a/frontend/src/routes/transactions/+page.svelte+++ b/frontend/src/routes/transactions/+page.svelte@@ -1,12 +1,13 @@<script lang="ts">- import { onMount } from 'svelte';- import { goto } from '$app/navigation';+ import { onMount, onDestroy } from 'svelte';+ import { browser } from '$app/environment';import { api } from '$lib/api';import * as Table from "$lib/components/ui/table";import { Button } from "$lib/components/ui/button";import { LoadingCircle } from "$lib/components/ui/loading-circle";import * as Select from "$lib/components/ui/select";- import { ArrowUpDown, ArrowDown, ArrowUp } from "@lucide/svelte";+ import { ArrowUpDown, ArrowDown, ArrowUp, TriangleAlert, CircleHelp } from "@lucide/svelte";+ import * as Tooltip from "$lib/components/ui/tooltip";import { TimeRangePicker } from "$lib/components/ui/time-range-picker";import { CalendarDate, getLocalTimeZone, today } from "@internationalized/date";import { projectsState } from '$lib/state/projects.svelte';@@ -33,11 +34,121 @@let total = $state(0);let totalPages = $state(0);+ // Preset definitions (must match TimeRangePicker)+ const presetMinutes: Record<string, number> = {+ '30m': 30,+ '60m': 60,+ '3h': 180,+ '6h': 360,+ '12h': 720,+ '24h': 1440,+ '3d': 4320,+ '7d': 10080,+ '1M': 43200,+ '3M': 129600,+ };++ // Helper functions+ function getTimeRangeFromPreset(presetValue: string): { from: Date; to: Date } {+ const minutes = presetMinutes[presetValue] || 360;+ const now = new Date();+ const from = new Date(now.getTime() - minutes * 60 * 1000);+ return { from, to: now };+ }++ function dateToCalendarDate(date: Date): CalendarDate {+ return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());+ }++ function dateToTimeString(date: Date): string {+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;+ }++ // Parse URL params - supports preset OR from/to+ function parseUrlParams(): { preset: string | null; from: Date | null; to: Date | null } {+ if (!browser) return { preset: '6h', from: null, to: null };+ const params = new URLSearchParams(window.location.search);+ const presetParam = params.get('preset');+ const fromParam = params.get('from');+ const toParam = params.get('to');++ // If preset is specified, use it+ if (presetParam && presetMinutes[presetParam]) {+ return { preset: presetParam, from: null, to: null };+ }++ // If custom from/to specified+ if (fromParam && toParam) {+ const from = new Date(fromParam);+ const to = new Date(toParam);+ if (!isNaN(from.getTime()) && !isNaN(to.getTime())) {+ return { preset: null, from, to };+ }+ }++ // Default to 6h preset+ return { preset: '6h', from: null, to: null };+ }++ // Initialize from URL+ const initialUrlParams = parseUrlParams();+ const initialRange = initialUrlParams.preset+ ? getTimeRangeFromPreset(initialUrlParams.preset)+ : { from: initialUrlParams.from!, to: initialUrlParams.to! };+// Date Range State- let fromDate = $state<CalendarDate>(today(getLocalTimeZone()).subtract({ days: 7 }));- let toDate = $state<CalendarDate>(today(getLocalTimeZone()));- let fromTime = $state('00:00');- let toTime = $state('23:59');+ let selectedPreset = $state<string | null>(initialUrlParams.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to));+ let fromTime = $state(dateToTimeString(initialRange.from));+ let toTime = $state(dateToTimeString(initialRange.to));++ // Update URL with current time range+ function updateUrl(pushState = true) {+ if (!browser) return;++ const params = new URLSearchParams();++ if (selectedPreset) {+ params.set('preset', selectedPreset);+ } else {+ const fromDateTime = new Date(getFromDateTime());+ const toDateTime = new Date(getToDateTime());+ params.set('from', fromDateTime.toISOString());+ params.set('to', toDateTime.toISOString());+ }++ const newUrl = `${window.location.pathname}?${params.toString()}`;++ if (pushState) {+ window.history.pushState({}, '', newUrl);+ } else {+ window.history.replaceState({}, '', newUrl);+ }+ }++ // Handle browser back/forward navigation+ function handlePopState() {+ const urlParams = parseUrlParams();++ if (urlParams.preset) {+ selectedPreset = urlParams.preset;+ const range = getTimeRangeFromPreset(urlParams.preset);+ fromDate = dateToCalendarDate(range.from);+ fromTime = dateToTimeString(range.from);+ toDate = dateToCalendarDate(range.to);+ toTime = dateToTimeString(range.to);+ } else if (urlParams.from && urlParams.to) {+ selectedPreset = null;+ fromDate = dateToCalendarDate(urlParams.from);+ fromTime = dateToTimeString(urlParams.from);+ toDate = dateToCalendarDate(urlParams.to);+ toTime = dateToTimeString(urlParams.to);+ }++ page = 1;+ loadData(false);+ }// Sorting - default to impact descendinglet orderBy = $state<SortField>('impact');@@ -64,13 +175,14 @@return `${dateStr}T${toTime || '23:59'}`;}- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) {+ function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {fromDate = from.date;fromTime = from.time;toDate = to.date;toTime = to.time;+ selectedPreset = preset;page = 1;- loadData();+ loadData(true);}function formatDuration(nanoseconds: number): string {@@ -94,30 +206,24 @@return count.toLocaleString();}- // Calculate impact score based on call volume and response time variance- function calculateImpact(count: number, p50: number, p95: number): { score: number; level: 'critical' | 'high' | 'medium' | 'low' } {+ // Calculate impact level based on call volume and response time variance+ // Returns: 'critical' | 'high' | 'medium' | null (null = not significant)+ function getImpactLevel(count: number, p50: number, p95: number): 'critical' | 'high' | 'medium' | null {const varianceMs = (p95 - p50) / 1_000_000;const score = count * varianceMs;- if (score > 100) return { score, level: 'critical' };- if (score > 10) return { score, level: 'high' };- if (score > 1) return { score, level: 'medium' };- return { score, level: 'low' };+ if (score > 100) return 'critical';+ if (score > 10) return 'high';+ if (score > 1) return 'medium';+ return null;}- function getImpactIndicator(count: number, p50: number, p95: number): { text: string; class: string } {- const { level } = calculateImpact(count, p50, p95);- switch (level) {- case 'critical': return { text: '!!!', class: 'text-red-500 font-bold' };- case 'high': return { text: '!!', class: 'text-orange-500 font-bold' };- case 'medium': return { text: '!', class: 'text-yellow-500 font-bold' };- default: return { text: '-', class: 'text-muted-foreground' };- }- }-- async function loadData() {+ async function loadData(pushToHistory = true) {loading = true;error = '';+ // Update URL+ updateUrl(pushToHistory);+try {const requestBody = {fromDate: new Date(getFromDateTime()).toISOString(),@@ -146,14 +252,14 @@function handlePageChange(newPage: number) {if (newPage >= 1 && newPage <= totalPages) {page = newPage;- loadData();+ loadData(false); // Don't push to history for pagination}}function handlePageSizeChange(newPageSize: string) {pageSize = parseInt(newPageSize);page = 1;- loadData();+ loadData(false); // Don't push to history for pagination}function handleSort(field: SortField) {@@ -166,19 +272,41 @@sortDirection = 'desc';}page = 1;- loadData();+ loadData(false); // Don't push to history for sorting}- function navigateToEndpoint(endpoint: string) {- const params = new URLSearchParams({- from: getFromDateTime(),- to: getToDateTime()- });- goto(`/transactions/${encodeURIComponent(endpoint)}?${params.toString()}`);+ function getEndpointUrl(endpoint: string): string {+ const params = new URLSearchParams();+ if (selectedPreset) {+ params.set('preset', selectedPreset);+ } else {+ params.set('from', new Date(getFromDateTime()).toISOString());+ params.set('to', new Date(getToDateTime()).toISOString());+ }+ return `/transactions/${encodeURIComponent(endpoint)}?${params.toString()}`;+ }++ function navigateToEndpoint(endpoint: string, event: MouseEvent) {+ const url = getEndpointUrl(endpoint);+ if (event.ctrlKey || event.metaKey) {+ window.open(url, '_blank');+ } else {+ window.location.href = url;+ }}onMount(() => {- loadData();+ // Add popstate listener for back/forward navigation+ window.addEventListener('popstate', handlePopState);++ // Initial load with replaceState (don't push to history)+ loadData(false);+ });++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }});</script>@@ -191,6 +319,7 @@bind:toDatebind:fromTimebind:toTime+ bind:preset={selectedPreset}onApply={handleTimeRangeChange}/></div>@@ -203,7 +332,7 @@<Table.Row><Table.Cell colspan={5} class="h-48"><div class="flex justify-center items-center h-full">- <LoadingCircle size="lg" />+ <LoadingCircle size="xlg" /></div></Table.Cell></Table.Row>@@ -227,91 +356,143 @@{:else}<Table.Header><Table.Row>- <Table.Head>Endpoint</Table.Head>+ <Table.Head>+ <span class="flex items-center gap-1.5">+ Endpoint+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">The API route or page being accessed</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head><Table.Head class="w-[100px]">- <Button- variant="ghost"- size="sm"- class="h-8 -ml-3 font-medium"- onclick={() => handleSort('count')}- >- Calls- {#if orderBy === 'count'}- {#if sortDirection === 'desc'}- <ArrowDown class="ml-2 h-4 w-4" />+ <div class="flex items-center">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('count')}+ >+ Calls+ {#if orderBy === 'count'}+ {#if sortDirection === 'desc'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUp class="ml-2 h-4 w-4" />+ {/if}{:else}- <ArrowUp class="ml-2 h-4 w-4" />+ <ArrowUpDown class="ml-2 h-4 w-4" />{/if}- {:else}- <ArrowUpDown class="ml-2 h-4 w-4" />- {/if}- </Button>+ </Button>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Total number of requests</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </div></Table.Head><Table.Head class="w-[100px]">- <Button- variant="ghost"- size="sm"- class="h-8 -ml-3 font-medium"- onclick={() => handleSort('p50_duration')}- >- Typical- {#if orderBy === 'p50_duration'}- {#if sortDirection === 'desc'}- <ArrowDown class="ml-2 h-4 w-4" />+ <div class="flex items-center">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('p50_duration')}+ >+ Typical+ {#if orderBy === 'p50_duration'}+ {#if sortDirection === 'desc'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUp class="ml-2 h-4 w-4" />+ {/if}{:else}- <ArrowUp class="ml-2 h-4 w-4" />+ <ArrowUpDown class="ml-2 h-4 w-4" />{/if}- {:else}- <ArrowUpDown class="ml-2 h-4 w-4" />- {/if}- </Button>+ </Button>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Median response time (P50)</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </div></Table.Head><Table.Head class="w-[100px]">- <Button- variant="ghost"- size="sm"- class="h-8 -ml-3 font-medium"- onclick={() => handleSort('p95_duration')}- >- Slow- {#if orderBy === 'p95_duration'}- {#if sortDirection === 'desc'}- <ArrowDown class="ml-2 h-4 w-4" />+ <div class="flex items-center">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 -ml-3 font-medium"+ onclick={() => handleSort('p95_duration')}+ >+ Slow+ {#if orderBy === 'p95_duration'}+ {#if sortDirection === 'desc'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUp class="ml-2 h-4 w-4" />+ {/if}{:else}- <ArrowUp class="ml-2 h-4 w-4" />+ <ArrowUpDown class="ml-2 h-4 w-4" />{/if}- {:else}- <ArrowUpDown class="ml-2 h-4 w-4" />- {/if}- </Button>+ </Button>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">95th percentile - slowest 5% of requests</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </div></Table.Head>- <Table.Head class="w-[80px]">- <Button- variant="ghost"- size="sm"- class="h-8 -ml-3 font-medium"- onclick={() => handleSort('impact')}- >- Impact- {#if orderBy === 'impact'}- {#if sortDirection === 'desc'}- <ArrowDown class="ml-2 h-4 w-4" />+ <Table.Head class="w-[120px] text-right">+ <div class="flex items-center justify-end gap-1.5">+ <Button+ variant="ghost"+ size="sm"+ class="h-8 font-medium"+ onclick={() => handleSort('impact')}+ >+ Impact+ {#if orderBy === 'impact'}+ {#if sortDirection === 'desc'}+ <ArrowDown class="ml-2 h-4 w-4" />+ {:else}+ <ArrowUp class="ml-2 h-4 w-4" />+ {/if}{:else}- <ArrowUp class="ml-2 h-4 w-4" />+ <ArrowUpDown class="ml-2 h-4 w-4" />{/if}- {:else}- <ArrowUpDown class="ml-2 h-4 w-4" />- {/if}- </Button>+ </Button>+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Priority based on traffic × response time variance</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </div></Table.Head></Table.Row></Table.Header><Table.Body>{#each endpoints as endpoint}- {@const impact = getImpactIndicator(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}+ {@const impactLevel = getImpactLevel(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}<Table.Rowclass="cursor-pointer hover:bg-muted/50"- onclick={() => navigateToEndpoint(endpoint.endpoint)}+ onclick={(e) => navigateToEndpoint(endpoint.endpoint, e)}><Table.Cell class="font-mono text-sm">{endpoint.endpoint}@@ -325,8 +506,22 @@<Table.Cell class="font-mono text-sm tabular-nums">{formatDuration(endpoint.p95Duration)}</Table.Cell>- <Table.Cell class="font-mono text-sm tabular-nums">- <span class={impact.class}>{impact.text}</span>+ <Table.Cell class="text-right">+ {#if impactLevel === 'critical'}+ <span class="inline-flex items-center gap-1 rounded-full bg-red-500/15 px-2 py-0.5 text-xs font-medium text-red-600 dark:text-red-400">+ <TriangleAlert class="h-3 w-3" />+ Critical+ </span>+ {:else if impactLevel === 'high'}+ <span class="inline-flex items-center gap-1 rounded-full bg-orange-500/15 px-2 py-0.5 text-xs font-medium text-orange-600 dark:text-orange-400">+ <TriangleAlert class="h-3 w-3" />+ High+ </span>+ {:else if impactLevel === 'medium'}+ <span class="inline-flex items-center gap-1 rounded-full bg-yellow-500/15 px-2 py-0.5 text-xs font-medium text-yellow-600 dark:text-yellow-500">+ Medium+ </span>+ {/if}</Table.Cell></Table.Row>{/each}diff --git a/frontend/src/routes/transactions/[endpoint]/+page.svelte b/frontend/src/routes/transactions/[endpoint]/+page.svelteindex 3ead4156..64f24cc2 100644--- a/frontend/src/routes/transactions/[endpoint]/+page.svelte+++ b/frontend/src/routes/transactions/[endpoint]/+page.svelte@@ -11,6 +11,7 @@import { ErrorDisplay } from "$lib/components/ui/error-display";import { projectsState } from '$lib/state/projects.svelte';import ScopeDisplay from '$lib/components/scope-display.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';type Transaction = {id: string;@@ -21,6 +22,8 @@bodySize: number;clientIP: string;scope: Record<string, string> | null;+ serverName: string;+ appVersion: string;};type SortField = 'recorded_at' | 'duration' | 'status_code' | 'body_size';@@ -40,11 +43,66 @@let total = $state(0);let totalPages = $state(0);+ // Preset definitions (must match TimeRangePicker)+ const presetMinutes: Record<string, number> = {+ '30m': 30,+ '60m': 60,+ '3h': 180,+ '6h': 360,+ '12h': 720,+ '24h': 1440,+ '3d': 4320,+ '7d': 10080,+ '1M': 43200,+ '3M': 129600,+ };++ // Helper functions+ function getTimeRangeFromPreset(presetValue: string): { from: Date; to: Date } {+ const minutes = presetMinutes[presetValue] || 360;+ const now = new Date();+ const from = new Date(now.getTime() - minutes * 60 * 1000);+ return { from, to: now };+ }++ function dateToCalendarDate(date: Date): CalendarDate {+ return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());+ }++ function dateToTimeString(date: Date): string {+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;+ }++ // Initialize from URL params+ function getInitialRange(): { preset: string | null; from: Date; to: Date } {+ // If preset is provided, use it+ if (data.preset && presetMinutes[data.preset]) {+ const range = getTimeRangeFromPreset(data.preset);+ return { preset: data.preset, from: range.from, to: range.to };+ }++ // If custom from/to provided+ if (data.from && data.to) {+ const from = new Date(data.from);+ const to = new Date(data.to);+ if (!isNaN(from.getTime()) && !isNaN(to.getTime())) {+ return { preset: null, from, to };+ }+ }++ // Default to 6h preset+ const range = getTimeRangeFromPreset('6h');+ return { preset: '6h', from: range.from, to: range.to };+ }++ const initialRange = getInitialRange();+// Date Range State- let fromDate = $state<CalendarDate>(today(getLocalTimeZone()).subtract({ days: 7 }));- let toDate = $state<CalendarDate>(today(getLocalTimeZone()));- let fromTime = $state('00:00');- let toTime = $state('23:59');+ let selectedPreset = $state<string | null>(initialRange.preset);+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from));+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to));+ let fromTime = $state(dateToTimeString(initialRange.from));+ let toTime = $state(dateToTimeString(initialRange.to));// Sorting Statelet orderBy = $state<SortField>('recorded_at');@@ -61,11 +119,12 @@return `${dateStr}T${toTime || '23:59'}`;}- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) {+ function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {fromDate = from.date;fromTime = from.time;toDate = to.date;toTime = to.time;+ selectedPreset = preset;page = 1;loadData();}@@ -160,28 +219,29 @@}function goBack() {- goto('/transactions');+ const params = new URLSearchParams();+ if (selectedPreset) {+ params.set('preset', selectedPreset);+ } else {+ params.set('from', new Date(getFromDateTime()).toISOString());+ params.set('to', new Date(getToDateTime()).toISOString());+ }+ goto(`/transactions?${params.toString()}`);}- onMount(() => {- // Initialize dates from URL params or use defaults (already set in state)- if (data.from && data.to) {- // Parse from URL params: "YYYY-MM-DDTHH:MM"- const fromParts = data.from.split('T');- const toParts = data.to.split('T');-- if (fromParts[0]) {- const [year, month, day] = fromParts[0].split('-').map(Number);- fromDate = new CalendarDate(year, month, day);- fromTime = fromParts[1] || '00:00';- }-- if (toParts[0]) {- const [year, month, day] = toParts[0].split('-').map(Number);- toDate = new CalendarDate(year, month, day);- toTime = toParts[1] || '23:59';- }+ // Build URL for transaction detail with current time range+ function getTransactionDetailUrl(transactionId: string): string {+ const params = new URLSearchParams();+ if (selectedPreset) {+ params.set('preset', selectedPreset);+ } else {+ params.set('from', new Date(getFromDateTime()).toISOString());+ params.set('to', new Date(getToDateTime()).toISOString());}+ return `/transactions/${encodeURIComponent(data.endpoint)}/${transactionId}?${params.toString()}`;+ }++ onMount(() => {loadData();});</script>@@ -223,6 +283,7 @@bind:toDatebind:fromTimebind:toTime+ bind:preset={selectedPreset}onApply={handleTimeRangeChange}/></div>@@ -310,6 +371,8 @@</Button></Table.Head><Table.Head class="w-[140px]">Client IP</Table.Head>+ <Table.Head class="w-[120px]">Server</Table.Head>+ <Table.Head class="w-[100px]">Version</Table.Head><Table.Head>Context</Table.Head></Table.Row></Table.Header>@@ -323,18 +386,23 @@<Table.Cell><Skeleton class="h-4 w-[50px]" /></Table.Cell><Table.Cell><Skeleton class="h-4 w-[60px]" /></Table.Cell><Table.Cell><Skeleton class="h-4 w-[100px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[100px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell><Table.Cell><Skeleton class="h-4 w-[150px]" /></Table.Cell></Table.Row>{/each}{:else if transactions.length === 0}<Table.Row>- <Table.Cell colspan={6} class="h-24 text-center">+ <Table.Cell colspan={8} class="h-24 text-center">No transactions found in this time range.</Table.Cell></Table.Row>{:else}{#each transactions as transaction}- <Table.Row>+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={createRowClickHandler(getTransactionDetailUrl(transaction.id))}+ ><Table.Cell class="text-muted-foreground">{new Date(transaction.recordedAt).toLocaleString()}</Table.Cell>@@ -350,6 +418,12 @@<Table.Cell class="font-mono text-sm text-muted-foreground">{transaction.clientIP}</Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {transaction.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {transaction.appVersion || '-'}+ </Table.Cell><Table.Cell><ScopeDisplay scope={transaction.scope} /></Table.Cell>diff --git a/frontend/src/routes/transactions/[endpoint]/+page.ts b/frontend/src/routes/transactions/[endpoint]/+page.tsindex fb736733..9b05016d 100644--- a/frontend/src/routes/transactions/[endpoint]/+page.ts+++ b/frontend/src/routes/transactions/[endpoint]/+page.ts@@ -11,7 +11,8 @@ export const load: PageLoad = ({ params, url }) => {return {endpoint: params.endpoint,- from: url.searchParams.get('from') || '',- to: url.searchParams.get('to') || ''+ preset: url.searchParams.get('preset') || null,+ from: url.searchParams.get('from') || null,+ to: url.searchParams.get('to') || null};};diff --git a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.svelte b/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.sveltenew file mode 100644index 00000000..cbaddfb6--- /dev/null+++ b/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.svelte@@ -0,0 +1,228 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import * as Card from '$lib/components/ui/card';+ import { Skeleton } from '$lib/components/ui/skeleton';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { projectsState } from '$lib/state/projects.svelte';+ import { ArrowLeft } from 'lucide-svelte';+ import SegmentWaterfall from '$lib/components/segments/segment-waterfall.svelte';+ import SegmentEmptyState from '$lib/components/segments/segment-empty-state.svelte';+ import type { TransactionDetailResponse } from '$lib/types/segments';++ let { data } = $props();++ let response = $state<TransactionDetailResponse | null>(null);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);++ async function loadData() {+ loading = true;+ error = '';+ notFound = false;++ try {+ const result = await api.post(+ `/transactions/${data.transactionId}`,+ {},+ { projectId: projectsState.currentProjectId ?? undefined }+ );+ response = result;+ } catch (e: unknown) {+ console.error(e);+ const err = e as { status?: number; message?: string };+ if (err.status === 404) {+ notFound = true;+ } else {+ error = err.message || 'Failed to load transaction details';+ }+ } finally {+ loading = false;+ }+ }++ function formatDuration(nanoseconds: number): string {+ const ms = nanoseconds / 1_000_000;+ if (ms < 1) {+ return `${(nanoseconds / 1000).toFixed(2)}us`;+ } else if (ms < 1000) {+ return `${ms.toFixed(2)}ms`;+ } else {+ return `${(ms / 1000).toFixed(2)}s`;+ }+ }++ function formatBytes(bytes: number): string {+ if (bytes < 1024) {+ return `${bytes} B`;+ } else if (bytes < 1024 * 1024) {+ return `${(bytes / 1024).toFixed(1)} KB`;+ } else {+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;+ }+ }++ function getStatusColor(statusCode: number): string {+ if (statusCode >= 200 && statusCode < 300) return 'text-green-500';+ if (statusCode >= 300 && statusCode < 400) return 'text-blue-500';+ if (statusCode >= 400 && statusCode < 500) return 'text-yellow-500';+ return 'text-red-500';+ }++ function getBackUrl(): string {+ const params = new URLSearchParams();+ if (data.preset) {+ params.set('preset', data.preset);+ } else if (data.from && data.to) {+ params.set('from', data.from);+ params.set('to', data.to);+ }+ const queryString = params.toString();+ return `/transactions/${encodeURIComponent(data.endpoint)}${queryString ? '?' + queryString : ''}`;+ }++ function goBack() {+ goto(getBackUrl());+ }++ const backHref = $derived(getBackUrl());++ onMount(() => {+ loadData();+ });+</script>++<div class="space-y-6">+ <!-- Header -->+ <div class="flex items-center gap-4">+ <Button variant="ghost" size="sm" onclick={goBack} class="h-8 w-8 p-0">+ <ArrowLeft class="h-4 w-4" />+ </Button>+ <div>+ <h2 class="font-mono text-2xl font-bold tracking-tight">+ {decodeURIComponent(data.endpoint)}+ </h2>+ <p class="text-muted-foreground text-sm">Transaction ID: {data.transactionId}</p>+ </div>+ </div>++ {#if loading}+ <Card.Root>+ <Card.Header>+ <Skeleton class="h-6 w-48" />+ </Card.Header>+ <Card.Content>+ <Skeleton class="mb-2 h-4 w-full" />+ <Skeleton class="mb-2 h-4 w-3/4" />+ <Skeleton class="h-32 w-full" />+ </Card.Content>+ </Card.Root>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Transaction Not Found"+ description="The transaction you're looking for doesn't exist or may have expired."+ backHref={backHref}+ backLabel="Back to Endpoint"+ onRetry={loadData}+ identifier={data.transactionId}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Failed to Load Transaction"+ description={error}+ backHref={backHref}+ backLabel="Back to Endpoint"+ onRetry={loadData}+ />+ {:else if response}+ <!-- Transaction Summary Card -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Transaction Details</Card.Title>+ <Card.Description>+ Recorded: {new Date(response.transaction.recordedAt).toLocaleString()}+ </Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4">+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Duration</p>+ <p class="font-mono text-lg">{formatDuration(response.transaction.duration)}</p>+ </div>+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Status</p>+ <p class="font-mono text-lg {getStatusColor(response.transaction.statusCode)}">+ {response.transaction.statusCode}+ </p>+ </div>+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Body Size</p>+ <p class="font-mono">{formatBytes(response.transaction.bodySize)}</p>+ </div>+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Client IP</p>+ <p class="font-mono">{response.transaction.clientIP || '-'}</p>+ </div>+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Server</p>+ <p class="font-mono">{response.transaction.serverName || '-'}</p>+ </div>+ <div class="space-y-1">+ <p class="text-muted-foreground text-sm">Version</p>+ <p class="font-mono">{response.transaction.appVersion || '-'}</p>+ </div>+ </div>+ </Card.Content>+ </Card.Root>++ <!-- Segments Section -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Segments</Card.Title>+ <Card.Description>+ {#if response.hasSegments}+ Timing breakdown of operations within this transaction+ {:else}+ No segments recorded for this transaction+ {/if}+ </Card.Description>+ </Card.Header>+ <Card.Content>+ {#if response.hasSegments}+ <SegmentWaterfall+ segments={response.segments}+ transactionDuration={response.transaction.duration}+ transactionStartTime={response.transaction.recordedAt}+ />+ {:else}+ <SegmentEmptyState framework={projectsState.currentProject?.framework ?? 'gin'} />+ {/if}+ </Card.Content>+ </Card.Root>++ <!-- Context Card (if scope exists) -->+ {#if response.transaction.scope && Object.keys(response.transaction.scope).length > 0}+ <Card.Root>+ <Card.Header>+ <Card.Title>Context</Card.Title>+ <Card.Description>Additional context captured with this transaction</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3">+ {#each Object.entries(response.transaction.scope).sort((a, b) => a[0].localeCompare(b[0])) as [key, value]}+ <div class="bg-muted flex flex-col gap-1 rounded-md p-3">+ <span class="text-muted-foreground text-xs font-medium">{key}</span>+ <span class="break-all font-mono text-sm">{value}</span>+ </div>+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+ {/if}+</div>diff --git a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.ts b/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.tsnew file mode 100644index 00000000..6f3a3a72--- /dev/null+++ b/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.ts@@ -0,0 +1,19 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const prerender = false;++export const load: PageLoad = ({ params, url }) => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login');+ }++ return {+ endpoint: params.endpoint,+ transactionId: params.transactionId,+ preset: url.searchParams.get('preset') || null,+ from: url.searchParams.get('from') || null,+ to: url.searchParams.get('to') || null+ };+};