The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
v2 progress
ddux0130bce45f39
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.goindex 040346f0..603a02ea 100644--- a/backend/app/controllers/clientcontrollers/client.controller.go+++ b/backend/app/controllers/clientcontrollers/client.controller.go@@ -33,15 +33,22 @@ func (e clientController) Report(c *gin.Context) {return}- transactionsToInsert := []models.Transaction{}+ endpointsToInsert := []models.Endpoint{}+ tasksToInsert := []models.Task{}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 = projectId- transactionsToInsert = append(transactionsToInsert, t)+ if ct.IsTask {+ t := ct.ToTask(request.AppVersion, request.ServerName)+ t.ProjectId = projectId+ tasksToInsert = append(tasksToInsert, t)+ } else {+ e := ct.ToEndpoint(request.AppVersion, request.ServerName)+ e.ProjectId = projectId+ endpointsToInsert = append(endpointsToInsert, e)+ }// Extract segments from transactionfor _, cs := range ct.Segments {@@ -64,13 +71,21 @@ func (e clientController) Report(c *gin.Context) {}}- err := repositories.TransactionRepository.InsertAsync(c, transactionsToInsert)+ if len(endpointsToInsert) > 0 {+ err := repositories.EndpointRepository.InsertAsync(c, endpointsToInsert)+ if err != nil {+ panic(err)+ }+ }- if err != nil {- panic(err)+ if len(tasksToInsert) > 0 {+ err := repositories.TaskRepository.InsertAsync(c, tasksToInsert)+ if err != nil {+ panic(err)+ }}- err = repositories.ExceptionStackTraceRepository.InsertAsync(c, exceptionStackTraceToInsert)+ err := repositories.ExceptionStackTraceRepository.InsertAsync(c, exceptionStackTraceToInsert)if err != nil {panic(err)diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.goindex 5025def1..95be0a30 100644--- a/backend/app/controllers/dashboard.controller.go+++ b/backend/app/controllers/dashboard.controller.go@@ -31,7 +31,7 @@ func (d dashboardController) GetDashboardOverview(c *gin.Context) {}// Get 10 worst performing endpoints- worstEndpoints, err := repositories.TransactionRepository.FindWorstEndpoints(c, projectId, start, now, 10)+ worstEndpoints, err := repositories.EndpointRepository.FindWorstEndpoints(c, projectId, start, now, 10)if err != nil {panic(err)}@@ -94,12 +94,12 @@ func (d dashboardController) GetDashboard(c *gin.Context) {metrics := make([]models.DashboardMetric, 0, 11)// 1. Requests count- requestsTrend, err := repositories.TransactionRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ requestsTrend, err := repositories.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}- requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, end)- requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, projectId, prevStart, prevEnd)+ requestsCurrent, _ := repositories.EndpointRepository.CountBetween(c, projectId, start, end)+ requestsPrev, _ := repositories.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))// 2. Exceptions count@@ -112,22 +112,22 @@ func (d dashboardController) GetDashboard(c *gin.Context) {metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))// 3. Average Response Time- avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)+ avgDurationTrend, err := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}avgDurationCurrent := getLastValue(avgDurationTrend)- avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ avgDurationPrevTrend, _ := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)avgDurationPrev := getAverageValue(avgDurationPrevTrend)metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))// 4. Error Rate- errorRateTrend, err := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)+ errorRateTrend, err := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}errorRateCurrent := getLastValue(errorRateTrend)- errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ errorRatePrevTrend, _ := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)errorRatePrev := getAverageValue(errorRatePrevTrend)metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))diff --git a/backend/app/controllers/transaction.controller.go b/backend/app/controllers/endpoint.controller.gosimilarity index 62%rename from backend/app/controllers/transaction.controller.gorename to backend/app/controllers/endpoint.controller.goindex c59d835b..e24b7413 100644--- a/backend/app/controllers/transaction.controller.go+++ b/backend/app/controllers/endpoint.controller.go@@ -10,9 +10,9 @@ import ("github.com/gin-gonic/gin")-type transactionController struct{}+type endpointController struct{}-type TransactionSearchRequest struct {+type EndpointSearchRequest struct {ProjectId string `json:"projectId"`FromDate time.Time `json:"fromDate"`ToDate time.Time `json:"toDate"`@@ -21,7 +21,7 @@ type TransactionSearchRequest struct {Pagination PaginationParams `json:"pagination"`}-type EndpointTransactionsRequest struct {+type EndpointInstancesRequest struct {ProjectId string `json:"projectId"`FromDate time.Time `json:"fromDate"`ToDate time.Time `json:"toDate"`@@ -30,26 +30,26 @@ type EndpointTransactionsRequest struct {Pagination PaginationParams `json:"pagination"`}-type EndpointTransactionsResponse struct {- Data []models.Transaction `json:"data"`+type EndpointInstancesResponse struct {+ Data []models.Endpoint `json:"data"`Stats *models.EndpointDetailStats `json:"stats"`- Pagination Pagination `json:"pagination"`+ Pagination Pagination `json:"pagination"`}-func (e transactionController) FindAllTransactions(c *gin.Context) {- var request TransactionSearchRequest+func (e endpointController) FindAllEndpoints(c *gin.Context) {+ var request EndpointSearchRequestif err := c.ShouldBindJSON(&request); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}- transactions, total, err := repositories.TransactionRepository.FindAll(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ endpoints, total, err := repositories.EndpointRepository.FindAll(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)if err != nil {panic(err)}- c.JSON(http.StatusOK, PaginatedResponse[models.Transaction]{- Data: transactions,+ c.JSON(http.StatusOK, PaginatedResponse[models.Endpoint]{+ Data: endpoints,Pagination: Pagination{Page: request.Pagination.Page,PageSize: request.Pagination.PageSize,@@ -59,14 +59,14 @@ func (e transactionController) FindAllTransactions(c *gin.Context) {})}-func (e transactionController) FindGroupedByEndpoint(c *gin.Context) {- var request TransactionSearchRequest+func (e endpointController) FindGroupedByEndpoint(c *gin.Context) {+ var request EndpointSearchRequestif err := c.ShouldBindJSON(&request); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}- stats, total, err := repositories.TransactionRepository.FindGroupedByEndpoint(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ stats, total, err := repositories.EndpointRepository.FindGroupedByEndpoint(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)if err != nil {panic(err)}@@ -82,7 +82,7 @@ func (e transactionController) FindGroupedByEndpoint(c *gin.Context) {})}-func (e transactionController) FindByEndpoint(c *gin.Context) {+func (e endpointController) FindByEndpoint(c *gin.Context) {rawEndpoint := c.Query("endpoint")if rawEndpoint == "" {c.JSON(http.StatusBadRequest, gin.H{"error": "endpoint is required"})@@ -95,26 +95,26 @@ func (e transactionController) FindByEndpoint(c *gin.Context) {endpoint = rawEndpoint // fallback to raw value if decoding fails}- var request EndpointTransactionsRequest+ var request EndpointInstancesRequestif err := c.ShouldBindJSON(&request); err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}- transactions, total, err := repositories.TransactionRepository.FindByEndpoint(c, request.ProjectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ endpoints, total, err := repositories.EndpointRepository.FindByEndpoint(c, request.ProjectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)if err != nil {panic(err)}// Get aggregate stats for this endpoint- stats, err := repositories.TransactionRepository.GetEndpointStats(c, request.ProjectId, endpoint, request.FromDate, request.ToDate)+ stats, err := repositories.EndpointRepository.GetEndpointStats(c, request.ProjectId, endpoint, request.FromDate, request.ToDate)if err != nil {// Don't fail the request if stats fail, just return nil statsstats = nil}- c.JSON(http.StatusOK, EndpointTransactionsResponse{- Data: transactions,+ c.JSON(http.StatusOK, EndpointInstancesResponse{+ Data: endpoints,Stats: stats,Pagination: Pagination{Page: request.Pagination.Page,@@ -125,4 +125,4 @@ func (e transactionController) FindByEndpoint(c *gin.Context) {})}-var TransactionController = transactionController{}+var EndpointController = endpointController{}diff --git a/backend/app/controllers/endpoint_detail.controller.go b/backend/app/controllers/endpoint_detail.controller.gonew file mode 100644index 00000000..541d99c4--- /dev/null+++ b/backend/app/controllers/endpoint_detail.controller.go@@ -0,0 +1,78 @@+package controllers++import (+ "backend/app/models"+ "backend/app/repositories"+ "net/http"++ "github.com/gin-gonic/gin"+)++type endpointDetailController struct{}++type EndpointDetailRequest struct {+ ProjectId string `json:"projectId"`+}++type EndpointExceptionInfo struct {+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ RecordedAt string `json:"recordedAt"`+}++type EndpointDetailResponse struct {+ Endpoint *models.Endpoint `json:"endpoint"`+ Segments []models.Segment `json:"segments"`+ HasSegments bool `json:"hasSegments"`+ Exception *EndpointExceptionInfo `json:"exception,omitempty"`+}++func (c endpointDetailController) GetEndpointDetail(ctx *gin.Context) {+ endpointId := ctx.Param("endpointId")+ if endpointId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "endpointId is required"})+ return+ }++ var request EndpointDetailRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Get endpoint+ endpoint, err := repositories.EndpointRepository.FindById(ctx, request.ProjectId, endpointId)+ if err != nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Endpoint not found"})+ return+ }++ // Get segments (flat list ordered by start_time)+ segments, err := repositories.SegmentRepository.FindByTransactionId(ctx, request.ProjectId, endpointId)+ if err != nil {+ panic(err)+ }++ // Get linked exception if any+ var exceptionInfo *EndpointExceptionInfo+ exception, err := repositories.ExceptionStackTraceRepository.FindByTransactionId(ctx, request.ProjectId, endpointId)+ if err != nil {+ panic(err)+ }+ if exception != nil {+ exceptionInfo = &EndpointExceptionInfo{+ ExceptionHash: exception.ExceptionHash,+ StackTrace: exception.StackTrace,+ RecordedAt: exception.RecordedAt.Format("2006-01-02T15:04:05Z07:00"),+ }+ }++ ctx.JSON(http.StatusOK, EndpointDetailResponse{+ Endpoint: endpoint,+ Segments: segments,+ HasSegments: len(segments) > 0,+ Exception: exceptionInfo,+ })+}++var EndpointDetailController = endpointDetailController{}diff --git a/backend/app/controllers/metric_record.controller.go b/backend/app/controllers/metric_record.controller.goindex d4752974..61e5d92e 100644--- a/backend/app/controllers/metric_record.controller.go+++ b/backend/app/controllers/metric_record.controller.go@@ -30,11 +30,11 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {twoDaysAgo := now.Add(-48 * time.Hour)// requests- requestsNow, err := repositories.TransactionRepository.CountBetween(c, projectId, oneDayAgo, now)+ requestsNow, err := repositories.EndpointRepository.CountBetween(c, projectId, oneDayAgo, now)if err != nil {panic(err)}- requestsPrev, err := repositories.TransactionRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)+ requestsPrev, err := repositories.EndpointRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)if err != nil {panic(err)}diff --git a/backend/app/controllers/metrics.controller.go b/backend/app/controllers/metrics.controller.goindex 6f77ced9..fa8284f4 100644--- a/backend/app/controllers/metrics.controller.go+++ b/backend/app/controllers/metrics.controller.go@@ -119,12 +119,12 @@ func (m metricsController) GetStatsMetrics(c *gin.Context) {metrics := make([]models.DashboardMetric, 0, 4)// 1. Requests count- requestsTrend, err := repositories.TransactionRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ requestsTrend, err := repositories.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}- requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, end)- requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, projectId, prevStart, prevEnd)+ requestsCurrent, _ := repositories.EndpointRepository.CountBetween(c, projectId, start, end)+ requestsPrev, _ := repositories.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))// 2. Exceptions count@@ -137,22 +137,22 @@ func (m metricsController) GetStatsMetrics(c *gin.Context) {metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))// 3. Average Response Time- avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)+ avgDurationTrend, err := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}avgDurationCurrent := getLastValue(avgDurationTrend)- avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ avgDurationPrevTrend, _ := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)avgDurationPrev := getAverageValue(avgDurationPrevTrend)metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))// 4. Error Rate- errorRateTrend, err := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)+ errorRateTrend, err := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)if err != nil {panic(err)}errorRateCurrent := getLastValue(errorRateTrend)- errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ errorRatePrevTrend, _ := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)errorRatePrev := getAverageValue(errorRatePrevTrend)metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex c0d28706..0247bf66 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -41,10 +41,17 @@ func RegisterControllers(router *gin.RouterGroup) {router.GET("/metrics/stats", middleware.UseAppAuth, MetricsController.GetStatsMetrics)router.GET("/metrics/server", middleware.UseAppAuth, MetricsController.GetServerMetrics)- 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)+ // Endpoints+ router.POST("/endpoints", middleware.UseAppAuth, EndpointController.FindAllEndpoints)+ router.POST("/endpoints/grouped", middleware.UseAppAuth, EndpointController.FindGroupedByEndpoint)+ router.POST("/endpoints/endpoint", middleware.UseAppAuth, EndpointController.FindByEndpoint)+ router.POST("/endpoints/:endpointId", middleware.UseAppAuth, EndpointDetailController.GetEndpointDetail)++ // Tasks+ router.POST("/tasks", middleware.UseAppAuth, TaskController.FindAllTasks)+ router.POST("/tasks/grouped", middleware.UseAppAuth, TaskController.FindGroupedByTaskName)+ router.POST("/tasks/task", middleware.UseAppAuth, TaskController.FindByTaskName)+ router.POST("/tasks/:taskId", middleware.UseAppAuth, TaskDetailController.GetTaskDetail)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/task.controller.go b/backend/app/controllers/task.controller.gonew file mode 100644index 00000000..dc662e0e--- /dev/null+++ b/backend/app/controllers/task.controller.go@@ -0,0 +1,128 @@+package controllers++import (+ "backend/app/models"+ "backend/app/repositories"+ "net/http"+ "net/url"+ "time"++ "github.com/gin-gonic/gin"+)++type taskController struct{}++type TaskSearchRequest struct {+ ProjectId string `json:"projectId"`+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ SortDirection string `json:"sortDirection"`+ Pagination PaginationParams `json:"pagination"`+}++type TaskInstancesRequest struct {+ ProjectId string `json:"projectId"`+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ SortDirection string `json:"sortDirection"`+ Pagination PaginationParams `json:"pagination"`+}++type TaskInstancesResponse struct {+ Data []models.Task `json:"data"`+ Stats *models.TaskDetailStats `json:"stats"`+ Pagination Pagination `json:"pagination"`+}++func (e taskController) FindAllTasks(c *gin.Context) {+ var request TaskSearchRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ tasks, total, err := repositories.TaskRepository.FindAll(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ if err != nil {+ panic(err)+ }++ c.JSON(http.StatusOK, PaginatedResponse[models.Task]{+ Data: tasks,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}++func (e taskController) FindGroupedByTaskName(c *gin.Context) {+ var request TaskSearchRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ stats, total, err := repositories.TaskRepository.FindGroupedByTaskName(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ if err != nil {+ panic(err)+ }++ c.JSON(http.StatusOK, PaginatedResponse[models.TaskStats]{+ Data: stats,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}++func (e taskController) FindByTaskName(c *gin.Context) {+ rawTaskName := c.Query("task")+ if rawTaskName == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "task is required"})+ return+ }++ // URL decode the task name+ taskName, err := url.PathUnescape(rawTaskName)+ if err != nil {+ taskName = rawTaskName // fallback to raw value if decoding fails+ }++ var request TaskInstancesRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ tasks, total, err := repositories.TaskRepository.FindByTaskName(c, request.ProjectId, taskName, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ if err != nil {+ panic(err)+ }++ // Get aggregate stats for this task+ stats, err := repositories.TaskRepository.GetTaskStats(c, request.ProjectId, taskName, request.FromDate, request.ToDate)+ if err != nil {+ // Don't fail the request if stats fail, just return nil stats+ stats = nil+ }++ c.JSON(http.StatusOK, TaskInstancesResponse{+ Data: tasks,+ Stats: stats,+ Pagination: Pagination{+ Page: request.Pagination.Page,+ PageSize: request.Pagination.PageSize,+ Total: total,+ TotalPages: (total + int64(request.Pagination.PageSize) - 1) / int64(request.Pagination.PageSize),+ },+ })+}++var TaskController = taskController{}diff --git a/backend/app/controllers/task_detail.controller.go b/backend/app/controllers/task_detail.controller.gonew file mode 100644index 00000000..5b94d33c--- /dev/null+++ b/backend/app/controllers/task_detail.controller.go@@ -0,0 +1,78 @@+package controllers++import (+ "backend/app/models"+ "backend/app/repositories"+ "net/http"++ "github.com/gin-gonic/gin"+)++type taskDetailController struct{}++type TaskDetailRequest struct {+ ProjectId string `json:"projectId"`+}++type TaskExceptionInfo struct {+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ RecordedAt string `json:"recordedAt"`+}++type TaskDetailResponse struct {+ Task *models.Task `json:"task"`+ Segments []models.Segment `json:"segments"`+ HasSegments bool `json:"hasSegments"`+ Exception *TaskExceptionInfo `json:"exception,omitempty"`+}++func (c taskDetailController) GetTaskDetail(ctx *gin.Context) {+ taskId := ctx.Param("taskId")+ if taskId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "taskId is required"})+ return+ }++ var request TaskDetailRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Get task+ task, err := repositories.TaskRepository.FindById(ctx, request.ProjectId, taskId)+ if err != nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Task not found"})+ return+ }++ // Get segments (flat list ordered by start_time)+ segments, err := repositories.SegmentRepository.FindByTransactionId(ctx, request.ProjectId, taskId)+ if err != nil {+ panic(err)+ }++ // Get linked exception if any+ var exceptionInfo *TaskExceptionInfo+ exception, err := repositories.ExceptionStackTraceRepository.FindByTransactionId(ctx, request.ProjectId, taskId)+ if err != nil {+ panic(err)+ }+ if exception != nil {+ exceptionInfo = &TaskExceptionInfo{+ ExceptionHash: exception.ExceptionHash,+ StackTrace: exception.StackTrace,+ RecordedAt: exception.RecordedAt.Format("2006-01-02T15:04:05Z07:00"),+ }+ }++ ctx.JSON(http.StatusOK, TaskDetailResponse{+ Task: task,+ Segments: segments,+ HasSegments: len(segments) > 0,+ Exception: exceptionInfo,+ })+}++var TaskDetailController = taskDetailController{}diff --git a/backend/app/controllers/transaction_detail.controller.go b/backend/app/controllers/transaction_detail.controller.godeleted file mode 100644index 3320b1ae..00000000--- a/backend/app/controllers/transaction_detail.controller.go+++ /dev/null@@ -1,78 +0,0 @@-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 ExceptionInfo struct {- ExceptionHash string `json:"exceptionHash"`- StackTrace string `json:"stackTrace"`- RecordedAt string `json:"recordedAt"`-}--type TransactionDetailResponse struct {- Transaction *models.Transaction `json:"transaction"`- Segments []models.Segment `json:"segments"`- HasSegments bool `json:"hasSegments"`- Exception *ExceptionInfo `json:"exception,omitempty"`-}--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)- }-- // Get linked exception if any- var exceptionInfo *ExceptionInfo- exception, err := repositories.ExceptionStackTraceRepository.FindByTransactionId(ctx, request.ProjectId, transactionId)- if err != nil {- panic(err)- }- if exception != nil {- exceptionInfo = &ExceptionInfo{- ExceptionHash: exception.ExceptionHash,- StackTrace: exception.StackTrace,- RecordedAt: exception.RecordedAt.Format("2006-01-02T15:04:05Z07:00"),- }- }-- ctx.JSON(http.StatusOK, TransactionDetailResponse{- Transaction: transaction,- Segments: segments,- HasSegments: len(segments) > 0,- Exception: exceptionInfo,- })-}--var TransactionDetailController = transactionDetailController{}diff --git a/backend/app/migrations/ch/0020_create_endpoints.up.sql b/backend/app/migrations/ch/0020_create_endpoints.up.sqlnew file mode 100644index 00000000..56f7d72a--- /dev/null+++ b/backend/app/migrations/ch/0020_create_endpoints.up.sql@@ -0,0 +1,15 @@+CREATE TABLE IF NOT EXISTS endpoints (+ id String,+ project_id String,+ endpoint String,+ duration Int64,+ recorded_at DateTime,+ status_code Int32,+ body_size Int32,+ client_ip String,+ scope String DEFAULT '{}',+ app_version String DEFAULT '',+ server_name String DEFAULT ''+) ENGINE = MergeTree()+PARTITION BY toYYYYMM(recorded_at)+ORDER BY (project_id, recorded_at, endpoint);diff --git a/backend/app/migrations/ch/0021_create_tasks.up.sql b/backend/app/migrations/ch/0021_create_tasks.up.sqlnew file mode 100644index 00000000..2157d8a1--- /dev/null+++ b/backend/app/migrations/ch/0021_create_tasks.up.sql@@ -0,0 +1,13 @@+CREATE TABLE IF NOT EXISTS tasks (+ id String,+ project_id String,+ task_name String,+ duration Int64,+ recorded_at DateTime,+ client_ip String,+ scope String DEFAULT '{}',+ app_version String DEFAULT '',+ server_name String DEFAULT ''+) ENGINE = MergeTree()+PARTITION BY toYYYYMM(recorded_at)+ORDER BY (project_id, recorded_at, task_name);diff --git a/backend/app/migrations/ch/0022_add_transaction_type_to_exceptions.up.sql b/backend/app/migrations/ch/0022_add_transaction_type_to_exceptions.up.sqlnew file mode 100644index 00000000..3698487b--- /dev/null+++ b/backend/app/migrations/ch/0022_add_transaction_type_to_exceptions.up.sql@@ -0,0 +1 @@+ALTER TABLE exception_stack_traces ADD COLUMN IF NOT EXISTS transaction_type String DEFAULT 'endpoint';diff --git a/backend/app/migrations/ch/0023_migrate_transactions_to_endpoints.up.sql b/backend/app/migrations/ch/0023_migrate_transactions_to_endpoints.up.sqlnew file mode 100644index 00000000..de2b40a4--- /dev/null+++ b/backend/app/migrations/ch/0023_migrate_transactions_to_endpoints.up.sql@@ -0,0 +1 @@+INSERT INTO endpoints SELECT * FROM transactions;diff --git a/backend/app/models/clientmodels/clientmodels.model.go b/backend/app/models/clientmodels/clientmodels.model.goindex ed79f6ad..bf92f8cf 100644--- a/backend/app/models/clientmodels/clientmodels.model.go+++ b/backend/app/models/clientmodels/clientmodels.model.go@@ -7,6 +7,7 @@ import (type ClientExceptionStackTrace struct {TransactionId *string `json:"transactionId"`+ IsTask bool `json:"isTask"`StackTrace string `json:"stackTrace"`RecordedAt time.Time `json:"recordedAt"`Scope map[string]string `json:"scope"`@@ -14,15 +15,20 @@ type ClientExceptionStackTrace struct {}func (c *ClientExceptionStackTrace) ToExceptionStackTrace(exceptionHash, appVersion, serverName string) models.ExceptionStackTrace {+ transactionType := "endpoint"+ if c.IsTask {+ transactionType = "task"+ }return models.ExceptionStackTrace{- ExceptionHash: exceptionHash,- TransactionId: c.TransactionId,- StackTrace: c.StackTrace,- RecordedAt: c.RecordedAt,- Scope: c.Scope,- IsMessage: c.IsMessage,- AppVersion: appVersion,- ServerName: serverName,+ ExceptionHash: exceptionHash,+ TransactionId: c.TransactionId,+ TransactionType: transactionType,+ StackTrace: c.StackTrace,+ RecordedAt: c.RecordedAt,+ Scope: c.Scope,+ IsMessage: c.IsMessage,+ AppVersion: appVersion,+ ServerName: serverName,}}@@ -51,10 +57,11 @@ type ClientTransaction struct {ClientIP string `json:"clientIP"`Scope map[string]string `json:"scope"`Segments []*ClientSegment `json:"segments"`+ IsTask bool `json:"isTask"`}-func (c *ClientTransaction) ToTransaction(appVersion, serverName string) models.Transaction {- return models.Transaction{+func (c *ClientTransaction) ToEndpoint(appVersion, serverName string) models.Endpoint {+ return models.Endpoint{Id: c.Id,Endpoint: c.Endpoint,Duration: c.Duration,@@ -68,6 +75,19 @@ func (c *ClientTransaction) ToTransaction(appVersion, serverName string) models.}}+func (c *ClientTransaction) ToTask(appVersion, serverName string) models.Task {+ return models.Task{+ Id: c.Id,+ TaskName: c.Endpoint, // Endpoint field is used as task name+ Duration: c.Duration,+ RecordedAt: c.RecordedAt,+ ClientIP: c.ClientIP,+ Scope: c.Scope,+ AppVersion: appVersion,+ ServerName: serverName,+ }+}+type ClientSegment struct {Id string `json:"id"`Name string `json:"name"`diff --git a/backend/app/models/transaction.model.go b/backend/app/models/endpoint.model.gosimilarity index 98%rename from backend/app/models/transaction.model.gorename to backend/app/models/endpoint.model.goindex 09857742..f54cd9a2 100644--- a/backend/app/models/transaction.model.go+++ b/backend/app/models/endpoint.model.go@@ -2,7 +2,7 @@ package modelsimport "time"-type Transaction struct {+type Endpoint 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 itdiff --git a/backend/app/models/exception_stack_trace.model.go b/backend/app/models/exception_stack_trace.model.goindex 0f3b70c7..103ad0c6 100644--- a/backend/app/models/exception_stack_trace.model.go+++ b/backend/app/models/exception_stack_trace.model.go@@ -3,15 +3,16 @@ 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"`- Scope map[string]string `json:"scope" ch:"scope"`- AppVersion string `json:"appVersion" ch:"app_version"`- ServerName string `json:"serverName" ch:"server_name"`- IsMessage bool `json:"isMessage" ch:"is_message"`+ ProjectId string `json:"projectId" ch:"project_id"`+ TransactionId *string `json:"transactionId" ch:"transaction_id"`+ TransactionType string `json:"transactionType" ch:"transaction_type"` // "endpoint" or "task"+ 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"`+ AppVersion string `json:"appVersion" ch:"app_version"`+ ServerName string `json:"serverName" ch:"server_name"`+ IsMessage bool `json:"isMessage" ch:"is_message"`}type ExceptionTrendPoint struct {diff --git a/backend/app/models/task.model.go b/backend/app/models/task.model.gonew file mode 100644index 00000000..ec6a79dd--- /dev/null+++ b/backend/app/models/task.model.go@@ -0,0 +1,34 @@+package models++import "time"++type Task struct {+ Id string `json:"id" ch:"id"`+ ProjectId string `json:"projectId" ch:"project_id"`+ TaskName string `json:"taskName" ch:"task_name"`+ Duration time.Duration `json:"duration" ch:"duration"`+ RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ ClientIP string `json:"clientIP" ch:"client_ip"`+ Scope map[string]string `json:"scope" ch:"scope"`+ AppVersion string `json:"appVersion" ch:"app_version"`+ ServerName string `json:"serverName" ch:"server_name"`+}++type TaskStats struct {+ TaskName string `json:"taskName"`+ Count uint64 `json:"count"`+ P50Duration time.Duration `json:"p50Duration"`+ P95Duration time.Duration `json:"p95Duration"`+ AvgDuration time.Duration `json:"avgDuration"`+ LastSeen time.Time `json:"lastSeen"`+}++// TaskDetailStats contains detailed statistics for a specific task+type TaskDetailStats struct {+ Count int64 `json:"count"`+ AvgDuration float64 `json:"avgDuration"` // in ms+ MedianDuration float64 `json:"medianDuration"` // in ms+ P95Duration float64 `json:"p95Duration"` // in ms+ P99Duration float64 `json:"p99Duration"` // in ms+ Throughput float64 `json:"throughput"` // tasks per minute+}diff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/endpoint.repository.gosimilarity index 72%rename from backend/app/repositories/transaction.repository.gorename to backend/app/repositories/endpoint.repository.goindex 7ecac828..d7c548ce 100644--- a/backend/app/repositories/transaction.repository.go+++ b/backend/app/repositories/endpoint.repository.go@@ -10,10 +10,10 @@ import ("github.com/ClickHouse/clickhouse-go/v2")-type transactionRepository struct{}+type endpointRepository struct{}-func (e *transactionRepository) InsertAsync(ctx context.Context, lines []models.Transaction) error {- batch, err := (*chdb.Conn).PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO transactions (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope, app_version, server_name)")+func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {+ batch, err := (*chdb.Conn).PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO endpoints (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope, app_version, server_name)")if err != nil {return err}@@ -31,15 +31,15 @@ func (e *transactionRepository) InsertAsync(ctx context.Context, lines []models.return batch.Send()}-func (e *transactionRepository) CountBetween(ctx context.Context, projectId string, start, end time.Time) (int64, error) {+func (e *endpointRepository) CountBetween(ctx context.Context, projectId string, start, end time.Time) (int64, error) {var count uint64- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, start, end).Scan(&count)+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, start, end).Scan(&count)return int64(count), err}-func (e *transactionRepository) FindAll(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {+func (e *endpointRepository) FindAll(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Endpoint, int64, error) {var count uint64- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)if err != nil {return nil, 0, err}@@ -57,16 +57,16 @@ 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, scope, app_version, server_name 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, app_version, server_name FROM endpoints 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}defer rows.Close()- var transactions []models.Transaction+ var endpoints []models.Endpointfor rows.Next() {- var t models.Transaction+ var t models.Endpointvar scopeJSON stringif err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {return nil, 0, err@@ -77,16 +77,16 @@ func (e *transactionRepository) FindAll(ctx context.Context, projectId string, ft.Scope = nil}}- transactions = append(transactions, t)+ endpoints = append(endpoints, t)}- return transactions, int64(count), nil+ return endpoints, int64(count), nil}-func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.EndpointStats, int64, error) {+func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.EndpointStats, int64, error) {// Count unique endpointsvar count uint64- err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(endpoint) FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)+ err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(endpoint) FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)if err != nil {return nil, 0, err}@@ -121,7 +121,7 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projequantile(0.95)(duration) as p95_duration,avg(duration) as avg_duration,max(recorded_at) as last_seen- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY endpointORDER BY ` + orderExpr + ` ` + sortDir + `@@ -149,9 +149,9 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projereturn stats, int64(count), nil}-func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId string, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Transaction, int64, error) {+func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId string, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {var count uint64- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, endpoint, fromDate, toDate).Scan(&count)+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, endpoint, fromDate, toDate).Scan(&count)if err != nil {return nil, 0, err}@@ -175,16 +175,16 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId stsortDir = "ASC"}- 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 endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope, app_version, server_name FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"rows, err := (*chdb.Conn).Query(ctx, query, projectId, endpoint, fromDate, toDate, pageSize, offset)if err != nil {return nil, 0, err}defer rows.Close()- var transactions []models.Transaction+ var endpoints []models.Endpointfor rows.Next() {- var t models.Transaction+ var t models.Endpointvar scopeJSON stringif err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); err != nil {return nil, 0, err@@ -195,23 +195,23 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId stt.Scope = nil}}- transactions = append(transactions, t)+ endpoints = append(endpoints, t)}- return transactions, int64(count), nil+ return endpoints, int64(count), nil}-// FindById returns a single transaction by ID-func (e *transactionRepository) FindById(ctx context.Context, projectId, transactionId string) (*models.Transaction, error) {+// FindById returns a single endpoint by ID+func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId string) (*models.Endpoint, error) {query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, scope, app_version, server_name- FROM transactions+ FROM endpointsWHERE project_id = ? AND id = ?LIMIT 1`- var t models.Transaction+ var t models.Endpointvar scopeJSON string- err := (*chdb.Conn).QueryRow(ctx, query, projectId, transactionId).Scan(+ err := (*chdb.Conn).QueryRow(ctx, query, projectId, endpointId).Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt,&t.StatusCode, &t.BodySize, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName)@@ -229,12 +229,12 @@ func (e *transactionRepository) FindById(ctx context.Context, projectId, transacreturn &t, nil}-// CountByHour returns transaction counts grouped by hour-func (e *transactionRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+// CountByHour returns endpoint counts grouped by hour+func (e *endpointRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfHour(recorded_at) as hour,toFloat64(count()) as count- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY hourORDER BY hour ASC`@@ -258,11 +258,11 @@ func (e *transactionRepository) CountByHour(ctx context.Context, projectId strin}// AvgDurationByHour returns average response time in ms grouped by hour-func (e *transactionRepository) AvgDurationByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfHour(recorded_at) as hour,avg(duration) / 1000000 as avg_duration_ms- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY hourORDER BY hour ASC`@@ -286,11 +286,11 @@ func (e *transactionRepository) AvgDurationByHour(ctx context.Context, projectId}// ErrorRateByHour returns error rate (percentage) grouped by hour-func (e *transactionRepository) ErrorRateByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+func (e *endpointRepository) ErrorRateByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfHour(recorded_at) as hour,countIf(status_code >= 400) * 100.0 / count() as error_rate- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY hourORDER BY hour ASC`@@ -313,12 +313,12 @@ func (e *transactionRepository) ErrorRateByHour(ctx context.Context, projectId sreturn points, nil}-// CountByInterval returns transaction counts grouped by configurable interval in minutes-func (e *transactionRepository) CountByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+// CountByInterval returns endpoint counts grouped by configurable interval in minutes+func (e *endpointRepository) CountByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,toFloat64(count()) as count- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY bucketORDER BY bucket ASC`@@ -342,11 +342,11 @@ func (e *transactionRepository) CountByInterval(ctx context.Context, projectId s}// AvgDurationByInterval returns average response time in ms grouped by configurable interval-func (e *transactionRepository) AvgDurationByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,avg(duration) / 1000000 as avg_duration_ms- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY bucketORDER BY bucket ASC`@@ -370,11 +370,11 @@ func (e *transactionRepository) AvgDurationByInterval(ctx context.Context, proje}// ErrorRateByInterval returns error rate (percentage) grouped by configurable interval-func (e *transactionRepository) ErrorRateByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+func (e *endpointRepository) ErrorRateByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {query := `SELECTtoStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,countIf(status_code >= 400) * 100.0 / count() as error_rate- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY bucketORDER BY bucket ASC`@@ -399,7 +399,7 @@ func (e *transactionRepository) ErrorRateByInterval(ctx context.Context, project// 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) {+func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId string, start, end time.Time, limit int) ([]models.EndpointStats, error) {query := `SELECTendpoint,count() as count,@@ -407,7 +407,7 @@ func (e *transactionRepository) FindWorstEndpoints(ctx context.Context, projectIquantile(0.95)(duration) as p95_duration,avg(duration) as avg_duration,max(recorded_at) as last_seen- FROM transactions+ FROM endpointsWHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?GROUP BY endpointORDER BY count * (p95_duration - p50_duration) DESC@@ -436,7 +436,7 @@ func (e *transactionRepository) FindWorstEndpoints(ctx context.Context, projectI}// GetEndpointStats returns aggregate statistics for a specific endpoint-func (e *transactionRepository) GetEndpointStats(ctx context.Context, projectId, endpoint string, start, end time.Time) (*models.EndpointDetailStats, error) {+func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId, endpoint string, start, end time.Time) (*models.EndpointDetailStats, error) {// Calculate time range duration for throughput calculationdurationMinutes := end.Sub(start).Minutes()if durationMinutes < 1 {@@ -453,7 +453,7 @@ func (e *transactionRepository) GetEndpointStats(ctx context.Context, projectId,countIf(duration <= 500000000 AND status_code < 400) +(countIf(duration > 500000000 AND duration <= 2000000000 AND status_code < 400) * 0.5)as satisfied_tolerating- FROM transactions+ FROM endpointsWHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?`var stats models.EndpointDetailStats@@ -484,4 +484,4 @@ func (e *transactionRepository) GetEndpointStats(ctx context.Context, projectId,return &stats, nil}-var TransactionRepository = transactionRepository{}+var EndpointRepository = endpointRepository{}diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.goindex f745eb61..c96cb782 100644--- a/backend/app/repositories/exception_stack_trace.repository.go+++ b/backend/app/repositories/exception_stack_trace.repository.go@@ -16,7 +16,7 @@ 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(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO exception_stack_traces (project_id, transaction_id, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_message)")+ batch, err := (*chdb.Conn).PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO exception_stack_traces (project_id, transaction_id, transaction_type, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_message)")if err != nil {return err}@@ -31,7 +31,11 @@ func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines [if est.IsMessage {isMessage = 1}- if err := batch.Append(est.ProjectId, est.TransactionId, est.ExceptionHash, est.StackTrace, est.RecordedAt, scopeJSON, est.AppVersion, est.ServerName, isMessage); err != nil {+ transactionType := est.TransactionType+ if transactionType == "" {+ transactionType = "endpoint"+ }+ if err := batch.Append(est.ProjectId, est.TransactionId, transactionType, est.ExceptionHash, est.StackTrace, est.RecordedAt, scopeJSON, est.AppVersion, est.ServerName, isMessage); err != nil {return err}}@@ -140,7 +144,7 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectI// Get individual occurrences with pagination (including scope)rows, err := (*chdb.Conn).Query(ctx,- "SELECT project_id, transaction_id, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_message FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",+ "SELECT project_id, transaction_id, transaction_type, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_message 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@@ -152,7 +156,7 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectIvar o models.ExceptionStackTracevar scopeJSON stringvar isMessage uint8- if err := rows.Scan(&o.ProjectId, &o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt, &scopeJSON, &o.AppVersion, &o.ServerName, &isMessage); err != nil {+ if err := rows.Scan(&o.ProjectId, &o.TransactionId, &o.TransactionType, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt, &scopeJSON, &o.AppVersion, &o.ServerName, &isMessage); err != nil {return nil, nil, 0, err}o.IsMessage = isMessage == 1@@ -308,12 +312,12 @@ func (e *exceptionStackTraceRepository) FindByTransactionId(ctx context.Context,var isMessage uint8err := (*chdb.Conn).QueryRow(ctx,- `SELECT project_id, transaction_id, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_message+ `SELECT project_id, transaction_id, transaction_type, exception_hash, stack_trace, recorded_at, scope, app_version, server_name, is_messageFROM exception_stack_tracesWHERE project_id = ? AND transaction_id = ?LIMIT 1`,projectId, transactionId).Scan(- &est.ProjectId, &est.TransactionId, &est.ExceptionHash, &est.StackTrace,+ &est.ProjectId, &est.TransactionId, &est.TransactionType, &est.ExceptionHash, &est.StackTrace,&est.RecordedAt, &scopeJSON, &est.AppVersion, &est.ServerName, &isMessage)if err != nil {diff --git a/backend/app/repositories/task.repository.go b/backend/app/repositories/task.repository.gonew file mode 100644index 00000000..42a76417--- /dev/null+++ b/backend/app/repositories/task.repository.go@@ -0,0 +1,415 @@+package repositories++import (+ "backend/app/chdb"+ "backend/app/models"+ "context"+ "encoding/json"+ "time"++ "github.com/ClickHouse/clickhouse-go/v2"+)++type taskRepository struct{}++func (e *taskRepository) InsertAsync(ctx context.Context, lines []models.Task) error {+ batch, err := (*chdb.Conn).PrepareBatch(clickhouse.Context(context.Background(), clickhouse.WithAsync(false)), "INSERT INTO tasks (id, project_id, task_name, duration, recorded_at, client_ip, scope, app_version, server_name)")+ if err != nil {+ return err+ }+ for _, t := range lines {+ scopeJSON := "{}"+ if len(t.Scope) != 0 {+ if scopeBytes, err := json.Marshal(t.Scope); err == nil {+ scopeJSON = string(scopeBytes)+ }+ }+ if err := batch.Append(t.Id, t.ProjectId, t.TaskName, t.Duration, t.RecordedAt, t.ClientIP, scopeJSON, t.AppVersion, t.ServerName); err != nil {+ return err+ }+ }+ return batch.Send()+}++func (e *taskRepository) CountBetween(ctx context.Context, projectId string, start, end time.Time) (int64, error) {+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, start, end).Scan(&count)+ return int64(count), err+}++func (e *taskRepository) FindAll(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Task, int64, error) {+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ }++ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ query := "SELECT id, project_id, task_name, duration, recorded_at, client_ip, scope, app_version, server_name FROM tasks 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+ }+ defer rows.Close()++ var tasks []models.Task+ for rows.Next() {+ var t models.Task+ var scopeJSON string+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.TaskName, &t.Duration, &t.RecordedAt, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); 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+ }+ }+ tasks = append(tasks, t)+ }++ return tasks, int64(count), nil+}++func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.TaskStats, int64, error) {+ // Count unique task names+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(task_name) FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ // 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)",+ }++ orderExpr, ok := orderByMap[orderBy]+ if !ok {+ orderExpr = orderByMap["impact"] // Default to impact expression+ }++ // Validate sort direction+ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ query := `SELECT+ task_name,+ 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 tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY task_name+ ORDER BY ` + orderExpr + ` ` + sortDir + `+ LIMIT ? OFFSET ?`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, fromDate, toDate, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var stats []models.TaskStats+ for rows.Next() {+ var s models.TaskStats+ var p50, p95, avg float64+ if err := rows.Scan(&s.TaskName, &s.Count, &p50, &p95, &avg, &s.LastSeen); err != nil {+ return nil, 0, err+ }+ s.P50Duration = time.Duration(p50)+ s.P95Duration = time.Duration(p95)+ s.AvgDuration = time.Duration(avg)+ stats = append(stats, s)+ }++ return stats, int64(count), nil+}++func (e *taskRepository) FindByTaskName(ctx context.Context, projectId string, taskName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Task, int64, error) {+ var count uint64+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, taskName, fromDate, toDate).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ }++ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ // Validate sort direction+ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ query := "SELECT id, project_id, task_name, duration, recorded_at, client_ip, scope, app_version, server_name FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, taskName, fromDate, toDate, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var tasks []models.Task+ for rows.Next() {+ var t models.Task+ var scopeJSON string+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.TaskName, &t.Duration, &t.RecordedAt, &t.ClientIP, &scopeJSON, &t.AppVersion, &t.ServerName); 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+ }+ }+ tasks = append(tasks, t)+ }++ return tasks, int64(count), nil+}++// FindById returns a single task by ID+func (e *taskRepository) FindById(ctx context.Context, projectId, taskId string) (*models.Task, error) {+ query := `SELECT id, project_id, task_name, duration, recorded_at, client_ip, scope, app_version, server_name+ FROM tasks+ WHERE project_id = ? AND id = ?+ LIMIT 1`++ var t models.Task+ var scopeJSON string++ err := (*chdb.Conn).QueryRow(ctx, query, projectId, taskId).Scan(+ &t.Id, &t.ProjectId, &t.TaskName, &t.Duration, &t.RecordedAt,+ &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 task counts grouped by hour+func (e *taskRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ toFloat64(count()) as count+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// AvgDurationByHour returns average duration in ms grouped by hour+func (e *taskRepository) AvgDurationByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfHour(recorded_at) as hour,+ avg(duration) / 1000000 as avg_duration_ms+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// CountByInterval returns task counts grouped by configurable interval in minutes+func (e *taskRepository) CountByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,+ toFloat64(count()) as count+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// AvgDurationByInterval returns average duration in ms grouped by configurable interval+func (e *taskRepository) AvgDurationByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,+ avg(duration) / 1000000 as avg_duration_ms+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`++ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {+ return nil, err+ }+ points = append(points, p)+ }++ return points, nil+}++// FindWorstTasks returns tasks ordered by impact score (count * variance)+func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId string, start, end time.Time, limit int) ([]models.TaskStats, error) {+ query := `SELECT+ task_name,+ 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 tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY task_name+ 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.TaskStats+ for rows.Next() {+ var s models.TaskStats+ var p50, p95, avg float64+ if err := rows.Scan(&s.TaskName, &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+}++// GetTaskStats returns aggregate statistics for a specific task+func (e *taskRepository) GetTaskStats(ctx context.Context, projectId, taskName string, start, end time.Time) (*models.TaskDetailStats, error) {+ // Calculate time range duration for throughput calculation+ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ query := `SELECT+ count() as count,+ avg(duration) / 1000000 as avg_duration_ms,+ quantile(0.5)(duration) / 1000000 as p50_duration_ms,+ quantile(0.95)(duration) / 1000000 as p95_duration_ms,+ quantile(0.99)(duration) / 1000000 as p99_duration_ms+ FROM tasks+ WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ?`++ var stats models.TaskDetailStats+ var count uint64++ err := (*chdb.Conn).QueryRow(ctx, query, projectId, taskName, start, end).Scan(+ &count,+ &stats.AvgDuration,+ &stats.MedianDuration,+ &stats.P95Duration,+ &stats.P99Duration,+ )+ if err != nil {+ return nil, err+ }++ stats.Count = int64(count)+ // Calculate throughput (tasks per minute)+ stats.Throughput = float64(count) / durationMinutes++ return &stats, nil+}++var TaskRepository = taskRepository{}diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelteindex 19607b7e..5f1c9350 100644--- a/frontend/src/lib/components/app-sidebar.svelte+++ b/frontend/src/lib/components/app-sidebar.svelte@@ -6,12 +6,13 @@import { LayoutDashboard } from "@lucide/svelte";import { page } from '$app/state';import { createRowClickHandler } from "$lib/utils/navigation";- import { Gauge } from "lucide-svelte";+ import { Gauge, ListTodo } from "lucide-svelte";const sidebarItems = [{Icon: LayoutDashboard, href: "/", title: "Dashboard", stickyParams: [] as string[]},{Icon: Bug, href: "/issues", title: "Issues", stickyParams: [] as string[]},- {Icon: Gauge, href: "/transactions", title: "Transactions", stickyParams: ['presets', 'from', 'to']},+ {Icon: Gauge, href: "/endpoints", title: "Endpoints", stickyParams: ['presets', 'from', 'to']},+ {Icon: ListTodo, href: "/tasks", title: "Tasks", stickyParams: ['presets', 'from', 'to']},{Icon: ChartLine, href: "/metrics", title: "Metrics", stickyParams: ['presets', 'from', 'to']},{Icon: Link2, href: "/connection", title: "Connection", stickyParams: [] as string[]},]diff --git a/frontend/src/lib/components/issues/event-card.svelte b/frontend/src/lib/components/issues/event-card.svelteindex f075f427..52628d18 100644--- a/frontend/src/lib/components/issues/event-card.svelte+++ b/frontend/src/lib/components/issues/event-card.svelte@@ -67,13 +67,16 @@{#if linkedTransaction}<hr class="border-border" /><div>- <p class="text-sm font-medium mb-3">Related Transaction</p>+ <p class="text-sm font-medium mb-3">+ {linkedTransaction.transactionType === 'task' ? 'Related Task' : 'Related Endpoint'}+ </p><div class="grid grid-cols-2 gap-4 md:grid-cols-4 mb-4"><LabelValue- label="Endpoint"+ label={linkedTransaction.transactionType === 'task' ? 'Task' : 'Endpoint'}value={linkedTransaction.endpoint}mono/>+ {#if linkedTransaction.transactionType !== 'task'}<LabelValuelabel="Status"value={linkedTransaction.statusCode}@@ -81,6 +84,7 @@largevalueClass={getStatusColor(linkedTransaction.statusCode)}/>+ {/if}<LabelValuelabel="Duration"value={formatDuration(linkedTransaction.duration)}@@ -93,10 +97,17 @@mono/></div>- <Button variant="outline" size="sm" onclick={() => goto(`/transactions/${encodeURIComponent(linkedTransaction.endpoint)}/${linkedTransaction.id}?preset=24h`)}>- View Transaction Details+ {#if linkedTransaction.transactionType === 'task'}+ <Button variant="outline" size="sm" onclick={() => goto(`/tasks/${encodeURIComponent(linkedTransaction.endpoint)}/${linkedTransaction.id}?preset=24h`)}>+ View Task Details<ArrowRight class="ml-2 h-4 w-4" /></Button>+ {:else}+ <Button variant="outline" size="sm" onclick={() => goto(`/endpoints/${encodeURIComponent(linkedTransaction.endpoint)}/${linkedTransaction.id}?preset=24h`)}>+ View Endpoint Details+ <ArrowRight class="ml-2 h-4 w-4" />+ </Button>+ {/if}</div>{/if}</Card.Content>diff --git a/frontend/src/lib/types/exceptions.ts b/frontend/src/lib/types/exceptions.tsindex 794ef080..f651dc53 100644--- a/frontend/src/lib/types/exceptions.ts+++ b/frontend/src/lib/types/exceptions.ts@@ -8,6 +8,7 @@ export type ExceptionGroup = {export type ExceptionOccurrence = {transactionId: string | null;+ transactionType: 'endpoint' | 'task';exceptionHash: string;stackTrace: string;recordedAt: string;@@ -24,4 +25,5 @@ export type LinkedTransaction = {duration: number;statusCode: number;recordedAt: string;+ transactionType: 'endpoint' | 'task';};diff --git a/frontend/src/lib/utils/url-params.ts b/frontend/src/lib/utils/url-params.tsindex 045cb749..a26b0d3d 100644--- a/frontend/src/lib/utils/url-params.ts+++ b/frontend/src/lib/utils/url-params.ts@@ -3,6 +3,7 @@ import { goto } from '$app/navigation';import { CalendarDate } from '@internationalized/date';import { getNow, parseISO } from './formatters';+export const presetMinutes: Record<string, number> = {'30m': 30,'60m': 60,'3h': 180,diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex a9d35f70..39c38622 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -169,7 +169,7 @@<Table.Rowclass="cursor-pointer hover:bg-muted/50"onclick={createRowClickHandler(- `/transactions/${encodeURIComponent(endpoint.endpoint)}?preset=24h`+ `/endpoints/${encodeURIComponent(endpoint.endpoint)}?preset=24h`)}><Table.Cell@@ -192,7 +192,7 @@</Table.Cell></Table.Row>{/each}- <ViewAllTableRow colspan={5} href="/transactions" label="View all transactions" />+ <ViewAllTableRow colspan={5} href="/endpoints" label="View all endpoints" /></Table.Body>{:else}<Table.Body>diff --git a/frontend/src/routes/transactions/+page.svelte b/frontend/src/routes/endpoints/+page.sveltesimilarity index 97%rename from frontend/src/routes/transactions/+page.svelterename to frontend/src/routes/endpoints/+page.svelteindex 374b90a4..7cd1cea3 100644--- a/frontend/src/routes/transactions/+page.svelte+++ b/frontend/src/routes/endpoints/+page.svelte@@ -164,7 +164,7 @@}};- const response = await api.post('/transactions/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });+ const response = await api.post('/endpoints/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });endpoints = response.data || [];total = response.pagination.total;@@ -222,7 +222,7 @@<!-- Header with Title and Time Range Filter --><div class="flex flex-col gap-4 sm:flex-row sm:justify-between">- <PageHeader title="Transactions" />+ <PageHeader title="Endpoints" /><div class="flex flex-col"><TimeRangePicker@@ -259,7 +259,7 @@</Table.Body>{:else if endpoints.length === 0}<Table.Body>- <TableEmptyState colspan={5} message="No transaction data received yet" />+ <TableEmptyState colspan={5} message="No endpoint data received yet" /></Table.Body>{:else}<Table.Header>@@ -312,7 +312,7 @@{@const impactLevel = getImpactLevel(endpoint.count, endpoint.p50Duration, endpoint.p95Duration)}<Table.Rowclass="cursor-pointer hover:bg-muted/50"- onclick={createRowClickHandler(resolve(`/transactions/${encodeURIComponent(endpoint.endpoint)}`), 'preset', 'from', 'to')}+ onclick={createRowClickHandler(resolve(`/endpoints/${encodeURIComponent(endpoint.endpoint)}`), 'preset', 'from', 'to')}><Table.Cell class="font-mono text-sm">{endpoint.endpoint}diff --git a/frontend/src/routes/transactions/+page.ts b/frontend/src/routes/endpoints/+page.tssimilarity index 100%rename from frontend/src/routes/transactions/+page.tsrename to frontend/src/routes/endpoints/+page.tsdiff --git a/frontend/src/routes/transactions/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.sveltesimilarity index 96%rename from frontend/src/routes/transactions/[endpoint]/+page.svelterename to frontend/src/routes/endpoints/[endpoint]/+page.svelteindex ee3b0b3b..e3995b4f 100644--- a/frontend/src/routes/transactions/[endpoint]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte@@ -167,7 +167,7 @@}};- const response = await api.post(`/transactions/endpoint?endpoint=${encodeURIComponent(data.endpoint)}`, requestBody, { projectId: projectsState.currentProjectId ?? undefined });+ const response = await api.post(`/endpoints/endpoint?endpoint=${encodeURIComponent(data.endpoint)}`, requestBody, { projectId: projectsState.currentProjectId ?? undefined });transactions = response.data || [];stats = response.stats || null;@@ -223,7 +223,7 @@status={404}title="Endpoint Not Found"description="The endpoint you're looking for doesn't exist or has no recorded transactions."- onBack={createRowClickHandler(resolve('/transactions'), 'presets', 'from', 'to')}+ onBack={createRowClickHandler(resolve('/endpoints'), 'presets', 'from', 'to')}backLabel="Back to Transactions"onRetry={() => loadData(false)}identifier={decodeURIComponent(data.endpoint)}@@ -233,7 +233,7 @@status={errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}title="Failed to Load Transactions"description={error}- onBack={createRowClickHandler(resolve('/transactions'), 'presets', 'from', 'to')}+ onBack={createRowClickHandler(resolve('/endpoints'), 'presets', 'from', 'to')}backLabel="Back to Transactions"onRetry={() => loadData(false)}/>@@ -244,7 +244,7 @@<PageHeadertitle={decodeURIComponent(data.endpoint)}subtitle="Transaction instances for this endpoint"- onBack={createRowClickHandler(resolve("/transactions"), "presets", "from", "to")}+ onBack={createRowClickHandler(resolve("/endpoints"), "presets", "from", "to")}/><div class="flex flex-col">@@ -358,9 +358,9 @@<Table.Rowclass="cursor-pointer hover:bg-muted/50"onclick={createRowClickHandler(- resolve("/transactions/[endpoint]/[transactionId]", {+ resolve("/endpoints/[endpoint]/[endpointId]", {endpoint: data.endpoint,- transactionId: transaction.id,+ endpointId: transaction.id,}))}><Table.Cell class="text-muted-foreground">diff --git a/frontend/src/routes/transactions/[endpoint]/+page.ts b/frontend/src/routes/endpoints/[endpoint]/+page.tssimilarity index 100%rename from frontend/src/routes/transactions/[endpoint]/+page.tsrename to frontend/src/routes/endpoints/[endpoint]/+page.tsdiff --git a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.sveltesimilarity index 83%rename from frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.svelterename to frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelteindex 5b7a16c9..92570234 100644--- a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte@@ -35,7 +35,7 @@try {const result = await api.post(- `/transactions/${data.transactionId}`,+ `/endpoints/${data.endpointId}`,{},{ projectId: projectsState.currentProjectId ?? undefined });@@ -46,7 +46,7 @@if (err.status === 404) {notFound = true;} else {- error = err.message || 'Failed to load transaction details';+ error = err.message || 'Failed to load endpoint details';}} finally {loading = false;@@ -70,8 +70,8 @@<div class="space-y-6"><PageHeader- title={decodeURIComponent(data.endpoint)} subtitle={`Transaction ID: ${data.transactionId}`}- onBack={createRowClickHandler(resolve('/transactions/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))} />+ title={decodeURIComponent(data.endpoint)} subtitle={`Endpoint ID: ${data.endpointId}`}+ onBack={createRowClickHandler(resolve('/endpoints/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))} />{#if loading}@@ -81,28 +81,28 @@{:else if notFound}<ErrorDisplaystatus={404}- title="Transaction Not Found"- description="The transaction you're looking for doesn't exist or may have expired."- onBack={createRowClickHandler(resolve('/transactions/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))}+ title="Endpoint Not Found"+ description="The endpoint instance you're looking for doesn't exist or may have expired."+ onBack={createRowClickHandler(resolve('/endpoints/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))}backLabel="Back to Endpoint"onRetry={loadData}- identifier={data.transactionId}+ identifier={data.endpointId}/>{:else if error}<ErrorDisplaystatus={400}- title="Failed to Load Transaction"+ title="Failed to Load Endpoint"description={error}- onBack={createRowClickHandler(resolve('/transactions/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))}+ onBack={createRowClickHandler(resolve('/endpoints/[endpoint]', {endpoint: encodeURIComponent(data.endpoint)}))}backLabel="Back to Endpoint"onRetry={loadData}/>{:else if response}- <!-- Transaction Details Card -->+ <!-- Endpoint Details Card --><Card.Root><Card.Header>- <Card.Title>Transaction Details</Card.Title>- <Card.Description>Details of this specific transaction occurrence</Card.Description>+ <Card.Title>Endpoint Details</Card.Title>+ <Card.Description>Details of this specific endpoint occurrence</Card.Description></Card.Header><Card.Content class="space-y-6"><div class="grid grid-cols-2 gap-4 md:grid-cols-4">@@ -169,7 +169,7 @@<TriangleAlert class="h-5 w-5 text-red-500" /><Card.Title class="text-red-600 dark:text-red-400">Exception Occurred</Card.Title></div>- <Card.Description>This transaction resulted in an exception</Card.Description>+ <Card.Description>This endpoint request resulted in an exception</Card.Description></Card.Header><Card.Content><div class="mb-4 max-h-32 overflow-x-auto rounded-md bg-muted p-3">@@ -198,9 +198,9 @@<Card.Title>Segments</Card.Title><Card.Description>{#if response.hasSegments}- Timing breakdown of operations within this transaction+ Timing breakdown of operations within this endpoint request{:else}- No segments recorded for this transaction+ No segments recorded for this endpoint request{/if}</Card.Description></Card.Header>diff --git a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.ts b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.tssimilarity index 92%rename from frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.tsrename to frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.tsindex 6f3a3a72..17f47097 100644--- a/frontend/src/routes/transactions/[endpoint]/[transactionId]/+page.ts+++ b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.ts@@ -11,7 +11,7 @@ export const load: PageLoad = ({ params, url }) => {return {endpoint: params.endpoint,- transactionId: params.transactionId,+ endpointId: params.endpointId,preset: url.searchParams.get('preset') || null,from: url.searchParams.get('from') || null,to: url.searchParams.get('to') || nulldiff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelteindex 24e37846..e436298d 100644--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte@@ -54,18 +54,22 @@const firstOccurrence = occurrences[0];if (firstOccurrence?.transactionId) {try {+ const isTask = firstOccurrence.transactionType === 'task';+ const endpoint = isTask ? '/tasks' : '/endpoints';const txResponse = await api.post(- `/transactions/${firstOccurrence.transactionId}`,+ `${endpoint}/${firstOccurrence.transactionId}`,{},{ projectId: projectsState.currentProjectId ?? undefined });- if (txResponse.transaction) {+ const txData = isTask ? txResponse.task : txResponse.transaction;+ if (txData) {linkedTransaction = {- id: txResponse.transaction.id,- endpoint: txResponse.transaction.endpoint,- duration: txResponse.transaction.duration,- statusCode: txResponse.transaction.statusCode,- recordedAt: txResponse.transaction.recordedAt+ id: txData.id,+ endpoint: isTask ? txData.taskName : txData.endpoint,+ duration: txData.duration,+ statusCode: txData.statusCode || 0,+ recordedAt: txData.recordedAt,+ transactionType: isTask ? 'task' : 'endpoint'};}} catch (txError) {diff --git a/frontend/src/routes/issues/[exceptionHash]/[recordedAt]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/[recordedAt]/+page.svelteindex db3479ce..5d6f9618 100644--- a/frontend/src/routes/issues/[exceptionHash]/[recordedAt]/+page.svelte+++ b/frontend/src/routes/issues/[exceptionHash]/[recordedAt]/+page.svelte@@ -64,18 +64,22 @@// Load linked transaction if this occurrence has a transactionIdif (occurrence.transactionId) {try {+ const isTask = occurrence.transactionType === 'task';+ const endpoint = isTask ? '/tasks' : '/endpoints';const txResponse = await api.post(- `/transactions/${occurrence.transactionId}`,+ `${endpoint}/${occurrence.transactionId}`,{},{ projectId: projectsState.currentProjectId ?? undefined });- if (txResponse.transaction) {+ const txData = isTask ? txResponse.task : txResponse.transaction;+ if (txData) {linkedTransaction = {- id: txResponse.transaction.id,- endpoint: txResponse.transaction.endpoint,- duration: txResponse.transaction.duration,- statusCode: txResponse.transaction.statusCode,- recordedAt: txResponse.transaction.recordedAt+ id: txData.id,+ endpoint: isTask ? txData.taskName : txData.endpoint,+ duration: txData.duration,+ statusCode: txData.statusCode || 0,+ recordedAt: txData.recordedAt,+ transactionType: isTask ? 'task' : 'endpoint'};}} catch (txError) {diff --git a/frontend/src/routes/tasks/+page.svelte b/frontend/src/routes/tasks/+page.sveltenew file mode 100644index 00000000..072fc9af--- /dev/null+++ b/frontend/src/routes/tasks/+page.svelte@@ -0,0 +1,312 @@+<script lang="ts">+ import { onMount, onDestroy } from 'svelte';+ import { api } from '$lib/api';+ import { formatDuration, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from "$lib/components/ui/table";+ import { LoadingCircle } from "$lib/components/ui/loading-circle";+ import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";+ import { TableEmptyState } from "$lib/components/ui/table-empty-state";+ import { PaginationFooter } from "$lib/components/ui/pagination-footer";+ import { TimeRangePicker } from "$lib/components/ui/time-range-picker";+ import { CalendarDate } from "@internationalized/date";+ import { projectsState } from '$lib/state/projects.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';+ import PageHeader from '$lib/components/issues/page-header.svelte';+ import {+ presetMinutes,+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ parseTimeRangeFromUrl,+ getResolvedTimeRange,+ updateUrl+ } from '$lib/utils/url-params';++ const timezone = $derived(getTimezone());++ type TaskStats = {+ taskName: string;+ count: number;+ p50Duration: number;+ p95Duration: number;+ avgDuration: number;+ lastSeen: string;+ };++ type SortField = 'count' | 'p50_duration' | 'p95_duration' | 'last_seen';+ type SortDirection = 'asc' | 'desc';++ let tasks = $state<TaskStats[]>([]);+ let loading = $state(true);+ let error = $state('');++ // Pagination State+ let page = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ // Initialize from URL+ const initialUrlParams = parseTimeRangeFromUrl(timezone);+ const initialRange = getResolvedTimeRange(initialUrlParams, timezone);++ // Date Range State+ 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 updateTimeRangeUrl(pushToHistory = true) {+ updateUrl(+ selectedPreset+ ? { preset: selectedPreset }+ : { from: getFromDateTimeUTC(), to: getToDateTimeUTC() },+ { pushToHistory }+ );+ }++ // Handle browser back/forward navigation+ function handlePopState() {+ const urlParams = parseTimeRangeFromUrl(timezone);+ const range = getResolvedTimeRange(urlParams, timezone);++ selectedPreset = urlParams.preset;+ fromDate = dateToCalendarDate(range.from);+ fromTime = dateToTimeString(range.from);+ toDate = dateToCalendarDate(range.to);+ toTime = dateToTimeString(range.to);++ page = 1;+ loadData(false);+ }++ // Sorting - default to count descending+ let orderBy = $state<SortField>('count');+ let sortDirection = $state<SortDirection>('desc');++ // Combine date and time into UTC ISO datetime string+ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone);+ return toUTCISO(dt);+ }++ 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(true);+ }++ // Format count with k/m suffixes+ function formatCount(count: number): string {+ if (count >= 1_000_000) {+ return `${(count / 1_000_000).toFixed(1)}m`;+ } else if (count >= 1_000) {+ return `${(count / 1_000).toFixed(1)}k`;+ }+ return count.toLocaleString();+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';++ // Update URL+ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ }+ };++ const response = await api.post('/tasks/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });++ tasks = response.data || [];+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ error = e.message || 'Failed to load data';+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false); // Don't push to history for pagination+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false); // Don't push to history for pagination+ }++ function handleSort(field: SortField) {+ if (orderBy === field) {+ // Toggle direction if clicking the same field+ sortDirection = sortDirection === 'desc' ? 'asc' : 'desc';+ } else {+ // New field, default to descending+ orderBy = field;+ sortDirection = 'desc';+ }+ page = 1;+ loadData(false); // Don't push to history for sorting+ }++ onMount(() => {+ // 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>++<div class="space-y-4">+ <!-- Header with Title and Time Range Filter -->+ <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">++ <PageHeader title="Tasks" />++ <div class="flex flex-col">+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ </div>+ </div>++ <!-- Tasks Table -->+ <div class="rounded-md border overflow-hidden">+ <Table.Root>+ {#if loading}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-48">+ <div class="flex justify-center items-center h-full">+ <LoadingCircle size="xlg" />+ </div>+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if error}+ <Table.Body>+ <Table.Row>+ <Table.Cell colspan={4} class="h-24 text-center text-red-500">+ {error}+ </Table.Cell>+ </Table.Row>+ </Table.Body>+ {:else if tasks.length === 0}+ <Table.Body>+ <TableEmptyState colspan={4} message="No task data received yet" />+ </Table.Body>+ {:else}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Task"+ tooltip="The background job or task name"+ />+ <TracewayTableHeader+ label="Runs"+ tooltip="Total number of task executions"+ sortField="count"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Typical"+ tooltip="Median duration (P50)"+ sortField="p50_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ <TracewayTableHeader+ label="Slow"+ tooltip="95th percentile - slowest 5% of executions"+ sortField="p95_duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[100px]"+ />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each tasks as task}+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={createRowClickHandler(resolve(`/tasks/${encodeURIComponent(task.taskName)}`), 'preset', 'from', 'to')}+ >+ <Table.Cell class="font-mono text-sm">+ {task.taskName}+ </Table.Cell>+ <Table.Cell class="tabular-nums">+ {formatCount(task.count)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(task.p50Duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm tabular-nums">+ {formatDuration(task.p95Duration)}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ {/if}+ </Table.Root>+ </div>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="task"+ />+</div>diff --git a/frontend/src/routes/tasks/+page.ts b/frontend/src/routes/tasks/+page.tsnew file mode 100644index 00000000..9f2ce0c4--- /dev/null+++ b/frontend/src/routes/tasks/+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/tasks/[task]/+page.svelte b/frontend/src/routes/tasks/[task]/+page.sveltenew file mode 100644index 00000000..17175882--- /dev/null+++ b/frontend/src/routes/tasks/[task]/+page.svelte@@ -0,0 +1,363 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { api } from '$lib/api';+ import { formatDuration, formatDurationMs, formatDateTime, parseISO, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import * as Table from "$lib/components/ui/table";+ import { LoadingCircle } from "$lib/components/ui/loading-circle";+ import { TimeRangePicker } from "$lib/components/ui/time-range-picker";+ import { TracewayTableHeader } from "$lib/components/ui/traceway-table-header";+ import { TableEmptyState } from "$lib/components/ui/table-empty-state";+ import { CalendarDate } 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';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import PaginationFooter from '$lib/components/ui/pagination-footer/pagination-footer.svelte';+ import PageHeader from '$lib/components/issues/page-header.svelte';+ import { resolve } from '$app/paths';+ import {+ presetMinutes,+ getTimeRangeFromPreset,+ dateToCalendarDate,+ dateToTimeString,+ updateUrl+ } from '$lib/utils/url-params';++ const timezone = $derived(getTimezone());++ type Task = {+ id: string;+ taskName: string;+ duration: number;+ recordedAt: string;+ clientIP: string;+ scope: Record<string, string> | null;+ serverName: string;+ appVersion: string;+ };++ type TaskStats = {+ count: number;+ avgDuration: number;+ medianDuration: number;+ p95Duration: number;+ p99Duration: number;+ throughput: number;+ };++ type SortField = 'recorded_at' | 'duration';+ type SortDirection = 'asc' | 'desc';++ let { data } = $props();++ let tasks = $state<Task[]>([]);+ let stats = $state<TaskStats | null>(null);+ let loading = $state(true);+ let error = $state('');+ let notFound = $state(false);+ let errorStatus = $state<number>(0);++ // Pagination State+ let page = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ // Initialize from URL params (from page data)+ 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, timezone);+ return { preset: data.preset, from: range.from, to: range.to };+ }++ // If custom from/to provided+ if (data.from && data.to) {+ const fromDt = parseISO(data.from, timezone);+ const toDt = parseISO(data.to, timezone);+ if (fromDt.isValid && toDt.isValid) {+ return { preset: null, from: fromDt.toJSDate(), to: toDt.toJSDate() };+ }+ }++ // Default to 6h preset+ const range = getTimeRangeFromPreset('6h', timezone);+ return { preset: '6h', from: range.from, to: range.to };+ }++ const initialRange = getInitialRange();++ // Date Range State+ 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));++ function updateTimeRangeUrl(pushToHistory = true) {+ updateUrl(+ selectedPreset+ ? { preset: selectedPreset }+ : { from: getFromDateTimeUTC(), to: getToDateTimeUTC() },+ { pushToHistory }+ );+ }++ // Sorting State+ let orderBy = $state<SortField>('recorded_at');+ let sortDirection = $state<SortDirection>('desc');++ // Combine date and time into UTC ISO datetime string+ function getFromDateTimeUTC(): string {+ const [hour, minute] = (fromTime || '00:00').split(':').map(Number);+ const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute }, timezone);+ return toUTCISO(dt);+ }++ function getToDateTimeUTC(): string {+ const [hour, minute] = (toTime || '23:59').split(':').map(Number);+ const dt = calendarDateTimeToLuxon({ year: toDate.year, month: toDate.month, day: toDate.day, hour, minute }, timezone);+ return toUTCISO(dt);+ }++ 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();+ }++ async function loadData(pushToHistory = true) {+ loading = true;+ error = '';+ notFound = false;+ errorStatus = 0;++ updateTimeRangeUrl(pushToHistory);++ try {+ const requestBody = {+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ orderBy: orderBy,+ sortDirection: sortDirection,+ pagination: {+ page: page,+ pageSize: pageSize+ }+ };++ const response = await api.post(`/tasks/task?task=${encodeURIComponent(data.task)}`, requestBody, { projectId: projectsState.currentProjectId ?? undefined });++ tasks = response.data || [];+ stats = response.stats || null;+ total = response.pagination.total;+ totalPages = response.pagination.totalPages;+ } catch (e: any) {+ console.error(e);+ errorStatus = e.status || 0;+ if (e.status === 404) {+ notFound = true;+ } else {+ error = e.message || 'Failed to load data';+ }+ } finally {+ loading = false;+ }+ }++ function handlePageChange(newPage: number) {+ if (newPage >= 1 && newPage <= totalPages) {+ page = newPage;+ loadData(false);+ }+ }++ function handlePageSizeChange(newPageSize: number) {+ pageSize = newPageSize;+ page = 1;+ loadData(false); // Don't push to history for pagination+ }++ function handleSort(field: SortField) {+ if (orderBy === field) {+ // Toggle direction if clicking the same field+ sortDirection = sortDirection === 'desc' ? 'asc' : 'desc';+ } else {+ // New field, default to descending+ orderBy = field;+ sortDirection = 'desc';+ }+ page = 1;+ loadData(false);+ }++ onMount(() => {+ loadData(false);+ });+</script>++<div class="space-y-6">+ {#if notFound}+ <ErrorDisplay+ status={404}+ title="Task Not Found"+ description="The task you're looking for doesn't exist or has no recorded executions."+ onBack={createRowClickHandler(resolve('/tasks'), 'presets', 'from', 'to')}+ backLabel="Back to Tasks"+ onRetry={() => loadData(false)}+ identifier={decodeURIComponent(data.task)}+ />+ {:else if error && !loading}+ <ErrorDisplay+ status={errorStatus === 400 ? 400 : errorStatus === 422 ? 422 : 400}+ title="Failed to Load Tasks"+ description={error}+ onBack={createRowClickHandler(resolve('/tasks'), 'presets', 'from', 'to')}+ backLabel="Back to Tasks"+ onRetry={() => loadData(false)}+ />+ {:else}+ <!-- Header with Title and Time Range Filter -->+ <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">++ <PageHeader+ title={decodeURIComponent(data.task)}+ subtitle="Task instances"+ onBack={createRowClickHandler(resolve("/tasks"), "presets", "from", "to")}+ />++ <div class="flex flex-col">+ <TimeRangePicker+ bind:fromDate+ bind:toDate+ bind:fromTime+ bind:toTime+ bind:preset={selectedPreset}+ onApply={handleTimeRangeChange}+ />+ </div>+ </div>++ <!-- Task Stats -->+ {#if stats}+ <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">+ <div class="space-y-1">+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.avgDuration)}</p>+ <p class="text-xs text-muted-foreground">Average duration</p>+ </div>+ <div class="space-y-1">+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.medianDuration)}</p>+ <p class="text-xs text-muted-foreground">Median duration</p>+ </div>+ <div class="space-y-1">+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p95Duration)}</p>+ <p class="text-xs text-muted-foreground">95th percentile</p>+ </div>+ <div class="space-y-1">+ <p class="text-2xl font-semibold tracking-tight">{formatDurationMs(stats.p99Duration)}</p>+ <p class="text-xs text-muted-foreground">99th percentile</p>+ </div>+ <div class="space-y-1">+ <p class="text-2xl font-semibold tracking-tight">{stats.throughput.toFixed(0)} rpm</p>+ <p class="text-xs text-muted-foreground">Average throughput</p>+ </div>+ </div>+ {:else if loading}+ <div class="flex items-center justify-center py-8">+ <LoadingCircle size="lg" />+ </div>+ {/if}++ <!-- Tasks Table -->+ <div class="rounded-md border overflow-hidden">+ <Table.Root>+ {#if loading || tasks.length > 0}+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Recorded At"+ sortField="recorded_at"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[180px]"+ />+ <TracewayTableHeader+ label="Duration"+ sortField="duration"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[120px]"+ />+ <TracewayTableHeader label="Client IP" class="w-[140px]" />+ <TracewayTableHeader label="Server" class="w-[120px]" />+ <TracewayTableHeader label="Version" class="w-[100px]" />+ <TracewayTableHeader label="Context" />+ </Table.Row>+ </Table.Header>+ {/if}+ <Table.Body>+ {#if loading}+ <Table.Row>+ <Table.Cell colspan={6} class="h-48">+ <div class="flex items-center justify-center">+ <LoadingCircle size="lg" />+ </div>+ </Table.Cell>+ </Table.Row>+ {:else if tasks.length === 0}+ <TableEmptyState colspan={6} message="No tasks found in this time range." />+ {:else}+ {#each tasks as task}+ <Table.Row+ class="cursor-pointer hover:bg-muted/50"+ onclick={createRowClickHandler(+ resolve("/tasks/[task]/[taskId]", {+ task: data.task,+ taskId: task.id,+ }))}+ >+ <Table.Cell class="text-muted-foreground">+ {formatDateTime(task.recordedAt, { timezone })}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm">+ {formatDuration(task.duration)}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {task.clientIP}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {task.serverName || '-'}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground">+ {task.appVersion || '-'}+ </Table.Cell>+ <Table.Cell>+ <ScopeDisplay scope={task.scope} />+ </Table.Cell>+ </Table.Row>+ {/each}+ {/if}+ </Table.Body>+ </Table.Root>+ </div>++ <!-- Pagination Footer -->+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={handlePageChange}+ onPageSizeChange={handlePageSizeChange}+ {loading}+ itemLabel="task"+ />+ {/if}+</div>diff --git a/frontend/src/routes/tasks/[task]/+page.ts b/frontend/src/routes/tasks/[task]/+page.tsnew file mode 100644index 00000000..1688386c--- /dev/null+++ b/frontend/src/routes/tasks/[task]/+page.ts@@ -0,0 +1,18 @@+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 {+ task: params.task,+ preset: url.searchParams.get('preset') || null,+ from: url.searchParams.get('from') || null,+ to: url.searchParams.get('to') || null+ };+};diff --git a/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte b/frontend/src/routes/tasks/[task]/[taskId]/+page.sveltenew file mode 100644index 00000000..531edc17--- /dev/null+++ b/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte@@ -0,0 +1,216 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { goto } from '$app/navigation';+ import { api } from '$lib/api';+ import { formatDuration, formatDateTime } from '$lib/utils/formatters';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { Button } from '$lib/components/ui/button';+ import * as Card from '$lib/components/ui/card';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { ErrorDisplay } from '$lib/components/ui/error-display';+ import { projectsState } from '$lib/state/projects.svelte';+ import { ArrowRight, TriangleAlert } from 'lucide-svelte';+ import { LabelValue } from '$lib/components/ui/label-value';+ import { ContextGrid } from '$lib/components/ui/context-grid';+ import SegmentWaterfall from '$lib/components/segments/segment-waterfall.svelte';+ import SegmentEmptyState from '$lib/components/segments/segment-empty-state.svelte';+ import PageHeader from '$lib/components/issues/page-header.svelte';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { resolve } from '$app/paths';++ type TaskDetailResponse = {+ task: {+ id: string;+ taskName: string;+ duration: number;+ recordedAt: string;+ clientIP: string;+ scope: Record<string, string> | null;+ serverName: string;+ appVersion: string;+ };+ exception?: {+ exceptionHash: string;+ stackTrace: string;+ };+ segments: any[];+ hasSegments: boolean;+ };++ let { data } = $props();++ const timezone = $derived(getTimezone());++ let response = $state<TaskDetailResponse | 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(+ `/tasks/${data.taskId}`,+ {},+ { 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 task details';+ }+ } finally {+ loading = false;+ }+ }++ onMount(() => {+ loadData();+ });+</script>++<div class="space-y-6">+ <PageHeader+ title={decodeURIComponent(data.task)} subtitle={`Task ID: ${data.taskId}`}+ onBack={createRowClickHandler(resolve('/tasks/[task]', {task: encodeURIComponent(data.task)}))} />+++ {#if loading}+ <div class="flex items-center justify-center py-20">+ <LoadingCircle size="xlg" />+ </div>+ {:else if notFound}+ <ErrorDisplay+ status={404}+ title="Task Not Found"+ description="The task instance you're looking for doesn't exist or may have expired."+ onBack={createRowClickHandler(resolve('/tasks/[task]', {task: encodeURIComponent(data.task)}))}+ backLabel="Back to Task"+ onRetry={loadData}+ identifier={data.taskId}+ />+ {:else if error}+ <ErrorDisplay+ status={400}+ title="Failed to Load Task"+ description={error}+ onBack={createRowClickHandler(resolve('/tasks/[task]', {task: encodeURIComponent(data.task)}))}+ backLabel="Back to Task"+ onRetry={loadData}+ />+ {:else if response}+ <!-- Task Details Card -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Task Details</Card.Title>+ <Card.Description>Details of this specific task execution</Card.Description>+ </Card.Header>+ <Card.Content class="space-y-6">+ <div class="grid grid-cols-2 gap-4 md:grid-cols-4">+ <LabelValue+ label="Task"+ value={decodeURIComponent(data.task)}+ mono+ />+ <LabelValue+ label="Duration"+ value={formatDuration(response.task.duration)}+ mono+ large+ />+ <LabelValue+ label="Recorded At"+ value={formatDateTime(response.task.recordedAt, { timezone })}+ mono+ />+ <LabelValue+ label="Server"+ value={response.task.serverName}+ mono+ />+ <LabelValue+ label="Version"+ value={response.task.appVersion}+ mono+ />+ <LabelValue+ label="Client IP"+ value={response.task.clientIP}+ mono+ />+ </div>++ {#if response.task.scope && Object.keys(response.task.scope).length > 0}+ <hr class="border-border" />+ <div>+ <p class="mb-3 text-sm font-medium">Context (Scope)</p>+ <ContextGrid scope={response.task.scope} />+ </div>+ {/if}+ </Card.Content>+ </Card.Root>++ <!-- Exception Card (if exception exists) -->+ {#if response.exception}+ <Card.Root class="border-red-500/30 bg-red-500/5">+ <Card.Header>+ <div class="flex items-center gap-2">+ <TriangleAlert class="h-5 w-5 text-red-500" />+ <Card.Title class="text-red-600 dark:text-red-400">Exception Occurred</Card.Title>+ </div>+ <Card.Description>This task execution resulted in an exception</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="mb-4 max-h-32 overflow-x-auto rounded-md bg-muted p-3">+ <pre class="font-mono text-sm whitespace-pre-wrap">{response.exception.stackTrace+ .split('\n')+ .slice(0, 4)+ .join('\n')}{response.exception.stackTrace.split('\n').length > 4+ ? '\n...'+ : ''}</pre>+ </div>+ <Button+ variant="outline"+ size="sm"+ onclick={() => goto(`/issues/${response!.exception!.exceptionHash}`)}+ >+ View Full Exception+ <ArrowRight class="ml-2 h-4 w-4" />+ </Button>+ </Card.Content>+ </Card.Root>+ {/if}++ <!-- Segments Section -->+ <Card.Root>+ <Card.Header>+ <Card.Title>Segments</Card.Title>+ <Card.Description>+ {#if response.hasSegments}+ Timing breakdown of operations within this task+ {:else}+ No segments recorded for this task+ {/if}+ </Card.Description>+ </Card.Header>+ <Card.Content>+ {#if response.hasSegments}+ <SegmentWaterfall+ segments={response.segments}+ transactionDuration={response.task.duration}+ transactionStartTime={response.task.recordedAt}+ />+ {:else}+ <SegmentEmptyState framework={projectsState.currentProject?.framework ?? 'gin'} />+ {/if}+ </Card.Content>+ </Card.Root>+ {/if}+</div>diff --git a/frontend/src/routes/tasks/[task]/[taskId]/+page.ts b/frontend/src/routes/tasks/[task]/[taskId]/+page.tsnew file mode 100644index 00000000..cea16c7e--- /dev/null+++ b/frontend/src/routes/tasks/[task]/[taskId]/+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 {+ task: params.task,+ taskId: params.taskId,+ preset: url.searchParams.get('preset') || null,+ from: url.searchParams.get('from') || null,+ to: url.searchParams.get('to') || null+ };+};