The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
throwing exceptions + scope added
dduxe5e9e312ee24
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.goindex 0170d07e..5789d57e 100644--- a/backend/app/controllers/auth.controller.go+++ b/backend/app/controllers/auth.controller.go@@ -22,10 +22,7 @@ func (a authController) Login(c *gin.Context) {appToken := os.Getenv("APP_TOKEN")if appToken == "" {- // Fallback or error if env not set, for safety.- // Assuming config is required.- c.JSON(http.StatusInternalServerError, gin.H{"error": "Server misconfiguration"})- return+ panic("APP_TOKEN environment variable is not set")}if request.Token != appToken {diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.goindex 8dbaf3fd..b10d7487 100644--- a/backend/app/controllers/dashboard.controller.go+++ b/backend/app/controllers/dashboard.controller.go@@ -11,6 +11,35 @@ import (type dashboardController struct{}+type DashboardOverviewResponse struct {+ RecentIssues []models.ExceptionGroup `json:"recentIssues"`+ WorstEndpoints []models.EndpointStats `json:"worstEndpoints"`+}++func (d dashboardController) GetDashboardOverview(c *gin.Context) {+ projectId := c.Query("projectId")++ now := time.Now()+ start := now.Add(-24 * time.Hour)++ // Get last 10 issues in the last 24 hours+ recentIssues, _, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, projectId, start, now, 1, 10, "last_seen", "")+ if err != nil {+ panic(err)+ }++ // Get 10 worst performing endpoints+ worstEndpoints, err := repositories.TransactionRepository.FindWorstEndpoints(c, projectId, start, now, 10)+ if err != nil {+ panic(err)+ }++ c.JSON(http.StatusOK, DashboardOverviewResponse{+ RecentIssues: recentIssues,+ WorstEndpoints: worstEndpoints,+ })+}+func (d dashboardController) GetDashboard(c *gin.Context) {projectId := c.Query("projectId")@@ -24,8 +53,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 1. Requests countrequestsTrend, err := repositories.TransactionRepository.CountByHour(c, projectId, start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, now)requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, projectId, prevStart, prevEnd)@@ -34,8 +62,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 2. Exceptions countexceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByHour(c, projectId, start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, now)exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)@@ -44,8 +71,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 3. Average Response TimeavgDurationTrend, err := repositories.TransactionRepository.AvgDurationByHour(c, projectId, start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}avgDurationCurrent := getLastValue(avgDurationTrend)avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByHour(c, projectId, prevStart, prevEnd)@@ -55,8 +81,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 4. Error RateerrorRateTrend, err := repositories.TransactionRepository.ErrorRateByHour(c, projectId, start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}errorRateCurrent := getLastValue(errorRateTrend)errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByHour(c, projectId, prevStart, prevEnd)@@ -66,8 +91,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 5. CPU UsagecpuTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, "cpu", start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}cpuCurrent := getLastValue(cpuTrend)cpuPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, "cpu", prevStart, prevEnd)@@ -76,8 +100,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 6. Memory UsagememTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, "ram", start, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}memCurrent := getLastValue(memTrend)memPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, "ram", prevStart, prevEnd)diff --git a/backend/app/controllers/exception_stack_trace.controller.go b/backend/app/controllers/exception_stack_trace.controller.goindex 745d8fdf..f6a5fa3b 100644--- a/backend/app/controllers/exception_stack_trace.controller.go+++ b/backend/app/controllers/exception_stack_trace.controller.go@@ -41,8 +41,7 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.Cexceptions, total, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.Search)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, PaginatedResponse[models.ExceptionGroup]{@@ -75,8 +74,7 @@ func (e exceptionStackTraceController) FindByHash(c *gin.Context) {c.JSON(http.StatusNotFound, gin.H{"error": "Exception not found"})return}- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, ExceptionDetailResponse{diff --git a/backend/app/controllers/metric_record.controller.go b/backend/app/controllers/metric_record.controller.goindex b9032327..d4752974 100644--- a/backend/app/controllers/metric_record.controller.go+++ b/backend/app/controllers/metric_record.controller.go@@ -32,49 +32,41 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {// requestsrequestsNow, err := repositories.TransactionRepository.CountBetween(c, projectId, oneDayAgo, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}requestsPrev, err := repositories.TransactionRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}// exceptionsexceptionsNow, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, oneDayAgo, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}exceptionsPrev, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}// ram usage last 24h vs previous 24hramNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, oneDayAgo, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}ramPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, twoDaysAgo, oneDayAgo)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}// memory usage last 24h vs previous 24hcpuNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, oneDayAgo, now)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}cpuPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, twoDaysAgo, oneDayAgo)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, HomepageStatsResponse{diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.goindex 00133fa0..ab4ab4cf 100644--- a/backend/app/controllers/project.controller.go+++ b/backend/app/controllers/project.controller.go@@ -71,8 +71,7 @@ func (p projectController) CreateProject(c *gin.Context) {project, err := repositories.ProjectRepository.Create(c, request.Name, request.Framework)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create project"})- return+ panic(err)}// Add to cachediff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 76833520..61a0bfdb 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -34,6 +34,7 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/stats", middleware.UseAppAuth, MetricRecordController.FindHomepageStats)router.GET("/dashboard", middleware.UseAppAuth, DashboardController.GetDashboard)+ router.GET("/dashboard/overview", middleware.UseAppAuth, DashboardController.GetDashboardOverview)router.POST("/transactions", middleware.UseAppAuth, TransactionController.FindAllTransactions)router.POST("/transactions/grouped", middleware.UseAppAuth, TransactionController.FindGroupedByEndpoint)diff --git a/backend/app/controllers/transaction.controller.go b/backend/app/controllers/transaction.controller.goindex 73612060..35b57d7f 100644--- a/backend/app/controllers/transaction.controller.go+++ b/backend/app/controllers/transaction.controller.go@@ -37,8 +37,7 @@ func (e transactionController) FindAllTransactions(c *gin.Context) {transactions, total, err := repositories.TransactionRepository.FindAll(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, PaginatedResponse[models.Transaction]{@@ -61,8 +60,7 @@ func (e transactionController) FindGroupedByEndpoint(c *gin.Context) {stats, total, err := repositories.TransactionRepository.FindGroupedByEndpoint(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, PaginatedResponse[models.EndpointStats]{@@ -97,8 +95,7 @@ func (e transactionController) FindByEndpoint(c *gin.Context) {transactions, total, err := repositories.TransactionRepository.FindByEndpoint(c, request.ProjectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return+ panic(err)}c.JSON(http.StatusOK, PaginatedResponse[models.Transaction]{diff --git a/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.down.sql b/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.down.sqlnew file mode 100644index 00000000..1d157be2--- /dev/null+++ b/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.down.sql@@ -0,0 +1 @@+ALTER TABLE exception_stack_traces DROP COLUMN IF EXISTS scope;diff --git a/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.up.sql b/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.up.sqlnew file mode 100644index 00000000..f627e7da--- /dev/null+++ b/backend/app/migrations/ch/0010_add_scope_to_exception_stack_traces.up.sql@@ -0,0 +1 @@+ALTER TABLE exception_stack_traces ADD COLUMN IF NOT EXISTS scope String DEFAULT '{}';diff --git a/backend/app/migrations/ch/0011_add_scope_to_transactions.down.sql b/backend/app/migrations/ch/0011_add_scope_to_transactions.down.sqlnew file mode 100644index 00000000..6f3110dd--- /dev/null+++ b/backend/app/migrations/ch/0011_add_scope_to_transactions.down.sql@@ -0,0 +1 @@+ALTER TABLE transactions DROP COLUMN IF EXISTS scope;diff --git a/backend/app/migrations/ch/0011_add_scope_to_transactions.up.sql b/backend/app/migrations/ch/0011_add_scope_to_transactions.up.sqlnew file mode 100644index 00000000..407f02ad--- /dev/null+++ b/backend/app/migrations/ch/0011_add_scope_to_transactions.up.sql@@ -0,0 +1 @@+ALTER TABLE transactions ADD COLUMN IF NOT EXISTS scope String DEFAULT '{}';diff --git a/backend/app/models/clientmodels/clientmodels.model.go b/backend/app/models/clientmodels/clientmodels.model.goindex 59fffd12..8929d2c4 100644--- a/backend/app/models/clientmodels/clientmodels.model.go+++ b/backend/app/models/clientmodels/clientmodels.model.go@@ -6,9 +6,10 @@ import ()type ClientExceptionStackTrace struct {- TransactionId *string `json:"transactionId"`- StackTrace string `json:"stackTrace"`- RecordedAt time.Time `json:"recordedAt"`+ TransactionId *string `json:"transactionId"`+ StackTrace string `json:"stackTrace"`+ RecordedAt time.Time `json:"recordedAt"`+ Scope map[string]string `json:"scope"`}func (c *ClientExceptionStackTrace) ToExceptionStackTrace(exceptionHash string) models.ExceptionStackTrace {@@ -17,6 +18,7 @@ func (c *ClientExceptionStackTrace) ToExceptionStackTrace(exceptionHash string)TransactionId: c.TransactionId,StackTrace: c.StackTrace,RecordedAt: c.RecordedAt,+ Scope: c.Scope,}}@@ -35,13 +37,14 @@ func (c *ClientMetricRecord) ToMetricRecord() models.MetricRecord {}type ClientTransaction struct {- Id string `json:"id"`- Endpoint string `json:"endpoint"`- Duration time.Duration `json:"duration"`- RecordedAt time.Time `json:"recordedAt"`- StatusCode int `json:"statusCode"`- BodySize int `json:"bodySize"`- ClientIP string `json:"clientIP"`+ Id string `json:"id"`+ Endpoint string `json:"endpoint"`+ Duration time.Duration `json:"duration"`+ RecordedAt time.Time `json:"recordedAt"`+ StatusCode int `json:"statusCode"`+ BodySize int `json:"bodySize"`+ ClientIP string `json:"clientIP"`+ Scope map[string]string `json:"scope"`}func (c *ClientTransaction) ToTransaction() models.Transaction {@@ -53,6 +56,7 @@ func (c *ClientTransaction) ToTransaction() models.Transaction {StatusCode: int32(c.StatusCode),BodySize: int32(c.BodySize),ClientIP: c.ClientIP,+ Scope: c.Scope,}}diff --git a/backend/app/models/exception_stack_trace.model.go b/backend/app/models/exception_stack_trace.model.goindex 4982d2be..08910f1a 100644--- a/backend/app/models/exception_stack_trace.model.go+++ b/backend/app/models/exception_stack_trace.model.go@@ -3,11 +3,12 @@ package modelsimport "time"type ExceptionStackTrace struct {- ProjectId string `json:"projectId" ch:"project_id"`- TransactionId *string `json:"transactionId" ch:"transaction_id"`- ExceptionHash string `json:"exceptionHash" ch:"exception_hash"`- StackTrace string `json:"stackTrace" ch:"stack_trace"`- RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ ProjectId string `json:"projectId" ch:"project_id"`+ TransactionId *string `json:"transactionId" ch:"transaction_id"`+ ExceptionHash string `json:"exceptionHash" ch:"exception_hash"`+ StackTrace string `json:"stackTrace" ch:"stack_trace"`+ RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ Scope map[string]string `json:"scope" ch:"scope"`}type ExceptionGroup struct {diff --git a/backend/app/models/transaction.model.go b/backend/app/models/transaction.model.goindex 9801c4bd..31ad9c25 100644--- a/backend/app/models/transaction.model.go+++ b/backend/app/models/transaction.model.go@@ -6,12 +6,13 @@ type Transaction struct {Id string `json:"id" ch:"id"`ProjectId string `json:"projectId" ch:"project_id"`// endpoint is the route from the router/does not contain actual params so it's safe to group on it- Endpoint string `json:"endpoint" ch:"endpoint"`- Duration time.Duration `json:"duration" ch:"duration"`- RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`- StatusCode int32 `json:"statusCode" ch:"status_code"`- BodySize int32 `json:"bodySize" ch:"body_size"`- ClientIP string `json:"clientIP" ch:"client_ip"`+ Endpoint string `json:"endpoint" ch:"endpoint"`+ Duration time.Duration `json:"duration" ch:"duration"`+ RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ StatusCode int32 `json:"statusCode" ch:"status_code"`+ BodySize int32 `json:"bodySize" ch:"body_size"`+ ClientIP string `json:"clientIP" ch:"client_ip"`+ Scope map[string]string `json:"scope" ch:"scope"`}type EndpointStats struct {diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.goindex b81755aa..2985fb9b 100644--- a/backend/app/repositories/exception_stack_trace.repository.go+++ b/backend/app/repositories/exception_stack_trace.repository.go@@ -4,6 +4,7 @@ import ("backend/app/chdb""backend/app/models""context"+ "encoding/json""errors""time")@@ -13,12 +14,18 @@ var ErrExceptionNotFound = errors.New("exception not found")type exceptionStackTraceRepository struct{}func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines []models.ExceptionStackTrace) error {- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO exception_stack_traces (project_id, transaction_id, exception_hash, stack_trace, recorded_at)")+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO exception_stack_traces (project_id, transaction_id, exception_hash, stack_trace, recorded_at, scope)")if err != nil {return err}for _, est := range lines {- if err := batch.Append(est.ProjectId, est.TransactionId, est.ExceptionHash, est.StackTrace, est.RecordedAt); err != nil {+ scopeJSON := "{}"+ if est.Scope != nil {+ if scopeBytes, err := json.Marshal(est.Scope); err == nil {+ scopeJSON = string(scopeBytes)+ }+ }+ if err := batch.Append(est.ProjectId, est.TransactionId, est.ExceptionHash, est.StackTrace, est.RecordedAt, scopeJSON); err != nil {return err}}@@ -96,9 +103,9 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectIreturn nil, nil, 0, ErrExceptionNotFound}- // Get individual occurrences with pagination+ // Get individual occurrences with pagination (including scope)rows, err := (*chdb.Conn).Query(ctx,- "SELECT project_id, transaction_id, exception_hash, stack_trace, recorded_at FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",+ "SELECT project_id, transaction_id, exception_hash, stack_trace, recorded_at, scope FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",projectId, exceptionHash, pageSize, offset)if err != nil {return nil, nil, 0, err@@ -108,9 +115,16 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectIvar occurrences []models.ExceptionStackTracefor rows.Next() {var o models.ExceptionStackTrace- if err := rows.Scan(&o.ProjectId, &o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt); err != nil {+ var scopeJSON string+ if err := rows.Scan(&o.ProjectId, &o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt, &scopeJSON); err != nil {return nil, nil, 0, err}+ // Parse scope JSON+ if scopeJSON != "" && scopeJSON != "{}" {+ if err := json.Unmarshal([]byte(scopeJSON), &o.Scope); err != nil {+ o.Scope = nil // If parsing fails, leave scope as nil+ }+ }occurrences = append(occurrences, o)}@@ -121,7 +135,7 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectIfunc (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfHour(recorded_at) as hour,- count() as count+ toFloat64(count()) as countFROM exception_stack_tracesWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY hourdiff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/transaction.repository.goindex c3203d29..3aec7c20 100644--- a/backend/app/repositories/transaction.repository.go+++ b/backend/app/repositories/transaction.repository.go@@ -4,18 +4,25 @@ import ("backend/app/chdb""backend/app/models""context"+ "encoding/json""time")type transactionRepository struct{}func (e *transactionRepository) InsertAsync(ctx context.Context, lines []models.Transaction) error {- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO transactions (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip)")+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO transactions (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope)")if err != nil {return err}for _, t := range lines {- if err := batch.Append(t.Id, t.ProjectId, t.Endpoint, t.Duration, t.RecordedAt, t.StatusCode, t.BodySize, t.ClientIP); err != nil {+ scopeJSON := "{}"+ if t.Scope != nil {+ if scopeBytes, err := json.Marshal(t.Scope); err == nil {+ scopeJSON = string(scopeBytes)+ }+ }+ if err := batch.Append(t.Id, t.ProjectId, t.Endpoint, t.Duration, t.RecordedAt, t.StatusCode, t.BodySize, t.ClientIP, scopeJSON); err != nil {return err}}@@ -48,7 +55,7 @@ func (e *transactionRepository) FindAll(ctx context.Context, projectId string, forderBy = "recorded_at"}- query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"rows, err := (*chdb.Conn).Query(ctx, query, projectId, fromDate, toDate, pageSize, offset)if err != nil {return nil, 0, err@@ -58,9 +65,16 @@ func (e *transactionRepository) FindAll(ctx context.Context, projectId string, fvar transactions []models.Transactionfor rows.Next() {var t models.Transaction- if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {+ var scopeJSON string+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON); err != nil {return nil, 0, err}+ // Parse scope JSON+ if scopeJSON != "" && scopeJSON != "{}" {+ if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {+ t.Scope = nil+ }+ }transactions = append(transactions, t)}@@ -77,16 +91,19 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projeoffset := (page - 1) * pageSize- allowedOrderBy := map[string]bool{- "count": true,- "p50_duration": true,- "p95_duration": true,- "avg_duration": true,- "last_seen": true,+ // Map frontend field names to SQL expressions+ orderByMap := map[string]string{+ "count": "count",+ "p50_duration": "p50_duration",+ "p95_duration": "p95_duration",+ "avg_duration": "avg_duration",+ "last_seen": "last_seen",+ "impact": "count * (p95_duration - p50_duration)",}- if !allowedOrderBy[orderBy] {- orderBy = "count"+ orderExpr, ok := orderByMap[orderBy]+ if !ok {+ orderExpr = "impact" // Default to impact}query := `SELECT@@ -99,7 +116,7 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projeFROM transactionsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY endpoint- ORDER BY ` + orderBy + ` DESC+ ORDER BY ` + orderExpr + ` DESCLIMIT ? OFFSET ?`rows, err := (*chdb.Conn).Query(ctx, query, projectId, fromDate, toDate, pageSize, offset)@@ -144,7 +161,7 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId storderBy = "recorded_at"}- query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope FROM transactions WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"rows, err := (*chdb.Conn).Query(ctx, query, projectId, endpoint, fromDate, toDate, pageSize, offset)if err != nil {return nil, 0, err@@ -154,9 +171,16 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId stvar transactions []models.Transactionfor rows.Next() {var t models.Transaction- if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {+ var scopeJSON string+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON); err != nil {return nil, 0, err}+ // Parse scope JSON+ if scopeJSON != "" && scopeJSON != "{}" {+ if err := json.Unmarshal([]byte(scopeJSON), &t.Scope); err != nil {+ t.Scope = nil+ }+ }transactions = append(transactions, t)}@@ -167,7 +191,7 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId stfunc (e *transactionRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfHour(recorded_at) as hour,- count() as count+ toFloat64(count()) as countFROM transactionsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY hour@@ -247,4 +271,42 @@ func (e *transactionRepository) ErrorRateByHour(ctx context.Context, projectId sreturn points, nil}+// FindWorstEndpoints returns endpoints ordered by impact score (count * variance)+// Higher call volume + larger variance = higher impact+func (e *transactionRepository) FindWorstEndpoints(ctx context.Context, projectId string, start, end time.Time, limit int) ([]models.EndpointStats, error) {+ query := `SELECT+ endpoint,+ count() as count,+ quantile(0.5)(duration) as p50_duration,+ quantile(0.95)(duration) as p95_duration,+ avg(duration) as avg_duration,+ max(recorded_at) as last_seen+ FROM transactions+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY endpoint+ ORDER BY count * (p95_duration - p50_duration) DESC+ LIMIT ?`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end, limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var stats []models.EndpointStats+ for rows.Next() {+ var s models.EndpointStats+ var p50, p95, avg float64+ if err := rows.Scan(&s.Endpoint, &s.Count, &p50, &p95, &avg, &s.LastSeen); err != nil {+ return nil, err+ }+ s.P50Duration = time.Duration(p50)+ s.P95Duration = time.Duration(p95)+ s.AvgDuration = time.Duration(avg)+ stats = append(stats, s)+ }++ return stats, nil+}+var TransactionRepository = transactionRepository{}diff --git a/clients/go-client/devtesting/devtesting.go b/clients/go-client/devtesting/devtesting.goindex c3acc28b..f958e944 100644--- a/clients/go-client/devtesting/devtesting.go+++ b/clients/go-client/devtesting/devtesting.go@@ -1,6 +1,9 @@package mainimport (+ "errors"+ "math/rand/v2"+ "time""traceway"tracewaygin "traceway/traceway_gin"@@ -22,9 +25,21 @@ func testGin() {))router.GET("/test-exception", func(ctx *gin.Context) {+ time.Sleep(time.Duration(rand.IntN(2000)) * time.Millisecond)panic("Cool")})+ router.GET("/test-self-report-scope", func(ctx *gin.Context) {+ traceway.CaptureExceptionWithScope(errors.New("Test"), map[string]string{"Cool": "Pretty cool"}, nil)+ })++ router.GET("/test-self-report-context", func(ctx *gin.Context) {+ scope := traceway.GetScopeFromContext(ctx)+ scope.SetTag("Interesting", "Pretty Cool")++ traceway.CaptureExceptionWithContext(ctx, errors.New("Test2"))+ })+router.GET("/test-ok", func(ctx *gin.Context) {ctx.JSON(200, gin.H{"status": "ok",diff --git a/clients/go-client/traceway.go b/clients/go-client/traceway.goindex 34d5bfc1..27893a0b 100644--- a/clients/go-client/traceway.go+++ b/clients/go-client/traceway.go@@ -3,10 +3,12 @@ package tracewayimport ("bytes""compress/gzip"+ "context""encoding/json""fmt""log""net/http"+ "os""reflect""runtime""runtime/debug"@@ -19,6 +21,138 @@ import ("github.com/gin-gonic/gin")+// Context key for scope+type tracewayContextKey string++const CtxScopeKey tracewayContextKey = "TRACEWAY_SCOPE"+const CtxTransactionIdKey tracewayContextKey = "TRACEWAY_TRANSACTION_ID"++// Scope holds contextual data for exceptions and transactions+type Scope struct {+ tags map[string]string+ mu sync.RWMutex+}++// NewScope creates a new empty scope+func NewScope() *Scope {+ return &Scope{tags: make(map[string]string)}+}++// SetTag sets a tag on the scope+func (s *Scope) SetTag(key, value string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.tags[key] = value+}++// GetTag gets a tag from the scope+func (s *Scope) GetTag(key string) (string, bool) {+ s.mu.RLock()+ defer s.mu.RUnlock()+ val, ok := s.tags[key]+ return val, ok+}++// GetTags returns a copy of all tags+func (s *Scope) GetTags() map[string]string {+ s.mu.RLock()+ defer s.mu.RUnlock()+ result := make(map[string]string, len(s.tags))+ for k, v := range s.tags {+ result[k] = v+ }+ return result+}++// Clone creates a deep copy of the scope+func (s *Scope) Clone() *Scope {+ return &Scope{tags: s.GetTags()}+}++// Clear removes all tags from the scope+func (s *Scope) Clear() {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.tags = make(map[string]string)+}++// Global default scope+var defaultScope = NewScope()++// ConfigureScope modifies the global default scope (persistent changes)+func ConfigureScope(fn func(*Scope)) {+ fn(defaultScope)+}++// WithScope creates an isolated scope clone for the callback and returns a new context+func WithScope(ctx context.Context, fn func(*Scope)) context.Context {+ scope := GetScopeFromContext(ctx).Clone()+ fn(scope)+ return context.WithValue(ctx, CtxScopeKey, scope)+}++// GetScopeFromContext retrieves scope from context, falls back to default clone+func GetScopeFromContext(ctx context.Context) *Scope {+ if ctx == nil {+ return defaultScope.Clone()+ }+ if scope, ok := ctx.Value(string(CtxScopeKey)).(*Scope); ok && scope != nil {+ return scope+ }++ return defaultScope.Clone()+}++// GetScopeFromGin is a convenience helper for Gin handlers+func GetScopeFromGin(c *gin.Context) *Scope {+ if scope, ok := c.Get(string(CtxScopeKey)); ok {+ if s, ok := scope.(*Scope); ok {+ return s+ }+ }+ return GetScopeFromContext(c.Request.Context())+}++func GetTransactionIdFromContext(ctx context.Context) *string {+ if val, ok := ctx.Value(string(CtxTransactionIdKey)).(*string); ok {+ return val+ }+ return nil+}++// GetHostname returns the hostname, cached for efficiency+var cachedHostname string+var hostnameOnce sync.Once++func getHostname() string {+ hostnameOnce.Do(func() {+ hostname, err := os.Hostname()+ if err != nil {+ cachedHostname = "unknown"+ } else {+ cachedHostname = hostname+ }+ })+ return cachedHostname+}++// GetEnvironment returns the environment from TRACEWAY_ENV or GO_ENV+var cachedEnvironment string+var envOnce sync.Once++func getEnvironment() string {+ envOnce.Do(func() {+ cachedEnvironment = os.Getenv("TRACEWAY_ENV")+ if cachedEnvironment == "" {+ cachedEnvironment = os.Getenv("GO_ENV")+ }+ if cachedEnvironment == "" {+ cachedEnvironment = "development"+ }+ })+ return cachedEnvironment+}+func CaptureStack(skip int) []runtime.Frame {const maxDepth = 64pcs := make([]uintptr, maxDepth)@@ -78,9 +212,10 @@ func FormatErrorWithStack(err error, frames []runtime.Frame) string {}type ExceptionStackTrace struct {- TransactionId *string `json:"transactionId"`- StackTrace string `json:"stackTrace"`- RecordedAt time.Time `json:"recordedAt"`+ TransactionId *string `json:"transactionId"`+ StackTrace string `json:"stackTrace"`+ RecordedAt time.Time `json:"recordedAt"`+ Scope map[string]string `json:"scope,omitempty"`}type MetricRecord struct {@@ -90,13 +225,14 @@ type MetricRecord struct {}type Transaction struct {- Id string `json:"id"`- Endpoint string `json:"endpoint"`- Duration time.Duration `json:"duration"`- RecordedAt time.Time `json:"recordedAt"`- StatusCode int `json:"statusCode"`- BodySize int `json:"bodySize"`- ClientIP string `json:"clientIP"`+ Id string `json:"id"`+ Endpoint string `json:"endpoint"`+ Duration time.Duration `json:"duration"`+ RecordedAt time.Time `json:"recordedAt"`+ StatusCode int `json:"statusCode"`+ BodySize int `json:"bodySize"`+ ClientIP string `json:"clientIP"`+ Scope map[string]string `json:"scope,omitempty"`}type CollectionFrame struct {@@ -458,6 +594,7 @@ func CaptureMetric(name string, value float64) {}}+// CaptureTransaction captures a transaction without scope (backward compatible)func CaptureTransaction(transactionId string,endpoint string,@@ -465,41 +602,78 @@ func CaptureTransaction(startedAt time.Time,statusCode, bodySize int,clientIP string,+) {+ CaptureTransactionWithScope(transactionId, endpoint, d, startedAt, statusCode, bodySize, clientIP, nil)+}++// CaptureTransactionWithScope captures a transaction with scope+func CaptureTransactionWithScope(+ transactionId string,+ endpoint string,+ d time.Duration,+ startedAt time.Time,+ statusCode, bodySize int,+ clientIP string,+ scope map[string]string,) {collectionFrameStore.messageQueue <- CollectionFrameMessage{msgType: CollectionFrameMessageTypeTransaction,transaction: &Transaction{- Id: transactionId, // for regular recover we don't need a transaction+ Id: transactionId,Endpoint: endpoint,Duration: d,RecordedAt: startedAt,StatusCode: statusCode,BodySize: bodySize,ClientIP: clientIP,+ Scope: scope,},}}++// CaptureTransactionException captures an exception linked to a transaction (backward compatible)func CaptureTransactionException(transactionId string, stacktrace string) {+ CaptureTransactionExceptionWithScope(transactionId, stacktrace, nil)+}++// CaptureTransactionExceptionWithScope captures an exception linked to a transaction with scope+func CaptureTransactionExceptionWithScope(transactionId string, stacktrace string, scope map[string]string) {collectionFrameStore.messageQueue <- CollectionFrameMessage{msgType: CollectionFrameMessageTypeException,exceptionStackTrace: &ExceptionStackTrace{TransactionId: &transactionId,StackTrace: stacktrace,RecordedAt: time.Now(),+ Scope: scope,},}}++// CaptureException captures an exception without context (backward compatible)func CaptureException(err error) {+ CaptureExceptionWithScope(err, nil, nil)+}++// CaptureExceptionWithScope captures an exception with scope+func CaptureExceptionWithScope(err error, scope map[string]string, transactionId *string) {collectionFrameStore.messageQueue <- CollectionFrameMessage{msgType: CollectionFrameMessageTypeException,exceptionStackTrace: &ExceptionStackTrace{- TransactionId: nil, // for regular recover we don't need a transaction+ TransactionId: transactionId,StackTrace: FormatErrorWithStack(err, CaptureStack(2)),RecordedAt: time.Now(),+ Scope: scope,},}}+// CaptureExceptionWithContext captures an exception extracting scope from context+func CaptureExceptionWithContext(ctx context.Context, err error) {+ scope := GetScopeFromContext(ctx)+ CaptureExceptionWithScope(err, scope.GetTags(), GetTransactionIdFromContext(ctx))+}++// Recover recovers from panic and captures it (backward compatible, no scope)func Recover() {r := recover()@@ -507,9 +681,27 @@ func Recover() {collectionFrameStore.messageQueue <- CollectionFrameMessage{msgType: CollectionFrameMessageTypeException,exceptionStackTrace: &ExceptionStackTrace{- TransactionId: nil, // for regular recover we don't need a transaction+ TransactionId: nil,+ StackTrace: FormatRWithStack(r, CaptureStack(2)),+ RecordedAt: time.Now(),+ },+ }+ }+}++// RecoverWithContext recovers from panic and captures it with scope from context+func RecoverWithContext(ctx context.Context) {+ r := recover()++ if r != nil {+ scope := GetScopeFromContext(ctx)+ collectionFrameStore.messageQueue <- CollectionFrameMessage{+ msgType: CollectionFrameMessageTypeException,+ exceptionStackTrace: &ExceptionStackTrace{+ TransactionId: nil,StackTrace: FormatRWithStack(r, CaptureStack(2)),RecordedAt: time.Now(),+ Scope: scope.GetTags(),},}}diff --git a/clients/go-client/traceway_gin/traceway_gin.go b/clients/go-client/traceway_gin/traceway_gin.goindex 4080d27d..d9ceebbf 100644--- a/clients/go-client/traceway_gin/traceway_gin.go+++ b/clients/go-client/traceway_gin/traceway_gin.go@@ -1,6 +1,10 @@package tracewayginimport (+ "context"+ "net/http"+ "os"+ "sync""time""traceway"@@ -8,11 +12,39 @@ import ("github.com/google/uuid")+// Cached values for default scope tags+var (+ cachedHostname string+ cachedEnvironment string+ initOnce sync.Once+)++func initCachedValues() {+ initOnce.Do(func() {+ hostname, err := os.Hostname()+ if err != nil {+ cachedHostname = "unknown"+ } else {+ cachedHostname = hostname+ }++ cachedEnvironment = os.Getenv("TRACEWAY_ENV")+ if cachedEnvironment == "" {+ cachedEnvironment = os.Getenv("GO_ENV")+ }+ if cachedEnvironment == "" {+ cachedEnvironment = "development"+ }+ })+}+func wrapAndExecute(c *gin.Context) (s *string) {defer func() {if r := recover(); r != nil {m := traceway.FormatRWithStack(r, traceway.CaptureStack(2))s = &m+ // we don't propagate just report+ c.AbortWithStatus(http.StatusInternalServerError)}}()c.Next()@@ -21,16 +53,27 @@ func wrapAndExecute(c *gin.Context) (s *string) {func New(app, connectionString string, options ...func(*traceway.TracewayOptions)) gin.HandlerFunc {traceway.Init(app, connectionString, options...)+ initCachedValues()return func(c *gin.Context) {start := time.Now()- path := c.Request.URL.Path- query := c.Request.URL.RawQuerymethod := c.Request.MethodclientIP := c.ClientIP()transactionId := uuid.NewString()+ // Create request-scoped scope with defaults+ scope := traceway.NewScope()+ scope.SetTag("server_name", cachedHostname)+ scope.SetTag("user_agent", c.Request.UserAgent())+ scope.SetTag("environment", cachedEnvironment)++ // Store scope in both gin.Context and request context+ ctx := context.WithValue(c.Request.Context(), string(traceway.CtxScopeKey), scope)+ c.Request = c.Request.WithContext(ctx)+ c.Set(string(traceway.CtxScopeKey), scope)+ c.Set(string(traceway.CtxTransactionIdKey), &transactionId)+stackTraceFormatted := wrapAndExecute(c)duration := time.Since(start)@@ -38,18 +81,26 @@ func New(app, connectionString string, options ...func(*traceway.TracewayOptionsstatusCode := c.Writer.Status()bodySize := c.Writer.Size()- if query != "" {- path = path + "?" + query+ if bodySize < 0 {+ bodySize = 0+ }++ // Use the registered route pattern (e.g., /users/:id) instead of actual path+ routePath := c.FullPath()+ if routePath == "" {+ // Fallback to actual path for unmatched routes+ routePath = c.Request.URL.Path}- transactionEndpoint := method + " " + path+ transactionEndpoint := method + " " + routePathdefer recover()- traceway.CaptureTransaction(transactionId, transactionEndpoint, duration, start, statusCode, bodySize, clientIP)+ // Capture transaction with scope+ traceway.CaptureTransactionWithScope(transactionId, transactionEndpoint, duration, start, statusCode, bodySize, clientIP, scope.GetTags())if stackTraceFormatted != nil {- traceway.CaptureTransactionException(transactionId, *stackTraceFormatted)+ traceway.CaptureTransactionExceptionWithScope(transactionId, *stackTraceFormatted, scope.GetTags())}}}diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex c3085a19..9c6660cd 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -1,6 +1,6 @@<script lang="ts">import * as Sidebar from "$lib/components/ui/sidebar";- import { List, Bug, Link2 } from "@lucide/svelte";+ import { List, Bug, Link2, BarChart3 } from "@lucide/svelte";import { themeState } from '$lib/state/theme.svelte';import { LayoutDashboard } from "@lucide/svelte";import { page } from '$app/state';@@ -10,6 +10,7 @@{Icon: LayoutDashboard, href: "/", title: "Dashboard"},{Icon: Bug, href: "/issues", title: "Issues"},{Icon: List, href: "/transactions", title: "Transactions"},+ {Icon: BarChart3, href: "/metrics", title: "Metrics"},{Icon: Link2, href: "/connection", title: "Connection"},]diff --git a/frontend/src/lib/components/scope-display.svelte b/frontend/src/lib/components/scope-display.sveltenew file mode 100644index 00000000..e8f9b11c--- /dev/null+++ b/frontend/src/lib/components/scope-display.svelte@@ -0,0 +1,52 @@+<script lang="ts">+ import * as Popover from "$lib/components/ui/popover";++ interface Props {+ scope: Record<string, string> | null | undefined;+ maxInlineTags?: number;+ }++ let { scope, maxInlineTags = 3 }: Props = $props();++ const entries = $derived(+ Object.entries(scope || {}).sort((a, b) => a[0].localeCompare(b[0]))+ );+ const hasMore = $derived(entries.length > maxInlineTags);+ const visibleEntries = $derived(entries.slice(0, maxInlineTags));+ const hiddenCount = $derived(entries.length - maxInlineTags);+</script>++{#if entries.length > 0}+ <div class="flex flex-wrap gap-1 items-center">+ {#each visibleEntries as [key, value]}+ <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-muted text-muted-foreground">+ <span class="font-semibold">{key}:</span>+ <span class="ml-1 font-mono truncate max-w-[120px]" title={value}>{value}</span>+ </span>+ {/each}+ {#if hasMore}+ <Popover.Root>+ <Popover.Trigger>+ <span class="text-xs text-muted-foreground hover:text-foreground cursor-pointer underline underline-offset-2">+ +{hiddenCount} more+ </span>+ </Popover.Trigger>+ <Popover.Content class="w-80">+ <div class="space-y-2">+ <h4 class="font-medium text-sm">All Context Tags</h4>+ <div class="grid gap-2">+ {#each entries as [key, value]}+ <div class="flex items-start gap-2 text-sm">+ <span class="font-medium text-muted-foreground shrink-0">{key}:</span>+ <span class="font-mono break-all">{value}</span>+ </div>+ {/each}+ </div>+ </div>+ </Popover.Content>+ </Popover.Root>+ {/if}+ </div>+{:else}+ <span class="text-xs text-muted-foreground">-</span>+{/if}diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex 7ba90c1d..37f2750c 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -1,16 +1,37 @@<script lang="ts">import { onMount } from 'svelte';- import { Button } from '$lib/components/ui/button';+ import { goto } from '$app/navigation';import { Skeleton } from '$lib/components/ui/skeleton';- import { RefreshCw } from 'lucide-svelte';- import MetricCard from '$lib/components/dashboard/metric-card.svelte';- import type { DashboardData, DashboardMetric } from '$lib/types/dashboard';- import { Card, CardContent } from '$lib/components/ui/card';+ import * as Table from '$lib/components/ui/table';+ import * as Tooltip from '$lib/components/ui/tooltip';+ import { ArrowRight, CircleHelp, Gauge, Bug } from 'lucide-svelte';import { api } from '$lib/api';import { ErrorDisplay } from '$lib/components/ui/error-display';import { projectsState } from '$lib/state/projects.svelte';- let dashboardData = $state<DashboardData | null>(null);+ type ExceptionGroup = {+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;+ };++ type EndpointStats = {+ endpoint: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ avgDuration: number;+ lastSeen: string;+ };++ type DashboardOverview = {+ recentIssues: ExceptionGroup[];+ worstEndpoints: EndpointStats[];+ };++ let data = $state<DashboardOverview | null>(null);let loading = $state(true);let error = $state('');let errorStatus = $state<number>(0);@@ -21,27 +42,10 @@errorStatus = 0;try {- const response = await api.get('/dashboard', { projectId: projectsState.currentProjectId ?? undefined });-- // Transform the API response to match the DashboardData type- // Convert timestamp strings to Date objects- const metrics: DashboardMetric[] = response.metrics.map((m: any) => ({- id: m.id,- name: m.name,- value: m.value,- unit: m.unit,- trend: m.trend.map((t: any) => ({- timestamp: new Date(t.timestamp),- value: t.value- })),- change24h: m.change24h,- status: m.status- }));-- dashboardData = {- metrics,- lastUpdated: new Date(response.lastUpdated)- };+ const response = await api.get('/dashboard/overview', {+ projectId: projectsState.currentProjectId ?? undefined+ });+ data = response;} catch (e: any) {errorStatus = e.status || 0;error = e.message || 'Failed to load dashboard data';@@ -55,33 +59,68 @@loadDashboard();});- const lastUpdatedFormatted = $derived(- dashboardData?.lastUpdated- ? dashboardData.lastUpdated.toLocaleString('en-US', {- hour: '2-digit',- minute: '2-digit',- second: '2-digit',- hour12: false- })- : ''- );-</script>+ function formatRelativeTime(dateStr: string): string {+ const date = new Date(dateStr);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);-<div class="space-y-4">- <!-- Header -->- <div class="flex items-center justify-between">- <div>- <h2 class="text-3xl font-bold tracking-tight">System Metrics</h2>- {#if dashboardData}- <p class="mt-1 text-sm text-muted-foreground">Last updated: {lastUpdatedFormatted}</p>- {/if}- </div>- <Button variant="outline" size="sm" onclick={loadDashboard} disabled={loading}>- <RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />- Refresh- </Button>- </div>+ if (diffMins < 1) return 'just now';+ if (diffMins < 60) return `${diffMins}m`;+ if (diffHours < 24) return `${diffHours}h`;+ return `${diffDays}d`;+ }++ function formatDuration(nanoseconds: number): string {+ const ms = nanoseconds / 1_000_000;+ if (ms < 1) {+ return `${(nanoseconds / 1000).toFixed(0)}µs`;+ } else if (ms < 1000) {+ return `${ms.toFixed(0)}ms`;+ } else {+ return `${(ms / 1000).toFixed(1)}s`;+ }+ }++ // 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+ 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' };+ }+ }+ function truncateStackTrace(stackTrace: string): string {+ const firstLine = stackTrace.split('\n')[0];+ if (firstLine.length > 70) {+ return firstLine.slice(0, 70) + '...';+ }+ return firstLine;+ }+</script>++<div class="space-y-6">{#if error && !loading}<ErrorDisplaystatus={errorStatus === 404 ? 404 : errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}@@ -91,28 +130,240 @@/>{/if}- <!-- Metrics Grid -->{#if !error}- <div class="grid grid-cols-1 gap-4 md:grid-cols-3">- {#if loading}- {#each Array(6) as _}- <Card>- <CardContent class="flex gap-3 flex-col">- <div class="flex items-center justify-between">- <Skeleton class="h-4 w-24" />- <Skeleton class="h-2 w-2 rounded-full" />- </div>- <Skeleton class="h-8 w-32" />- <Skeleton class="h-16 w-full" />- <Skeleton class="h-3 w-28" />- </CardContent>- </Card>- {/each}- {:else if dashboardData}- {#each dashboardData.metrics as metric (metric.id)}- <MetricCard {metric} />- {/each}- {/if}+ <div class="space-y-8">+ <!-- Endpoints -->+ <div>+ <div class="flex items-center gap-3 mb-4">+ <div class="flex h-8 w-8 items-center justify-center rounded-md bg-chart-1/10">+ <Gauge class="h-5 w-5 text-chart-1" />+ </div>+ <h2 class="text-2xl font-bold tracking-tight">Endpoints</h2>+ </div>+ <div class="rounded-md border overflow-hidden">+ <Table.Root>+ <Table.Header>+ <Table.Row class="hover:bg-transparent">+ <Table.Head class="h-10 text-sm">+ <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="h-10 w-[70px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ Calls+ <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>+ </span>+ </Table.Head>+ <Table.Head class="h-10 w-[80px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ Typical+ <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>+ </span>+ </Table.Head>+ <Table.Head class="h-10 w-[70px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ Slow+ <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%</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head class="h-10 w-[80px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ Impact+ <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 × variance</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if loading}+ {#each Array(4) as _}+ <Table.Row>+ <Table.Cell class="py-3"><Skeleton class="h-4 w-[150px]" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[35px] ml-auto" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[45px] ml-auto" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[45px] ml-auto" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[45px] ml-auto" /></Table.Cell>+ </Table.Row>+ {/each}+ {:else if data?.worstEndpoints && data.worstEndpoints.length > 0}+ {#each data.worstEndpoints as endpoint}+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={() => goto(`/transactions/${encodeURIComponent(endpoint.endpoint)}`)}+ >+ <Table.Cell class="py-3 font-mono text-sm truncate max-w-[300px]" title={endpoint.endpoint}>+ {endpoint.endpoint}+ </Table.Cell>+ <Table.Cell class="py-3 text-right tabular-nums">+ {endpoint.count.toLocaleString()}+ </Table.Cell>+ <Table.Cell class="py-3 text-right font-mono text-sm tabular-nums">+ {formatDuration(endpoint.p50Duration)}+ </Table.Cell>+ <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>+ </Table.Row>+ {/each}+ <Table.Row+ class="cursor-pointer bg-muted/50 hover:bg-muted"+ onclick={() => goto('/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" />+ </Table.Cell>+ </Table.Row>+ {:else}+ <Table.Row>+ <Table.Cell colspan={5} class="h-24 text-center text-muted-foreground">+ No transaction data received yet+ </Table.Cell>+ </Table.Row>+ {/if}+ </Table.Body>+ </Table.Root>+ </div>+ </div>++ <!-- Issues Section -->+ <div>+ <div class="flex items-center gap-3 mb-4">+ <div class="flex h-8 w-8 items-center justify-center rounded-md bg-destructive/10">+ <Bug class="h-5 w-5 text-destructive" />+ </div>+ <h2 class="text-2xl font-bold tracking-tight">Issues</h2>+ </div>+ <div class="rounded-md border overflow-hidden">+ <Table.Root>+ <Table.Header>+ <Table.Row class="hover:bg-transparent">+ <Table.Head class="h-10 text-sm">+ <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="h-10 w-[70px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ Count+ <Tooltip.Root>+ <Tooltip.Trigger>+ <CircleHelp class="h-3.5 w-3.5 text-muted-foreground/60" />+ </Tooltip.Trigger>+ <Tooltip.Content>+ <p class="text-xs">Number of times this issue occurred</p>+ </Tooltip.Content>+ </Tooltip.Root>+ </span>+ </Table.Head>+ <Table.Head class="h-10 w-[70px] text-right text-sm">+ <span class="flex items-center justify-end gap-1.5">+ When+ <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>+ {#if loading}+ {#each Array(4) as _}+ <Table.Row>+ <Table.Cell class="py-3"><Skeleton class="h-4 w-[200px]" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[30px] ml-auto" /></Table.Cell>+ <Table.Cell class="py-3 text-right"><Skeleton class="h-4 w-[35px] ml-auto" /></Table.Cell>+ </Table.Row>+ {/each}+ {:else if data?.recentIssues && data.recentIssues.length > 0}+ {#each data.recentIssues as issue}+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={() => goto(`/issues/${issue.exceptionHash}`)}+ >+ <Table.Cell class="py-3 font-mono text-sm" title={issue.stackTrace}>+ {truncateStackTrace(issue.stackTrace)}+ </Table.Cell>+ <Table.Cell class="py-3 text-right font-medium tabular-nums">+ {issue.count}+ </Table.Cell>+ <Table.Cell class="py-3 text-right text-muted-foreground text-sm tabular-nums">+ {formatRelativeTime(issue.lastSeen)}+ </Table.Cell>+ </Table.Row>+ {/each}+ <Table.Row+ class="cursor-pointer bg-muted/50 hover:bg-muted"+ onclick={() => goto('/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" />+ </Table.Cell>+ </Table.Row>+ {:else}+ <Table.Row>+ <Table.Cell colspan={3} class="h-24 text-center text-muted-foreground">+ No issues in the last 24 hours+ </Table.Cell>+ </Table.Row>+ {/if}+ </Table.Body>+ </Table.Root>+ </div>+ </div></div>{/if}</div>diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelteindex 00acc2dd..01aa64d4 100644--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte@@ -9,6 +9,7 @@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";type ExceptionGroup = {exceptionHash: string;@@ -23,6 +24,7 @@exceptionHash: string;stackTrace: string;recordedAt: string;+ scope: Record<string, string> | null;};let group = $state<ExceptionGroup | null>(null);@@ -30,12 +32,11 @@let loading = $state(true);let error = $state('');let notFound = $state(false);-- // Pagination- let currentPage = $state(1);- let pageSize = $state(20);let total = $state(0);- let totalPages = $state(0);++ // Get scope from the most recent occurrence for display+ const latestScope = $derived(occurrences[0]?.scope);+ const hasMoreOccurrences = $derived(total > 10);async function loadData() {loading = true;@@ -46,15 +47,14 @@const exceptionHash = page.params.exceptionHash;const response = await api.post(`/exception-stack-traces/${exceptionHash}`, {pagination: {- page: currentPage,- pageSize: pageSize+ page: 1,+ pageSize: 10}}, { projectId: projectsState.currentProjectId ?? undefined });group = response.group;occurrences = response.occurrences || [];total = response.pagination.total;- totalPages = response.pagination.totalPages;} catch (e: any) {console.error(e);if (e.status === 404) {@@ -67,11 +67,18 @@}}- function handlePageChange(newPage: number) {- if (newPage >= 1 && newPage <= totalPages) {- currentPage = newPage;- loadData();- }+ function formatRelativeTime(dateStr: string): string {+ const date = new Date(dateStr);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);++ if (diffMins < 1) return 'just now';+ if (diffMins < 60) return `${diffMins}m ago`;+ if (diffHours < 24) return `${diffHours}h ago`;+ return `${diffDays}d ago`;}onMount(() => {@@ -139,6 +146,26 @@</Card.Content></Card.Root>+ <!-- Context Card -->+ {#if latestScope && Object.keys(latestScope).length > 0}+ <Card.Root>+ <Card.Header>+ <Card.Title>Context</Card.Title>+ <Card.Description>Additional context captured with this exception (from most recent occurrence)</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">+ {#each Object.entries(latestScope).sort((a, b) => a[0].localeCompare(b[0])) as [key, value]}+ <div class="flex flex-col gap-1 p-3 rounded-md bg-muted">+ <span class="text-xs font-medium text-muted-foreground">{key}</span>+ <span class="text-sm font-mono break-all">{value}</span>+ </div>+ {/each}+ </div>+ </Card.Content>+ </Card.Root>+ {/if}+<!-- Occurrences Table --><Card.Root><Card.Header>@@ -170,35 +197,20 @@</Table.Cell></Table.Row>{/each}+ {#if hasMoreOccurrences}+ <Table.Row+ class="cursor-pointer bg-muted/50 hover:bg-muted"+ onclick={() => goto(`/issues/${page.params.exceptionHash}/events`)}+ >+ <Table.Cell colspan={2} 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>+ {/if}{/if}</Table.Body></Table.Root></div>-- <!-- Pagination -->- {#if totalPages > 1}- <div class="flex items-center justify-end space-x-2 py-4">- <div class="text-sm text-muted-foreground">- Page {currentPage} of {totalPages}- </div>- <Button- variant="outline"- size="sm"- onclick={() => handlePageChange(currentPage - 1)}- disabled={currentPage <= 1}- >- Previous- </Button>- <Button- variant="outline"- size="sm"- onclick={() => handlePageChange(currentPage + 1)}- disabled={currentPage >= totalPages}- >- Next- </Button>- </div>- {/if}</Card.Content></Card.Root>{/if}diff --git a/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/events/+page.sveltenew file mode 100644index 00000000..db085994--- /dev/null+++ b/frontend/src/routes/issues/[exceptionHash]/events/+page.svelte@@ -0,0 +1,258 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { page } from '$app/state';+ 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 * as Table from "$lib/components/ui/table";+ import * as Select from "$lib/components/ui/select";+ import { Skeleton } from "$lib/components/ui/skeleton";+ import { ErrorDisplay } from "$lib/components/ui/error-display";+ import { projectsState } from '$lib/state/projects.svelte';++ type ExceptionGroup = {+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;+ };++ type ExceptionOccurrence = {+ transactionId: string | null;+ exceptionHash: string;+ stackTrace: string;+ recordedAt: string;+ };++ let group = $state<ExceptionGroup | null>(null);+ let occurrences = $state<ExceptionOccurrence[]>([]);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);++ // Pagination state+ let currentPage = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ // Page size options+ const pageSizeOptions = [+ { value: "10", label: "10" },+ { value: "20", label: "20" },+ { value: "50", label: "50" },+ { value: "100", label: "100" }+ ];++ const pageSizeLabel = $derived(pageSizeOptions.find(o => o.value === pageSize.toString())?.label ?? pageSize.toString());++ async function loadData() {+ loading = true;+ error = '';+ notFound = false;++ try {+ const exceptionHash = page.params.exceptionHash;+ const response = await api.post(`/exception-stack-traces/${exceptionHash}`, {+ pagination: {+ page: currentPage,+ pageSize: pageSize+ }+ }, { projectId: projectsState.currentProjectId ?? undefined });++ group = response.group;+ occurrences = response.occurrences || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ if (e.status === 404) {+ notFound = true;+ } else {+ error = e.message || 'Failed to load exception details';+ }+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ currentPage = newPage;+ loadData();+ }+ }++ function handlePageSizeChange(newPageSize: string) {+ pageSize = parseInt(newPageSize);+ currentPage = 1;+ loadData();+ }++ function truncateStackTrace(stackTrace: string): string {+ const firstLine = stackTrace.split('\n')[0];+ if (firstLine.length > 80) {+ return firstLine.slice(0, 80) + '...';+ }+ return firstLine;+ }++ onMount(() => {+ loadData();+ });+</script>++<div class="space-y-6">+ <!-- Header -->+ <div class="flex items-center gap-4">+ <Button variant="outline" size="sm" onclick={() => goto(`/issues/${page.params.exceptionHash}`)}>+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2">+ <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>+ </svg>+ Back to Issue+ </Button>+ </div>++ {#if loading && !group}+ <!-- Loading skeleton -->+ <Card.Root>+ <Card.Header>+ <Skeleton class="h-6 w-48" />+ </Card.Header>+ <Card.Content>+ <Skeleton class="h-4 w-full mb-2" />+ <Skeleton class="h-4 w-3/4" />+ </Card.Content>+ </Card.Root>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Exception Not Found"+ description="The exception you're looking for doesn't exist or may have been removed."+ backHref="/issues"+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ identifier={page.params.exceptionHash}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Something Went Wrong"+ description={error}+ backHref="/issues"+ backLabel="Back to Issues"+ onRetry={() => loadData()}+ />+ {:else if group}+ <!-- Issue Summary -->+ <Card.Root>+ <Card.Header class="pb-3">+ <Card.Title class="text-lg">All Events</Card.Title>+ <Card.Description class="font-mono text-sm">+ {truncateStackTrace(group.stackTrace)}+ </Card.Description>+ </Card.Header>+ </Card.Root>++ <!-- Events Table -->+ <div class="rounded-md border overflow-hidden">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <Table.Head>Recorded At</Table.Head>+ <Table.Head>Transaction ID</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#if loading}+ {#each Array(5) as _}+ <Table.Row>+ <Table.Cell><Skeleton class="h-4 w-[150px]" /></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">+ 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}`)}+ >+ <Table.Cell>{new Date(occurrence.recordedAt).toLocaleString()}</Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {occurrence.transactionId || '-'}+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>++ <!-- Pagination Footer -->+ <div class="flex items-center justify-between px-2">+ <div class="flex-1 text-sm text-muted-foreground">+ Showing {occurrences.length} of {total} events+ </div>+ <div class="flex items-center space-x-6 lg:space-x-8">+ <div class="flex items-center space-x-2">+ <p class="text-sm font-medium">Rows per page</p>+ <Select.Root+ type="single"+ value={pageSize.toString()}+ onValueChange={(v) => {+ if (v) {+ handlePageSizeChange(v);+ }+ }}+ >+ <Select.Trigger class="h-8 w-[70px]">+ {pageSizeLabel}+ </Select.Trigger>+ <Select.Content side="top">+ {#each pageSizeOptions as option}+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <div class="flex w-[100px] items-center justify-center text-sm font-medium">+ Page {currentPage} of {totalPages || 1}+ </div>+ <div class="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(currentPage - 1)}+ disabled={currentPage <= 1 || loading}+ >+ <span class="sr-only">Go to previous page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="lucide lucide-chevron-left h-4 w-4">+ <path d="M8.84182 3.13514C9.04327 3.32401 9.05348 3.64042 8.86462 3.84188L5.43521 7.49991L8.86462 11.1579C9.05348 11.3594 9.04327 11.6758 8.84182 11.8647C8.64036 12.0535 8.32394 12.0433 8.13508 11.8419L4.38508 7.84188C4.20477 7.64955 4.20477 7.35027 4.38508 7.15794L8.13508 3.15794C8.32394 2.95648 8.64036 2.94628 8.84182 3.13514Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ <Button+ variant="outline"+ size="sm"+ class="h-8 w-8 p-0"+ onclick={() => handlePageChange(currentPage + 1)}+ disabled={currentPage >= totalPages || loading}+ >+ <span class="sr-only">Go to next page</span>+ <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none" class="lucide lucide-chevron-right h-4 w-4">+ <path d="M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z" fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"></path>+ </svg>+ </Button>+ </div>+ </div>+ </div>+ {/if}+</div>diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.sveltenew file mode 100644index 00000000..e0bfea7f--- /dev/null+++ b/frontend/src/routes/metrics/+page.svelte@@ -0,0 +1,118 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { Button } from '$lib/components/ui/button';+ import { Skeleton } from '$lib/components/ui/skeleton';+ import { RefreshCw } from 'lucide-svelte';+ import MetricCard from '$lib/components/dashboard/metric-card.svelte';+ import type { DashboardData, DashboardMetric } 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';++ let dashboardData = $state<DashboardData | null>(null);+ let loading = $state(true);+ let error = $state('');+ let errorStatus = $state<number>(0);++ async function loadDashboard() {+ loading = true;+ error = '';+ errorStatus = 0;++ try {+ const response = await api.get('/dashboard', { projectId: projectsState.currentProjectId ?? undefined });++ // Transform the API response to match the DashboardData type+ // Convert timestamp strings to Date objects+ const metrics: DashboardMetric[] = response.metrics.map((m: any) => ({+ id: m.id,+ name: m.name,+ value: m.value,+ unit: m.unit,+ trend: m.trend.map((t: any) => ({+ timestamp: new Date(t.timestamp),+ value: t.value+ })),+ change24h: m.change24h,+ status: m.status+ }));++ dashboardData = {+ metrics,+ lastUpdated: new Date(response.lastUpdated)+ };+ } catch (e: any) {+ errorStatus = e.status || 0;+ error = e.message || 'Failed to load dashboard data';+ console.error(e);+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ loadDashboard();+ });++ const lastUpdatedFormatted = $derived(+ dashboardData?.lastUpdated+ ? dashboardData.lastUpdated.toLocaleString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hour12: false+ })+ : ''+ );+</script>++<div class="space-y-4">+ <!-- Header -->+ <div class="flex items-center justify-between">+ <div>+ <h2 class="text-3xl font-bold tracking-tight">Metrics</h2>+ {#if dashboardData}+ <p class="mt-1 text-sm text-muted-foreground">Last updated: {lastUpdatedFormatted}</p>+ {/if}+ </div>+ <Button variant="outline" size="sm" onclick={loadDashboard} disabled={loading}>+ <RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />+ Refresh+ </Button>+ </div>++ {#if error && !loading}+ <ErrorDisplay+ status={errorStatus === 404 ? 404 : errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}+ title="Failed to Load Metrics"+ description={error}+ onRetry={() => loadDashboard()}+ />+ {/if}++ <!-- Metrics Grid -->+ {#if !error}+ <div class="grid grid-cols-1 gap-4 md:grid-cols-3">+ {#if loading}+ {#each Array(6) as _}+ <Card>+ <CardContent class="flex gap-3 flex-col">+ <div class="flex items-center justify-between">+ <Skeleton class="h-4 w-24" />+ <Skeleton class="h-2 w-2 rounded-full" />+ </div>+ <Skeleton class="h-8 w-32" />+ <Skeleton class="h-16 w-full" />+ <Skeleton class="h-3 w-28" />+ </CardContent>+ </Card>+ {/each}+ {:else if dashboardData}+ {#each dashboardData.metrics as metric (metric.id)}+ <MetricCard {metric} />+ {/each}+ {/if}+ </div>+ {/if}+</div>diff --git a/frontend/src/routes/metrics/+page.ts b/frontend/src/routes/metrics/+page.tsnew file mode 100644index 00000000..9f2ce0c4--- /dev/null+++ b/frontend/src/routes/metrics/+page.ts@@ -0,0 +1,9 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const load: PageLoad = () => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login');+ }+};diff --git a/frontend/src/routes/transactions/+page.svelte b/frontend/src/routes/transactions/+page.svelteindex 6a015e07..01be6818 100644--- a/frontend/src/routes/transactions/+page.svelte+++ b/frontend/src/routes/transactions/+page.svelte@@ -20,7 +20,7 @@lastSeen: string;};- type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen';+ type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen' | 'impact';let endpoints = $state<EndpointStats[]>([]);let loading = $state(true);@@ -38,8 +38,8 @@let fromTime = $state('00:00');let toTime = $state('23:59');- // Sorting- let orderBy = $state<SortField>('count');+ // Sorting - default to impact+ let orderBy = $state<SortField>('impact');// Page size optionsconst pageSizeOptions = [@@ -74,11 +74,31 @@function formatDuration(nanoseconds: number): string {const ms = nanoseconds / 1_000_000;if (ms < 1) {- return `${(nanoseconds / 1000).toFixed(2)}µs`;+ return `${(nanoseconds / 1000).toFixed(0)}µs`;} else if (ms < 1000) {- return `${ms.toFixed(2)}ms`;+ return `${ms.toFixed(0)}ms`;} else {- return `${(ms / 1000).toFixed(2)}s`;+ return `${(ms / 1000).toFixed(1)}s`;+ }+ }++ // 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' } {+ 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' };+ }++ 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' };}}@@ -161,14 +181,14 @@<Table.Header><Table.Row><Table.Head>Endpoint</Table.Head>- <Table.Head class="w-[120px]">+ <Table.Head class="w-[100px]"><Buttonvariant="ghost"size="sm"class="h-8 -ml-3 font-medium"onclick={() => handleSort('count')}>- Requests+ Calls{#if orderBy === 'count'}<ArrowDown class="ml-2 h-4 w-4" />{:else}@@ -176,14 +196,14 @@{/if}</Button></Table.Head>- <Table.Head class="w-[120px]">+ <Table.Head class="w-[100px]"><Buttonvariant="ghost"size="sm"class="h-8 -ml-3 font-medium"onclick={() => handleSort('p50_duration')}>- P50+ Typical{#if orderBy === 'p50_duration'}<ArrowDown class="ml-2 h-4 w-4" />{:else}@@ -191,14 +211,14 @@{/if}</Button></Table.Head>- <Table.Head class="w-[120px]">+ <Table.Head class="w-[100px]"><Buttonvariant="ghost"size="sm"class="h-8 -ml-3 font-medium"onclick={() => handleSort('p95_duration')}>- P95+ Slow{#if orderBy === 'p95_duration'}<ArrowDown class="ml-2 h-4 w-4" />{:else}@@ -206,15 +226,15 @@{/if}</Button></Table.Head>- <Table.Head class="w-[180px]">+ <Table.Head class="w-[80px]"><Buttonvariant="ghost"size="sm"class="h-8 -ml-3 font-medium"- onclick={() => handleSort('last_seen')}+ onclick={() => handleSort('impact')}>- Last Seen- {#if orderBy === 'last_seen'}+ Impact+ {#if orderBy === 'impact'}<ArrowDown class="ml-2 h-4 w-4" />{:else}<ArrowUpDown class="ml-2 h-4 w-4" />@@ -228,10 +248,10 @@{#each Array(5) as _}<Table.Row><Table.Cell><Skeleton class="h-4 w-[250px]" /></Table.Cell>+ <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-[60px]" /></Table.Cell>- <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell>- <Table.Cell><Skeleton class="h-4 w-[80px]" /></Table.Cell>- <Table.Cell><Skeleton class="h-4 w-[140px]" /></Table.Cell>+ <Table.Cell><Skeleton class="h-4 w-[30px]" /></Table.Cell></Table.Row>{/each}{:else if error}@@ -242,12 +262,13 @@</Table.Row>{:else if endpoints.length === 0}<Table.Row>- <Table.Cell colspan={5} class="h-24 text-center">- No transactions found in this time range.+ <Table.Cell colspan={5} class="h-24 text-center text-muted-foreground">+ No transaction data received yet</Table.Cell></Table.Row>{:else}{#each endpoints as endpoint}+ {@const impact = getImpactIndicator(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}<Table.Rowclass="cursor-pointer hover:bg-muted/50"onclick={() => navigateToEndpoint(endpoint.endpoint)}@@ -255,17 +276,17 @@<Table.Cell class="font-mono text-sm">{endpoint.endpoint}</Table.Cell>- <Table.Cell class="font-medium">+ <Table.Cell class="tabular-nums">{endpoint.count.toLocaleString()}</Table.Cell>- <Table.Cell class="font-mono text-sm">+ <Table.Cell class="font-mono text-sm tabular-nums">{formatDuration(endpoint.p50Duration)}</Table.Cell>- <Table.Cell class="font-mono text-sm">+ <Table.Cell class="font-mono text-sm tabular-nums">{formatDuration(endpoint.p95Duration)}</Table.Cell>- <Table.Cell class="text-muted-foreground">- {new Date(endpoint.lastSeen).toLocaleString()}+ <Table.Cell class="font-mono text-sm tabular-nums">+ <span class={impact.class}>{impact.text}</span></Table.Cell></Table.Row>{/each}diff --git a/frontend/src/routes/transactions/[endpoint]/+page.svelte b/frontend/src/routes/transactions/[endpoint]/+page.svelteindex bf7aa487..91df61e5 100644--- a/frontend/src/routes/transactions/[endpoint]/+page.svelte+++ b/frontend/src/routes/transactions/[endpoint]/+page.svelte@@ -10,6 +10,7 @@import { CalendarDate, getLocalTimeZone, today } from "@internationalized/date";import { ErrorDisplay } from "$lib/components/ui/error-display";import { projectsState } from '$lib/state/projects.svelte';+ import ScopeDisplay from '$lib/components/scope-display.svelte';type Transaction = {id: string;@@ -19,6 +20,7 @@statusCode: number;bodySize: number;clientIP: string;+ scope: Record<string, string> | null;};type SortField = 'recorded_at' | 'duration' | 'status_code' | 'body_size';@@ -281,6 +283,7 @@</Button></Table.Head><Table.Head class="w-[140px]">Client IP</Table.Head>+ <Table.Head>Context</Table.Head></Table.Row></Table.Header><Table.Body>@@ -292,11 +295,12 @@<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-[150px]" /></Table.Cell></Table.Row>{/each}{:else if transactions.length === 0}<Table.Row>- <Table.Cell colspan={5} class="h-24 text-center">+ <Table.Cell colspan={6} class="h-24 text-center">No transactions found in this time range.</Table.Cell></Table.Row>@@ -318,6 +322,9 @@<Table.Cell class="font-mono text-sm text-muted-foreground">{transaction.clientIP}</Table.Cell>+ <Table.Cell>+ <ScopeDisplay scope={transaction.scope} />+ </Table.Cell></Table.Row>{/each}{/if}