The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: org level overview + k8s support (#298)
narrow-adventure63a0ca93ab6c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 520151cb..8279cf35 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -678,7 +678,7 @@ Dashboards are org-owned JSON documents (`{schemaVersion, widgets: [{id, title,| POST | `/api/dashboards/populate-defaults` | App+Write | Install the framework-default template set for an empty project || GET | `/api/metrics/discover/org` | App | Metric names across all org projects (command palette) |-Templates are DB rows seeded by migrations (`traceway-otel-agent` for the OTel host agent, `golang` for Go SDK apps, `traceway-clickhouse`/`traceway-duckdb` for the telemetry stores of a monitored Traceway instance; SQLite emits no store-specific metrics so it has no template); cloud can insert more rows without a release. The OTLP metric ingest allowlists per-resource grouping tags (`container.name`, `k8s.pod.name`, `k8s.node.name`, `postgresql.database.name`, ...) in `otelcontrollers/metric_converter.go` for custom widgets.+Templates are DB rows seeded by migrations (`traceway-otel-agent` for the OTel host agent, `golang` for Go SDK apps, `traceway-clickhouse`/`traceway-duckdb` for the telemetry stores of a monitored Traceway instance; SQLite emits no store-specific metrics so it has no template); cloud can insert more rows without a release. The OTLP metric ingest allowlists per-resource identity and grouping tags (`host.name`, `host.id`, `os.type`, `cloud.region`, `container.name`, `k8s.cluster.name`, `k8s.pod.name`, `k8s.node.name`, `postgresql.database.name`, ...) in `otelcontrollers/metric_converter.go` for infrastructure views and custom widgets.**Endpoints**| Method | Endpoint | Auth | Purpose |diff --git a/backend/app/controllers/metric_query.controller.go b/backend/app/controllers/metric_query.controller.goindex ec4d68ec..30e7bf8a 100644--- a/backend/app/controllers/metric_query.controller.go+++ b/backend/app/controllers/metric_query.controller.go@@ -118,13 +118,11 @@ type DiscoverResponse struct {Metrics []models.DiscoveredMetric `json:"metrics"`}-func (c *metricQueryController) Discover(ctx *gin.Context) {- projectId, err := middleware.GetProjectId(ctx)- if err != nil {- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))- return- }+type DiscoverInstancesResponse struct {+ Instances []string `json:"instances"`+}+func parseMetricDiscoveryRange(ctx *gin.Context) (time.Time, time.Time) {from := time.Now().AddDate(0, 0, -7)to := time.Now()@@ -139,6 +137,18 @@ func (c *metricQueryController) Discover(ctx *gin.Context) {}}+ return from, to+}++func (c *metricQueryController) Discover(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ from, to := parseMetricDiscoveryRange(ctx)+span := traceway.StartSpan(ctx, "discover metrics")discovered, err := telemetry.MetricPointRepository.DiscoverMetrics(ctx, projectId, from, to)span.End()@@ -170,6 +180,28 @@ func (c *metricQueryController) Discover(ctx *gin.Context) {ctx.JSON(http.StatusOK, DiscoverResponse{Metrics: discovered})}+func (c *metricQueryController) DiscoverInstances(ctx *gin.Context) {+ projectId, err := middleware.GetProjectId(ctx)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ from, to := parseMetricDiscoveryRange(ctx)+ span := traceway.StartSpan(ctx, "discover instances")+ instances, err := telemetry.MetricPointRepository.GetDistinctServers(ctx, projectId, from, to)+ span.End()+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to discover instances: %w", err))+ return+ }+ if instances == nil {+ instances = []string{}+ }++ ctx.JSON(http.StatusOK, DiscoverInstancesResponse{Instances: instances})+}+const discoverOrgMaxProjects = 25type OrgDiscoveredMetric struct {diff --git a/backend/app/controllers/organization_overview.controller.go b/backend/app/controllers/organization_overview.controller.gonew file mode 100644index 00000000..a3e881c6--- /dev/null+++ b/backend/app/controllers/organization_overview.controller.go@@ -0,0 +1,494 @@+package controllers++import (+ "database/sql"+ "fmt"+ "math"+ "net/http"+ "sort"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ traceway "go.tracewayapp.com"+)++type organizationOverviewController struct{}++var OrganizationOverviewController = organizationOverviewController{}++const orgOverviewMaxIssues = 50+const orgOverviewMaxPages = 50++// orgOverviewProjects loads the organization's projects in one short+// transaction: the fan-out handlers run their telemetry queries outside any+// tx so the single-connection SQLite main DB is never held across them.+func orgOverviewProjects(organizationId int) ([]*models.Project, error) {+ projects, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.Project, error) {+ return transactional.ProjectRepository.FindByOrganizationId(tx, organizationId)+ })+ if err != nil {+ return nil, err+ }+ return projects, nil+}++type orgServerRow struct {+ ServerName string `json:"serverName"`+ ProjectId uuid.UUID `json:"projectId"`+ ProjectName string `json:"projectName"`+ CpuPct *float64 `json:"cpuPct"`+ MemoryPct *float64 `json:"memoryPct"`+ DiskPct *float64 `json:"diskPct"`+ NetworkRxBps *float64 `json:"networkRxBps"`+ NetworkTxBps *float64 `json:"networkTxBps"`+ LastReportedAt time.Time `json:"lastReportedAt"`+ Trend []models.TimeSeriesPoint `json:"trend"`+ TelemetrySource string `json:"telemetrySource"`+ DashboardId *int `json:"dashboardId"`+ HostName string `json:"hostName"`+ HostId string `json:"hostId"`+ HostArch string `json:"hostArch"`+ OsType string `json:"osType"`+ OsDescription string `json:"osDescription"`+ CloudProvider string `json:"cloudProvider"`+ CloudRegion string `json:"cloudRegion"`+ K8sClusterName string `json:"k8sClusterName"`+ K8sNodeName string `json:"k8sNodeName"`+}++func orgServerDashboardIds(organizationId int) (map[uuid.UUID]int, error) {+ return db.ExecuteTransaction(func(tx *sql.Tx) (map[uuid.UUID]int, error) {+ dashboards, err := transactional.DashboardRepository.FindByOrganization(tx, organizationId)+ if err != nil {+ return nil, err+ }+ assignments, err := transactional.DashboardRepository.FindAssignmentsByOrganization(tx, organizationId)+ if err != nil {+ return nil, err+ }++ serverDashboardIds := make(map[int]bool)+ for _, dashboard := range dashboards {+ if dashboard.TemplateKey != nil && *dashboard.TemplateKey == "traceway-otel-agent" {+ serverDashboardIds[dashboard.Id] = true+ }+ }++ result := make(map[uuid.UUID]int)+ for _, assignment := range assignments {+ if serverDashboardIds[assignment.DashboardId] && result[assignment.ProjectId] == 0 {+ result[assignment.ProjectId] = assignment.DashboardId+ }+ }+ return result, nil+ })+}++func clampPercent(value float64) float64 {+ return math.Max(0, math.Min(100, value))+}++func otelFractionToPercent(value float64) float64 {+ if value <= 1.5 {+ value *= 100+ }+ return clampPercent(value)+}++func pointerTo(value float64) *float64 {+ return &value+}++func lastSeriesValue(series map[string][]models.TimeSeriesPoint, serverName string) (float64, bool) {+ points := series[serverName]+ if len(points) == 0 {+ return 0, false+ }+ return points[len(points)-1].Value, true+}++func cpuUsageTrend(idle []models.TimeSeriesPoint) []models.TimeSeriesPoint {+ trend := make([]models.TimeSeriesPoint, 0, len(idle))+ for _, point := range idle {+ trend = append(trend, models.TimeSeriesPoint{+ Timestamp: point.Timestamp,+ Value: clampPercent(100 - otelFractionToPercent(point.Value)),+ })+ }+ return trend+}++func latestCounterRate(points []models.TimeSeriesPoint) (float64, bool) {+ if len(points) < 2 {+ return 0, false+ }+ previous := points[len(points)-2]+ latest := points[len(points)-1]+ seconds := latest.Timestamp.Sub(previous.Timestamp).Seconds()+ if seconds <= 0 {+ return 0, false+ }+ delta := latest.Value - previous.Value+ if delta < 0 {+ return 0, true+ }+ return delta / seconds, true+}++func applyServerMetadata(row *orgServerRow, tags map[string]string) {+ row.HostName = tags["host.name"]+ row.HostId = tags["host.id"]+ row.HostArch = tags["host.arch"]+ row.OsType = tags["os.type"]+ row.OsDescription = tags["os.description"]+ row.CloudProvider = tags["cloud.provider"]+ row.CloudRegion = tags["cloud.region"]+ row.K8sClusterName = tags["k8s.cluster.name"]+ row.K8sNodeName = tags["k8s.node.name"]+}++func loadProjectServerRows(ctx *gin.Context, project *models.Project, dashboardId int, since, now time.Time) ([]orgServerRow, error) {+ latestOtel, err := telemetry.MetricPointRepository.LatestPerServer(ctx, project.Id, models.MetricNameSystemCPUUtilization, since)+ if err != nil {+ return nil, err+ }+ latestSdk, err := telemetry.MetricPointRepository.LatestPerServer(ctx, project.Id, models.MetricNameCpuUsage, since)+ if err != nil {+ return nil, err+ }+ if len(latestOtel) == 0 && len(latestSdk) == 0 {+ return []orgServerRow{}, nil+ }++ rows := make(map[string]*orgServerRow, len(latestOtel)+len(latestSdk))+ for _, point := range latestOtel {+ row := &orgServerRow{+ ServerName: point.ServerName,+ ProjectId: project.Id,+ ProjectName: project.Name,+ LastReportedAt: point.LastReportedAt,+ Trend: []models.TimeSeriesPoint{},+ TelemetrySource: "otel",+ }+ if dashboardId > 0 {+ row.DashboardId = &dashboardId+ }+ applyServerMetadata(row, point.Tags)+ rows[point.ServerName] = row+ }+ for _, point := range latestSdk {+ if row := rows[point.ServerName]; row != nil {+ if point.LastReportedAt.After(row.LastReportedAt) {+ row.LastReportedAt = point.LastReportedAt+ }+ continue+ }+ row := &orgServerRow{+ ServerName: point.ServerName,+ ProjectId: project.Id,+ ProjectName: project.Name,+ LastReportedAt: point.LastReportedAt,+ Trend: []models.TimeSeriesPoint{},+ TelemetrySource: "sdk",+ }+ if dashboardId > 0 {+ row.DashboardId = &dashboardId+ }+ applyServerMetadata(row, point.Tags)+ rows[point.ServerName] = row+ }++ if len(latestOtel) > 0 {+ cpuIdle, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemCPUUtilization, since, now, 2, "avg", map[string]string{"state": "idle"}, "server_name")+ if err != nil {+ return nil, err+ }+ memoryUsed, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemMemoryUtilization, since, now, 2, "avg", map[string]string{"state": "used"}, "server_name")+ if err != nil {+ return nil, err+ }+ filesystemUsed, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemFilesystemUtilization, since, now, 2, "max", map[string]string{"state": "used"}, "server_name")+ if err != nil {+ return nil, err+ }+ networkReceive, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemNetworkIO, since, now, 1, "sum", map[string]string{"direction": "receive"}, "server_name")+ if err != nil {+ return nil, err+ }+ networkTransmit, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemNetworkIO, since, now, 1, "sum", map[string]string{"direction": "transmit"}, "server_name")+ if err != nil {+ return nil, err+ }++ for _, point := range latestOtel {+ row := rows[point.ServerName]+ row.Trend = cpuUsageTrend(cpuIdle[point.ServerName])+ if len(row.Trend) > 0 {+ row.CpuPct = pointerTo(row.Trend[len(row.Trend)-1].Value)+ }+ if value, ok := lastSeriesValue(memoryUsed, point.ServerName); ok {+ row.MemoryPct = pointerTo(otelFractionToPercent(value))+ }+ if value, ok := lastSeriesValue(filesystemUsed, point.ServerName); ok {+ row.DiskPct = pointerTo(otelFractionToPercent(value))+ }+ if value, ok := latestCounterRate(networkReceive[point.ServerName]); ok {+ row.NetworkRxBps = pointerTo(value)+ }+ if value, ok := latestCounterRate(networkTransmit[point.ServerName]); ok {+ row.NetworkTxBps = pointerTo(value)+ }+ }+ }++ if len(latestSdk) > 0 {+ serverNames := make([]string, 0, len(latestSdk))+ for _, point := range latestSdk {+ serverNames = append(serverNames, point.ServerName)+ }+ cpu, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(ctx, project.Id, models.MetricNameCpuUsage, since, now, 2, serverNames)+ if err != nil {+ return nil, err+ }+ memoryUsed, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(ctx, project.Id, models.MetricNameMemoryUsage, since, now, 2, serverNames)+ if err != nil {+ return nil, err+ }+ memoryTotal, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(ctx, project.Id, models.MetricNameMemoryTotal, since, now, 2, serverNames)+ if err != nil {+ return nil, err+ }++ for _, point := range latestSdk {+ row := rows[point.ServerName]+ if row.CpuPct == nil {+ row.Trend = cpu[point.ServerName]+ if value, ok := lastSeriesValue(cpu, point.ServerName); ok {+ row.CpuPct = pointerTo(clampPercent(value))+ }+ }+ used, hasUsed := lastSeriesValue(memoryUsed, point.ServerName)+ total, hasTotal := lastSeriesValue(memoryTotal, point.ServerName)+ if row.MemoryPct == nil && hasUsed && hasTotal && total > 0 {+ row.MemoryPct = pointerTo(clampPercent(used / total * 100))+ }+ }+ }++ result := make([]orgServerRow, 0, len(rows))+ for _, row := range rows {+ result = append(result, *row)+ }+ return result, nil+}++func (c *organizationOverviewController) Servers(ctx *gin.Context) {+ organizationId := middleware.GetOrganizationId(ctx)+ projects, err := orgOverviewProjects(organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization projects: %w", err))+ return+ }+ dashboardIds, err := orgServerDashboardIds(organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to resolve organization server dashboards: %w", err))+ return+ }++ now := time.Now().UTC()+ since := now.Add(-30 * time.Minute)+ servers := make([]orgServerRow, 0)+ partial := false+ for _, project := range projects {+ span := traceway.StartSpan(ctx, fmt.Sprintf("org overview servers: project %s", project.Id))+ projectServers, err := loadProjectServerRows(ctx, project, dashboardIds[project.Id], since, now)+ span.End()+ if err != nil {+ partial = true+ traceway.CaptureException(traceway.NewStackTraceErrorf("failed to load server metrics for project %s: %w", project.Id, err))+ continue+ }+ servers = append(servers, projectServers...)+ }++ sort.Slice(servers, func(i, j int) bool {+ return servers[i].LastReportedAt.After(servers[j].LastReportedAt)+ })++ ctx.JSON(http.StatusOK, gin.H{"servers": servers, "refreshedAt": now, "partial": partial})+}++type orgIssueRow struct {+ models.ExceptionGroup+ ProjectId uuid.UUID `json:"projectId"`+ ProjectName string `json:"projectName"`+}++func (c *organizationOverviewController) Issues(ctx *gin.Context) {+ organizationId := middleware.GetOrganizationId(ctx)+ projects, err := orgOverviewProjects(organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization projects: %w", err))+ return+ }++ now := time.Now().UTC()+ from := now.Add(-24 * time.Hour)++ issues := make([]orgIssueRow, 0)+ var totalGroups int64+ for _, project := range projects {+ span := traceway.StartSpan(ctx, fmt.Sprintf("org overview issues: project %s", project.Id))+ groups, total, err := telemetry.ExceptionStackTraceRepository.FindGrouped(ctx, project.Id, from, now, 1, orgOverviewMaxIssues, "last_seen", "", "", false)+ span.End()+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load issues for project %s: %w", project.Id, err))+ return+ }+ totalGroups += total+ for _, group := range groups {+ issues = append(issues, orgIssueRow{ExceptionGroup: group, ProjectId: project.Id, ProjectName: project.Name})+ }+ }++ sort.Slice(issues, func(i, j int) bool {+ return issues[i].LastSeen.After(issues[j].LastSeen)+ })+ if len(issues) > orgOverviewMaxIssues {+ issues = issues[:orgOverviewMaxIssues]+ }++ ctx.JSON(http.StatusOK, gin.H{"issues": issues, "totalGroups": totalGroups})+}++type orgPageRow struct {+ pageResponse+ ProjectName string `json:"projectName"`+}++func (c *organizationOverviewController) Pages(ctx *gin.Context) {+ tx := db.GetTx(ctx)+ organizationId := middleware.GetOrganizationId(ctx)++ pages, err := transactional.PageRepository.FindByOrganization(tx, organizationId, "active", orgOverviewMaxPages, 0)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization pages: %w", err))+ return+ }+ openCount, err := transactional.PageRepository.CountByOrganization(tx, organizationId, models.PageStatusOpen)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count open pages: %w", err))+ return+ }+ downCount, err := transactional.SyntheticCheckRepository.CountDownByOrganization(tx, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count down monitors: %w", err))+ return+ }+ projects, err := transactional.ProjectRepository.FindByOrganizationId(tx, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization projects: %w", err))+ return+ }+ projectNames := make(map[uuid.UUID]string, len(projects))+ for _, project := range projects {+ projectNames[project.Id] = project.Name+ }++ names := map[int]string{}+ for _, page := range pages {+ if page.AcknowledgedBy != nil || page.ResolvedBy != nil {+ names, err = memberNames(tx, organizationId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load members: %w", err))+ return+ }+ break+ }+ }++ items := make([]orgPageRow, 0, len(pages))+ for _, page := range pages {+ items = append(items, orgPageRow{pageResponse: toPageResponse(page, names), ProjectName: projectNames[page.ProjectId]})+ }++ ctx.JSON(http.StatusOK, gin.H{"pages": items, "openPagesCount": openCount, "downMonitorsCount": downCount})+}++type orgMonitorRow struct {+ *models.SyntheticCheck+ ProjectName string `json:"projectName"`+ Aggregates *models.CheckAggregates `json:"aggregates"`+}++func (c *organizationOverviewController) Monitors(ctx *gin.Context) {+ organizationId := middleware.GetOrganizationId(ctx)++ type orgMonitorsData struct {+ projects []*models.Project+ checks []*models.SyntheticCheck+ }+ data, err := db.ExecuteTransaction(func(tx *sql.Tx) (*orgMonitorsData, error) {+ projects, err := transactional.ProjectRepository.FindByOrganizationId(tx, organizationId)+ if err != nil {+ return nil, err+ }+ checks, err := transactional.SyntheticCheckRepository.FindByOrganization(tx, organizationId)+ if err != nil {+ return nil, err+ }+ return &orgMonitorsData{projects: projects, checks: checks}, nil+ })+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization monitors: %w", err))+ return+ }++ projectNames := make(map[uuid.UUID]string, len(data.projects))+ for _, project := range data.projects {+ projectNames[project.Id] = project.Name+ }++ projectsWithChecks := make([]uuid.UUID, 0)+ seen := make(map[uuid.UUID]bool)+ for _, check := range data.checks {+ if !seen[check.ProjectId] {+ seen[check.ProjectId] = true+ projectsWithChecks = append(projectsWithChecks, check.ProjectId)+ }+ }+ now := time.Now().UTC()+ from := now.AddDate(0, 0, -30)++ aggregates := make(map[int]*models.CheckAggregates)+ for _, projectId := range projectsWithChecks {+ span := traceway.StartSpan(ctx, fmt.Sprintf("org overview monitors: project %s", projectId))+ projectAggregates, err := telemetry.CheckResultRepository.AggregatesByProject(ctx, projectId, from, now)+ span.End()+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to aggregate check results for project %s: %w", projectId, err))+ return+ }+ for checkId, agg := range projectAggregates {+ aggregates[checkId] = agg+ }+ }++ items := make([]orgMonitorRow, 0, len(data.checks))+ for _, check := range data.checks {+ items = append(items, orgMonitorRow{+ SyntheticCheck: check,+ ProjectName: projectNames[check.ProjectId],+ Aggregates: aggregates[check.Id],+ })+ }++ ctx.JSON(http.StatusOK, gin.H{"checks": items})+}diff --git a/backend/app/controllers/organization_overview_test.go b/backend/app/controllers/organization_overview_test.gonew file mode 100644index 00000000..ce6f74ec--- /dev/null+++ b/backend/app/controllers/organization_overview_test.go@@ -0,0 +1,38 @@+package controllers++import (+ "testing"+ "time"++ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestCpuUsageTrendConvertsIdleFraction(t *testing.T) {+ now := time.Now().UTC()+ trend := cpuUsageTrend([]models.TimeSeriesPoint{+ {Timestamp: now, Value: 0.82},+ {Timestamp: now.Add(time.Minute), Value: 0.35},+ })+ if len(trend) != 2 || trend[0].Value != 18 || trend[1].Value != 65 {+ t.Fatalf("cpu trend = %+v, want 18%% then 65%%", trend)+ }+}++func TestLatestCounterRate(t *testing.T) {+ now := time.Now().UTC()+ rate, ok := latestCounterRate([]models.TimeSeriesPoint{+ {Timestamp: now, Value: 1_000},+ {Timestamp: now.Add(time.Minute), Value: 7_000},+ })+ if !ok || rate != 100 {+ t.Fatalf("rate = %v, %v, want 100 bytes/s", rate, ok)+ }++ rate, ok = latestCounterRate([]models.TimeSeriesPoint{+ {Timestamp: now, Value: 7_000},+ {Timestamp: now.Add(time.Minute), Value: 50},+ })+ if !ok || rate != 0 {+ t.Fatalf("reset rate = %v, %v, want 0 bytes/s", rate, ok)+ }+}diff --git a/backend/app/controllers/otelcontrollers/metric_converter.go b/backend/app/controllers/otelcontrollers/metric_converter.goindex d95c4fc2..08643b5c 100644--- a/backend/app/controllers/otelcontrollers/metric_converter.go+++ b/backend/app/controllers/otelcontrollers/metric_converter.go@@ -15,7 +15,7 @@ type convertedMetrics struct {Entries []transactional.MetricRegistrationEntry}-// processResourceAttrAllowlist names the OTel Resource attributes we lift+// metricResourceAttrAllowlist names the OTel Resource attributes we lift// onto each metric point's tags. Necessary because the hostmetrics process// scraper distinguishes per-process metrics via Resource attributes (one// ResourceMetrics per process), not data-point attributes — without this,@@ -24,7 +24,15 @@ type convertedMetrics struct {// container/pod/node/database identity also lives on the Resource. The list// is an allowlist rather than a passthrough so other receivers can't blow up// metric_points cardinality with arbitrary resource attrs.-var processResourceAttrAllowlist = []string{+var metricResourceAttrAllowlist = []string{+ "host.name",+ "host.id",+ "host.arch",+ "os.type",+ "os.description",+ "cloud.provider",+ "cloud.region",+ "cloud.availability_zone","process.pid","process.executable.name","process.command_line",@@ -36,6 +44,7 @@ var processResourceAttrAllowlist = []string{"k8s.node.name","k8s.deployment.name","k8s.container.name",+ "k8s.cluster.name","postgresql.database.name",}@@ -46,7 +55,7 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSerfor _, rm := range req.ResourceMetrics {resAttrs := rm.GetResource().GetAttributes()sn := getStringAttribute(resAttrs, "service.name")- resTags := extractProcessResourceTags(resAttrs)+ resTags := extractMetricResourceTags(resAttrs)for _, sm := range rm.ScopeMetrics {for _, metric := range sm.Metrics {@@ -163,7 +172,7 @@ func buildTags(serverName string, resTags map[string]string, attrs []*commonpb.Kreturn tags}-func extractProcessResourceTags(resAttrs []*commonpb.KeyValue) map[string]string {+func extractMetricResourceTags(resAttrs []*commonpb.KeyValue) map[string]string {if len(resAttrs) == 0 {return nil}@@ -171,8 +180,8 @@ func extractProcessResourceTags(resAttrs []*commonpb.KeyValue) map[string]stringif len(all) == 0 {return nil}- out := make(map[string]string, len(processResourceAttrAllowlist))- for _, k := range processResourceAttrAllowlist {+ out := make(map[string]string, len(metricResourceAttrAllowlist))+ for _, k := range metricResourceAttrAllowlist {if v, ok := all[k]; ok && v != "" {out[k] = v}diff --git a/backend/app/controllers/otelcontrollers/metric_converter_test.go b/backend/app/controllers/otelcontrollers/metric_converter_test.gonew file mode 100644index 00000000..3a50e0b8--- /dev/null+++ b/backend/app/controllers/otelcontrollers/metric_converter_test.go@@ -0,0 +1,58 @@+package otelcontrollers++import (+ "testing"++ "github.com/google/uuid"+ colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"+ metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"+)++func TestConvertMetricPointsPreservesInfrastructureResourceAttributes(t *testing.T) {+ req := &colmetricspb.ExportMetricsServiceRequest{+ ResourceMetrics: []*metricspb.ResourceMetrics{{+ Resource: &resourcepb.Resource{Attributes: []*commonpb.KeyValue{+ strKV("service.name", "payments-node-1"),+ strKV("host.name", "ip-10-0-1-24"),+ strKV("host.id", "i-018b5d2"),+ strKV("host.arch", "amd64"),+ strKV("os.type", "linux"),+ strKV("cloud.region", "eu-central-1"),+ strKV("k8s.cluster.name", "production"),+ strKV("deployment.environment.name", "production"),+ }},+ ScopeMetrics: []*metricspb.ScopeMetrics{{Metrics: []*metricspb.Metric{{+ Name: "system.cpu.utilization",+ Data: &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{DataPoints: []*metricspb.NumberDataPoint{{+ Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: 0.25},+ Attributes: []*commonpb.KeyValue{strKV("state", "idle")},+ }}}},+ }}}},+ }},+ }++ converted := convertMetricPoints(uuid.New(), req)+ if len(converted.Points) != 1 {+ t.Fatalf("converted %d points, want 1", len(converted.Points))+ }+ tags := converted.Points[0].Tags+ for key, want := range map[string]string{+ "server_name": "payments-node-1",+ "host.name": "ip-10-0-1-24",+ "host.id": "i-018b5d2",+ "host.arch": "amd64",+ "os.type": "linux",+ "cloud.region": "eu-central-1",+ "k8s.cluster.name": "production",+ "state": "idle",+ } {+ if got := tags[key]; got != want {+ t.Errorf("tag %q = %q, want %q", key, got, want)+ }+ }+ if _, ok := tags["deployment.environment.name"]; ok {+ t.Error("unexpected non-allowlisted deployment.environment.name tag")+ }+}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 27233d8b..e81d64f4 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -92,6 +92,7 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/metrics/query", middleware.UseAppAuth, middleware.RequireProjectAccess, MetricQueryController.Query)router.GET("/metrics/discover", middleware.UseAppAuth, middleware.RequireProjectAccess, MetricQueryController.Discover)+ router.GET("/metrics/discover/instances", middleware.UseAppAuth, middleware.RequireProjectAccess, MetricQueryController.DiscoverInstances)router.GET("/metrics/discover/tags", middleware.UseAppAuth, middleware.RequireProjectAccess, MetricQueryController.DiscoverTags)router.GET("/metrics/discover/org", middleware.UseAppAuth, MetricQueryController.DiscoverOrg)router.PUT("/metrics/registry", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, MetricQueryController.UpdateRegistry)@@ -278,6 +279,15 @@ func RegisterControllers(router *gin.RouterGroup) {router.DELETE("/organizations/:organizationId/status-pages/:id", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, StatusPageController.Delete)router.POST("/organizations/:organizationId/status-pages/:id/logo", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, StatusPageController.UploadLogo)+ // Org overview: servers/issues/monitors fan out over per-project telemetry+ // queries, so they deliberately skip Transactional (RequireOrganizationAccess+ // completes its own short transaction before the handler runs); the pure+ // main-DB pages endpoint keeps it.+ router.GET("/organizations/:organizationId/overview/servers", middleware.UseAppAuth, middleware.RequireOrganizationAccess, OrganizationOverviewController.Servers)+ router.GET("/organizations/:organizationId/overview/issues", middleware.UseAppAuth, middleware.RequireOrganizationAccess, OrganizationOverviewController.Issues)+ router.GET("/organizations/:organizationId/overview/pages", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, OrganizationOverviewController.Pages)+ router.GET("/organizations/:organizationId/overview/monitors", middleware.UseAppAuth, middleware.RequireOrganizationAccess, OrganizationOverviewController.Monitors)+router.GET("/organizations/:organizationId/incidents", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.List)router.GET("/organizations/:organizationId/incidents/:incidentId/updates", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.ListUpdates)router.GET("/organizations/:organizationId/status-pages/:id/incidents", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, IncidentController.ListForStatusPage)diff --git a/backend/app/migrations/pg/0141_create_pages_org_active_idx.up.sql b/backend/app/migrations/pg/0141_create_pages_org_active_idx.up.sqlnew file mode 100644index 00000000..24c1034b--- /dev/null+++ b/backend/app/migrations/pg/0141_create_pages_org_active_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS pages_org_active_idx ON pages (organization_id, created_at DESC) WHERE status <> 'resolved'diff --git a/backend/app/migrations/sqlite/0075_create_pages_org_active_idx.up.sql b/backend/app/migrations/sqlite/0075_create_pages_org_active_idx.up.sqlnew file mode 100644index 00000000..24c1034b--- /dev/null+++ b/backend/app/migrations/sqlite/0075_create_pages_org_active_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS pages_org_active_idx ON pages (organization_id, created_at DESC) WHERE status <> 'resolved'diff --git a/backend/app/models/metric_record.model.go b/backend/app/models/metric_record.model.goindex 2930b39f..2db28c63 100644--- a/backend/app/models/metric_record.model.go+++ b/backend/app/models/metric_record.model.go@@ -14,6 +14,13 @@ type MetricPoint struct {RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`}+type ServerLatestPoint struct {+ ServerName string `json:"serverName"`+ Value float64 `json:"value"`+ LastReportedAt time.Time `json:"lastReportedAt"`+ Tags map[string]string `json:"tags,omitempty"`+}+type DiscoveredMetric struct {Name string `json:"name"`TagKeys []string `json:"tagKeys"`@@ -22,12 +29,16 @@ type DiscoveredMetric struct {}const (- MetricNameMemoryUsage = "mem.used"- MetricNameMemoryTotal = "mem.total"- MetricNameCpuUsage = "cpu.used_pcnt"- MetricNameGoRoutines = "go.go_routines"- MetricNameHeapObjects = "go.heap_objects"- MetricNameNumGC = "go.num_gc"- MetricNameGCPauseTotal = "go.gc_pause"+ MetricNameMemoryUsage = "mem.used"+ MetricNameMemoryTotal = "mem.total"+ MetricNameCpuUsage = "cpu.used_pcnt"+ MetricNameGoRoutines = "go.go_routines"+ MetricNameHeapObjects = "go.heap_objects"+ MetricNameNumGC = "go.num_gc"+ MetricNameGCPauseTotal = "go.gc_pause"+ MetricNameSystemCPUUtilization = "system.cpu.utilization"+ MetricNameSystemMemoryUtilization = "system.memory.utilization"+ MetricNameSystemFilesystemUtilization = "system.filesystem.utilization"+ MetricNameSystemNetworkIO = "system.network.io"// other metric names are custom and added by the clients)diff --git a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.goindex 9c1835b5..4d4b391a 100644--- a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go@@ -222,6 +222,33 @@ func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectIreturn servers, nil}+func (r *metricPointRepository) LatestPerServer(ctx context.Context, projectId uuid.UUID, name string, since time.Time) ([]models.ServerLatestPoint, error) {+ query := `SELECT tags['server_name'] AS sn,+ argMax(value, recorded_at) AS latest_value,+ max(recorded_at) AS last_reported_at,+ argMax(tags, recorded_at) AS latest_tags+ FROM metric_points+ WHERE project_id = ? AND name = ? AND recorded_at >= ?+ AND tags['server_name'] != ''+ GROUP BY sn ORDER BY sn ASC`++ rows, err := chdb.Conn.Query(ctx, query, projectId, name, since)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.ServerLatestPoint+ for rows.Next() {+ var p models.ServerLatestPoint+ if err := rows.Scan(&p.ServerName, &p.Value, &p.LastReportedAt, &p.Tags); err != nil {+ return nil, err+ }+ points = append(points, p)+ }+ return points, rows.Err()+}+func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {table := selectTable(end.Sub(start))aggFunc := aggregationFunc("avg", table)diff --git a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go b/backend/app/repositories/telemetry/duckdb/metric_point.repository.goindex 5eeba426..c8e399e9 100644--- a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go+++ b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go@@ -15,6 +15,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes")type metricPointRepository struct{}@@ -235,6 +236,39 @@ func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectIreturn servers, nil}+func (r *metricPointRepository) LatestPerServer(ctx context.Context, projectId uuid.UUID, name string, since time.Time) ([]models.ServerLatestPoint, error) {+ query, args, err := lit.ParseNamedQuery(db.Driver,+ `SELECT server_name AS sn,+ arg_max(value, recorded_at) AS latest_value,+ max(recorded_at) AS last_reported_at,+ arg_max(tags, recorded_at) AS latest_tags+ FROM metric_points+ WHERE project_id = :project_id AND name = :name AND recorded_at >= :since AND server_name != ''+ GROUP BY sn ORDER BY sn ASC`,+ lit.P{"project_id": projectId, "name": name, "since": since.UTC()})+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.ServerLatestPoint+ for rows.Next() {+ var p models.ServerLatestPoint+ var tags sqlitetypes.SQLiteJSONMap+ if err := rows.Scan(&p.ServerName, &p.Value, &p.LastReportedAt, &tags); err != nil {+ return nil, err+ }+ p.Tags = map[string]string(tags)+ points = append(points, p)+ }+ return points, rows.Err()+}+func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60diff --git a/backend/app/repositories/telemetry/metric_point_repository_test.go b/backend/app/repositories/telemetry/metric_point_repository_test.goindex 082d465b..672897c7 100644--- a/backend/app/repositories/telemetry/metric_point_repository_test.go+++ b/backend/app/repositories/telemetry/metric_point_repository_test.go@@ -280,6 +280,46 @@ func TestMetricPointRepository_GetDistinctServers(t *testing.T) {}}+func TestMetricPointRepository_LatestPerServer(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Second)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 10, map[string]string{"server_name": "api-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 30, map[string]string{"server_name": "api-1", "os.type": "linux"}, base.Add(2*time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 50, map[string]string{"server_name": "worker-1"}, base.Add(3*time.Minute)),+ makeMetricPoint(projectId, "mem.used", 99, map[string]string{"server_name": "api-1"}, base.Add(4*time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 70, nil, base.Add(5*time.Minute)),+ makeMetricPoint(uuid.New(), "cpu.used_pcnt", 80, map[string]string{"server_name": "other"}, base.Add(6*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ latest, err := MetricPointRepository.LatestPerServer(ctx, projectId, "cpu.used_pcnt", base.Add(time.Minute))+ if err != nil {+ t.Fatalf("LatestPerServer failed: %v", err)+ }+ if len(latest) != 2 {+ t.Fatalf("LatestPerServer returned %d rows, want 2: %+v", len(latest), latest)+ }+ if latest[0].ServerName != "api-1" || latest[0].Value != 30 {+ t.Errorf("latest[0] = %+v, want api-1 value 30", latest[0])+ }+ if !latest[0].LastReportedAt.Equal(base.Add(2 * time.Minute)) {+ t.Errorf("api-1 timestamp = %s, want %s", latest[0].LastReportedAt, base.Add(2*time.Minute))+ }+ if latest[0].Tags["os.type"] != "linux" {+ t.Errorf("api-1 tags = %v, want os.type=linux", latest[0].Tags)+ }+ if latest[1].ServerName != "worker-1" || latest[1].Value != 50 {+ t.Errorf("latest[1] = %+v, want worker-1 value 50", latest[1])+ }+}+func TestMetricPointRepository_InsertEmpty(t *testing.T) {setupTestDB(t)ctx := context.Background()diff --git a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go b/backend/app/repositories/telemetry/sqlite/metric_point.repository.goindex 20a4606f..37cad2e2 100644--- a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go+++ b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go@@ -262,6 +262,51 @@ func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectIreturn servers, nil}+func (r *metricPointRepository) LatestPerServer(ctx context.Context, projectId uuid.UUID, name string, since time.Time) ([]models.ServerLatestPoint, error) {+ query, args, err := lit.ParseNamedQuery(db.Driver,+ `SELECT sn, latest_value, last_reported_at, latest_tags+ FROM (+ SELECT json_extract(tags, '$.server_name') AS sn,+ value AS latest_value,+ recorded_at AS last_reported_at,+ tags AS latest_tags,+ ROW_NUMBER() OVER (+ PARTITION BY json_extract(tags, '$.server_name')+ ORDER BY recorded_at DESC+ ) AS row_number+ FROM metric_points+ WHERE project_id = :project_id AND name = :name AND recorded_at >= :since+ AND json_extract(tags, '$.server_name') IS NOT NULL+ AND json_extract(tags, '$.server_name') != ''+ )+ WHERE row_number = 1+ ORDER BY sn ASC`,+ lit.P{"project_id": projectId, "name": name, "since": sqlitetypes.NewSQLiteTime(since)})+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.ServerLatestPoint+ for rows.Next() {+ var p models.ServerLatestPoint+ var lastReportedAt sqlitetypes.SQLiteTime+ var tags sqlitetypes.SQLiteJSONMap+ if err := rows.Scan(&p.ServerName, &p.Value, &lastReportedAt, &tags); err != nil {+ return nil, err+ }+ p.LastReportedAt = lastReportedAt.Time+ p.Tags = map[string]string(tags)+ points = append(points, p)+ }+ return points, rows.Err()+}+func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60diff --git a/backend/app/repositories/transactional/pg/page.repository.go b/backend/app/repositories/transactional/pg/page.repository.goindex 80fbf2b6..691afeb7 100644--- a/backend/app/repositories/transactional/pg/page.repository.go+++ b/backend/app/repositories/transactional/pg/page.repository.go@@ -104,6 +104,29 @@ func (r *pageRepository) CountOpenByProject(tx *sql.Tx, projectId uuid.UUID) (inreturn r.CountByProject(tx, projectId, models.PageStatusOpen)}+func (r *pageRepository) FindByOrganization(tx *sql.Tx, organizationId int, status string, limit int, offset int) ([]*models.Page, error) {+ return lit.SelectNamed[models.Page](+ tx,+ "SELECT "+pageColumns+" FROM pages WHERE organization_id = :organization_id AND ("+statusCondition(status)+") ORDER BY created_at DESC, id DESC LIMIT :limit OFFSET :offset",+ lit.P{"organization_id": organizationId, "limit": limit, "offset": offset},+ )+}++func (r *pageRepository) CountByOrganization(tx *sql.Tx, organizationId int, status string) (int, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM pages WHERE organization_id = :organization_id AND ("+statusCondition(status)+")",+ lit.P{"organization_id": organizationId},+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}+// statusCondition maps a status filter to a fixed SQL condition; values are// from a closed set, never user input.func statusCondition(status string) string {diff --git a/backend/app/repositories/transactional/pg/synthetic_check.repository.go b/backend/app/repositories/transactional/pg/synthetic_check.repository.goindex 6e251f85..4f945da3 100644--- a/backend/app/repositories/transactional/pg/synthetic_check.repository.go+++ b/backend/app/repositories/transactional/pg/synthetic_check.repository.go@@ -135,6 +135,29 @@ func (r *syntheticCheckRepository) FindByIdInOrganization(tx *sql.Tx, id int, or)}+func (r *syntheticCheckRepository) FindByOrganization(tx *sql.Tx, organizationId int) ([]*models.SyntheticCheck, error) {+ return lit.SelectNamed[models.SyntheticCheck](+ tx,+ "SELECT c.id, c.project_id, c.name, c.check_type, c.enabled, c.interval_seconds, c.timeout_seconds, c.config, c.failure_threshold, c.current_status, c.consecutive_failures, c.last_run_at, c.last_state_change_at, c.next_run_at, c.created_at, c.updated_at FROM synthetic_checks c JOIN projects p ON p.id = c.project_id WHERE p.organization_id = :organization_id ORDER BY c.name ASC, c.id ASC",+ lit.P{"organization_id": organizationId},+ )+}++func (r *syntheticCheckRepository) CountDownByOrganization(tx *sql.Tx, organizationId int) (int, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM synthetic_checks c JOIN projects p ON p.id = c.project_id WHERE p.organization_id = :organization_id AND c.enabled = true AND c.current_status = 'down'",+ lit.P{"organization_id": organizationId},+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}+func (r *syntheticCheckRepository) CountDownAll(tx *sql.Tx) (int, error) {result, err := lit.SelectSingleNamed[models.CountResult](tx,diff --git a/backend/app/repositories/transactional/sqlite/page.repository.go b/backend/app/repositories/transactional/sqlite/page.repository.goindex 45e107bc..ab0f505c 100644--- a/backend/app/repositories/transactional/sqlite/page.repository.go+++ b/backend/app/repositories/transactional/sqlite/page.repository.go@@ -104,6 +104,29 @@ func (r *pageRepository) CountOpenByProject(tx *sql.Tx, projectId uuid.UUID) (inreturn r.CountByProject(tx, projectId, models.PageStatusOpen)}+func (r *pageRepository) FindByOrganization(tx *sql.Tx, organizationId int, status string, limit int, offset int) ([]*models.Page, error) {+ return lit.SelectNamed[models.Page](+ tx,+ "SELECT "+pageColumns+" FROM pages WHERE organization_id = :organization_id AND ("+statusCondition(status)+") ORDER BY created_at DESC, id DESC LIMIT :limit OFFSET :offset",+ lit.P{"organization_id": organizationId, "limit": limit, "offset": offset},+ )+}++func (r *pageRepository) CountByOrganization(tx *sql.Tx, organizationId int, status string) (int, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM pages WHERE organization_id = :organization_id AND ("+statusCondition(status)+")",+ lit.P{"organization_id": organizationId},+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}+// statusCondition maps a status filter to a fixed SQL condition; values are// from a closed set, never user input.func statusCondition(status string) string {diff --git a/backend/app/repositories/transactional/sqlite/synthetic_check.repository.go b/backend/app/repositories/transactional/sqlite/synthetic_check.repository.goindex 116c6a5b..30c9524a 100644--- a/backend/app/repositories/transactional/sqlite/synthetic_check.repository.go+++ b/backend/app/repositories/transactional/sqlite/synthetic_check.repository.go@@ -135,6 +135,29 @@ func (r *syntheticCheckRepository) FindByIdInOrganization(tx *sql.Tx, id int, or)}+func (r *syntheticCheckRepository) FindByOrganization(tx *sql.Tx, organizationId int) ([]*models.SyntheticCheck, error) {+ return lit.SelectNamed[models.SyntheticCheck](+ tx,+ "SELECT c.id, c.project_id, c.name, c.check_type, c.enabled, c.interval_seconds, c.timeout_seconds, c.config, c.failure_threshold, c.current_status, c.consecutive_failures, c.last_run_at, c.last_state_change_at, c.next_run_at, c.created_at, c.updated_at FROM synthetic_checks c JOIN projects p ON p.id = c.project_id WHERE p.organization_id = :organization_id ORDER BY c.name ASC, c.id ASC",+ lit.P{"organization_id": organizationId},+ )+}++func (r *syntheticCheckRepository) CountDownByOrganization(tx *sql.Tx, organizationId int) (int, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ "SELECT COUNT(*) as count FROM synthetic_checks c JOIN projects p ON p.id = c.project_id WHERE p.organization_id = :organization_id AND c.enabled = true AND c.current_status = 'down'",+ lit.P{"organization_id": organizationId},+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}+func (r *syntheticCheckRepository) CountDownAll(tx *sql.Tx) (int, error) {result, err := lit.SelectSingleNamed[models.CountResult](tx,diff --git a/frontend/src/lib/components/add-project-modal.svelte b/frontend/src/lib/components/add-project-modal.svelteindex 6333d579..6002a961 100644--- a/frontend/src/lib/components/add-project-modal.svelte+++ b/frontend/src/lib/components/add-project-modal.svelte@@ -22,9 +22,10 @@open: boolean;onOpenChange: (open: boolean) => void;onProjectCreated: () => void;+ initialOrganizationId?: number | null;}- let { open, onOpenChange, onProjectCreated }: Props = $props();+ let { open, onOpenChange, onProjectCreated, initialOrganizationId = null }: Props = $props();let projectName = $state('');let selectedFramework = $state<Framework>('opentelemetry');@@ -40,9 +41,11 @@if (open) {untrack(() => {const currentOrgId = projectsState.currentProject?.organizationId;- selectedOrgId = writableOrgs.some((o) => o.id === currentOrgId)- ? currentOrgId!- : (writableOrgs[0]?.id ?? null);+ selectedOrgId = writableOrgs.some((o) => o.id === initialOrganizationId)+ ? initialOrganizationId+ : writableOrgs.some((o) => o.id === currentOrgId)+ ? currentOrgId!+ : (writableOrgs[0]?.id ?? null);});}});diff --git a/frontend/src/lib/components/dashboard/instance-filter.svelte b/frontend/src/lib/components/dashboard/instance-filter.sveltenew file mode 100644index 00000000..3812691c--- /dev/null+++ b/frontend/src/lib/components/dashboard/instance-filter.svelte@@ -0,0 +1,219 @@+<script lang="ts">+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import * as Command from '$lib/components/ui/command';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import * as Popover from '$lib/components/ui/popover';+ import { Check, ChevronDown, Server, X } from '@lucide/svelte';++ let {+ value = '',+ from,+ to,+ projectId,+ onValueChange+ } = $props<{+ value?: string;+ from: string;+ to: string;+ projectId?: string | null;+ onValueChange?: (value: string) => void;+ }>();++ let open = $state(false);+ let search = $state('');+ let instances = $state<string[]>([]);+ let loading = $state(false);+ let loadError = $state('');+ let loadedKey = '';+ let pendingKey = '';+ let observedContext = '';+ let loadSequence = 0;++ const selectedIsOutsideRange = $derived(value !== '' && !instances.includes(value));++ function contextKey() {+ return `${projectId ?? ''}|${from}|${to}`;+ }++ async function loadInstances(force = false) {+ if (!projectId) {+ instances = [];+ loading = false;+ loadError = '';+ return;+ }++ const key = contextKey();+ if (!force && (loadedKey === key || pendingKey === key)) return;++ const sequence = ++loadSequence;+ pendingKey = key;+ loading = true;+ loadError = '';++ try {+ const response = await api.get(+ `/metrics/discover/instances?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ { projectId }+ );+ if (sequence !== loadSequence) return;++ const discovered = Array.isArray(response.instances) ? response.instances : [];+ instances = [...new Set(discovered)]+ .filter(+ (instance): instance is string => typeof instance === 'string' && instance.trim() !== ''+ )+ .map((instance) => instance.trim())+ .sort((a, b) => a.localeCompare(b));+ loadedKey = key;+ } catch {+ if (sequence !== loadSequence) return;+ instances = [];+ loadError = 'Could not load instances for this time range.';+ } finally {+ if (sequence === loadSequence) {+ pendingKey = '';+ loading = false;+ }+ }+ }++ function handleOpenChange(nextOpen: boolean) {+ open = nextOpen;+ if (nextOpen) {+ void loadInstances();+ } else {+ search = '';+ }+ }++ function selectInstance(instance: string) {+ onValueChange?.(instance);+ open = false;+ search = '';+ }++ $effect(() => {+ const key = contextKey();+ if (key === observedContext) return;++ observedContext = key;+ loadedKey = '';+ instances = [];+ loadError = '';+ loadSequence++;+ pendingKey = '';+ loading = false;+ if (open) void loadInstances();+ });+</script>++<div class="flex h-9 w-full min-w-0 @2xl:w-60 @2xl:min-w-60 @2xl:shrink-0">+ <Popover.Root bind:open onOpenChange={handleOpenChange}>+ <Popover.Trigger class="min-w-0 flex-1">+ <Button+ variant="outline"+ class="h-9 w-full min-w-0 shrink justify-start gap-2 px-3 font-normal {value+ ? 'rounded-r-none border-primary/30 bg-primary/5 hover:bg-primary/10 dark:bg-primary/10'+ : 'border-dashed text-muted-foreground'}"+ aria-label={value ? `Instance filter: ${value}` : 'Filter dashboard by instance'}+ >+ <Server class="size-4 shrink-0 {value ? 'text-primary' : ''}" />+ {#if value}+ <span+ class="min-w-0 flex-1 truncate text-left font-mono text-xs font-medium text-foreground"+ >+ {value}+ </span>+ {:else}+ <span class="min-w-0 flex-1 truncate text-left">All instances</span>+ {/if}+ <ChevronDown class="size-3.5 shrink-0 text-muted-foreground" />+ </Button>+ </Popover.Trigger>++ <Popover.Content align="end" class="w-80 max-w-[calc(100vw-2rem)] p-0">+ <div class="border-b px-3 py-2.5">+ <p class="text-sm font-medium">Filter by instance</p>+ <p class="mt-0.5 text-xs text-muted-foreground">+ Scopes every metric query on this dashboard.+ </p>+ </div>++ {#if loading}+ <div class="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">+ <LoadingCircle size="sm" />+ <span>Loading instances...</span>+ </div>+ {:else if loadError}+ <div class="space-y-2 px-4 py-5 text-center">+ <p class="text-sm text-muted-foreground">{loadError}</p>+ <Button variant="outline" size="sm" onclick={() => loadInstances(true)}>Try again</Button>+ </div>+ {:else}+ <Command.Root>+ <Command.Input bind:value={search} placeholder="Find an instance..." />+ <Command.List class="max-h-72">+ <Command.Empty>No matching instances.</Command.Empty>+ <Command.Group>+ <Command.Item+ value="all instances"+ keywords={['all', 'clear', 'project']}+ onSelect={() => selectInstance('')}+ >+ <div class="grid size-6 shrink-0 place-items-center rounded-md bg-muted">+ <Server class="size-3.5 text-muted-foreground" />+ </div>+ <span class="flex-1">All instances</span>+ {#if value === ''}<Check class="text-primary" />{/if}+ </Command.Item>+ </Command.Group>++ {#if selectedIsOutsideRange}+ <Command.Separator />+ <Command.Group heading="Selected">+ <Command.Item {value} onSelect={() => selectInstance(value)}>+ <span class="size-2 shrink-0 rounded-full bg-muted-foreground/50"></span>+ <span class="min-w-0 flex-1 truncate font-mono text-xs">{value}</span>+ <span class="text-[11px] text-muted-foreground">Not seen</span>+ <Check class="text-primary" />+ </Command.Item>+ </Command.Group>+ {/if}++ {#if instances.length > 0}+ <Command.Separator />+ <Command.Group heading={`Seen in range · ${instances.length}`}>+ {#each instances as instance (instance)}+ <Command.Item value={instance} onSelect={() => selectInstance(instance)}>+ <span class="size-2 shrink-0 rounded-full bg-emerald-500"></span>+ <span class="min-w-0 flex-1 truncate font-mono text-xs">{instance}</span>+ {#if value === instance}<Check class="text-primary" />{/if}+ </Command.Item>+ {/each}+ </Command.Group>+ {:else if search === '' && !selectedIsOutsideRange}+ <div class="px-4 py-6 text-center text-sm text-muted-foreground">+ No instances reported in this time range.+ </div>+ {/if}+ </Command.List>+ </Command.Root>+ {/if}+ </Popover.Content>+ </Popover.Root>++ {#if value}+ <Button+ variant="outline"+ size="icon"+ class="-ml-px size-9 rounded-l-none border-primary/30 bg-primary/5 text-muted-foreground hover:bg-primary/10 hover:text-foreground dark:bg-primary/10"+ onclick={() => selectInstance('')}+ aria-label={`Clear instance filter for ${value}`}+ title="Clear instance filter"+ >+ <X class="size-3.5" />+ </Button>+ {/if}+</div>diff --git a/frontend/src/lib/components/dashboard/widget-grid.svelte b/frontend/src/lib/components/dashboard/widget-grid.svelteindex 84d56e53..fdac1c6e 100644--- a/frontend/src/lib/components/dashboard/widget-grid.svelte+++ b/frontend/src/lib/components/dashboard/widget-grid.svelte@@ -39,7 +39,8 @@onResizeWidget,onAddWidget,onToggleStar,- onRangeSelect+ onRangeSelect,+ scopeTagFilters = {}} = $props<{widgets: Widget[];fromDateUTC: string;@@ -53,6 +54,7 @@onAddWidget?: () => void;onToggleStar?: (widget: Widget) => void;onRangeSelect?: (from: Date, to: Date) => void;+ scopeTagFilters?: Record<string, string>;}>();let sharedHoverTime = $state<Date | null>(null);@@ -312,6 +314,7 @@{timeDomain}{onRangeSelect}{sharedHoverTime}+ {scopeTagFilters}onHoverTimeChange={(time) => (sharedHoverTime = time)}isSourceChart={false}/>diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelteindex 3572b864..dd123a3d 100644--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte@@ -26,7 +26,8 @@onRangeSelect,sharedHoverTime = null,isSourceChart = false,- onHoverTimeChange+ onHoverTimeChange,+ scopeTagFilters = {}} = $props<{widget: {id: number;@@ -41,12 +42,14 @@sharedHoverTime?: Date | null;isSourceChart?: boolean;onHoverTimeChange?: (time: Date | null) => void;+ scopeTagFilters?: Record<string, string>;}>();let series = $state<Array<{ key: string; data: MetricTrendPoint[]; color: string }>>([]);let loading = $state(true);let singleValue = $state<number | null>(null);let resolvedUnit = $state('');+ let loadSequence = 0;const colors = ['var(--chart-1)',@@ -58,6 +61,7 @@];const effectiveUnit = $derived(widget.config.unit ?? resolvedUnit);+ const scopeFilterKey = $derived(JSON.stringify(scopeTagFilters));// Fallbacks for the first render; once mounted the chart fills the measured card spaceconst chartHeights: Record<string, number> = { sm: 200, md: 300, lg: 420 };@@ -111,9 +115,10 @@);async function loadData() {+ const sequence = ++loadSequence;const sources = widget.config.sources;if (!sources || sources.length === 0) {- loading = false;+ if (sequence === loadSequence) loading = false;return;}@@ -125,7 +130,7 @@const queries = sources.map((s: DashboardWidgetSource) => ({name: s.name,aggregation: s.aggregation || 'avg',- tagFilters: s.tagFilters,+ tagFilters: { ...(s.tagFilters ?? {}), ...scopeTagFilters },groupBy: s.groupBy}));@@ -134,6 +139,7 @@{ queries, from: fromDateUTC, to: toDateUTC },{ projectId: projectsState.currentProjectId ?? undefined });+ if (sequence !== loadSequence) return;const units = new SvelteSet<string>();const usedKeys = new SvelteSet<string>();@@ -167,13 +173,15 @@singleValue = newSeries.length > 0 ? reduceSeries(newSeries[0].data, aggregation) : null;}} catch {- // keep empty+ if (sequence !== loadSequence) return;+ // Retain the last successful snapshot during transient query failures.} finally {- loading = false;+ if (sequence === loadSequence) loading = false;}}$effect(() => {+ void scopeFilterKey;if (fromDateUTC && toDateUTC) {loadData();}diff --git a/frontend/src/lib/components/organization-project-switcher.svelte b/frontend/src/lib/components/organization-project-switcher.sveltenew file mode 100644index 00000000..2cd6fcda--- /dev/null+++ b/frontend/src/lib/components/organization-project-switcher.svelte@@ -0,0 +1,151 @@+<script lang="ts">+ import { page } from '$app/state';+ import { Building2, Check, ChevronDown, Pencil, Plus } from '@lucide/svelte';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState, type Project } from '$lib/state/projects.svelte';+ import { gotoHref } from '$lib/utils/navigation';+ import FrameworkIcon from './framework-icon.svelte';++ interface Props {+ onAddProject: () => void;+ onEditProject: () => void;+ }++ let { onAddProject, onEditProject }: Props = $props();++ const organizationContext = $derived(+ page.url.pathname === '/organization' || page.url.pathname.startsWith('/organization/')+ );++ const selectedOrganizationId = $derived.by(() => {+ if (!organizationContext) return null;+ const value = Number(page.url.searchParams.get('organizationId'));+ if (+ Number.isInteger(value) &&+ authState.organizations.some((organization) => organization.id === value)+ ) {+ return value;+ }+ return authState.organizations[0]?.id ?? null;+ });++ const selectedOrganization = $derived(+ authState.organizations.find((organization) => organization.id === selectedOrganizationId) ??+ null+ );++ const groups = $derived.by(() => {+ const grouped = authState.organizations.map((organization) => ({+ organization,+ projects: projectsState.projects.filter(+ (project) => project.organizationId === organization.id+ )+ }));+ const knownOrganizationIds = new Set(+ authState.organizations.map((organization) => organization.id)+ );+ const ungroupedProjects = projectsState.projects.filter(+ (project) =>+ project.organizationId === null || !knownOrganizationIds.has(project.organizationId)+ );+ return { grouped, ungroupedProjects };+ });++ function selectProject(projectId: string) {+ gotoHref(`/?projectId=${projectId}`);+ }++ function selectOrganization(organizationId: number) {+ gotoHref(`/organization?organizationId=${organizationId}`);+ }+</script>++{#snippet projectItem(project: Project)}+ <DropdownMenu.Item+ onclick={() => selectProject(project.id)}+ class="flex cursor-pointer items-center justify-between py-2 pl-4"+ >+ <div class="flex min-w-0 items-center gap-2.5">+ <FrameworkIcon framework={project.framework} class="size-5 shrink-0" />+ <span class="truncate">{project.name}</span>+ </div>+ {#if !organizationContext && project.id === projectsState.currentProjectId}+ <Check class="size-4 shrink-0" />+ {/if}+ </DropdownMenu.Item>+{/snippet}++<DropdownMenu.Root>+ <DropdownMenu.Trigger+ class="flex max-w-[min(70vw,32rem)] min-w-0 items-center gap-2 rounded-md px-2 py-1 text-lg font-semibold transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ aria-label="Switch organization or project"+ >+ {#if organizationContext}+ <Building2 class="size-5 shrink-0 text-muted-foreground" />+ <span class="truncate">{selectedOrganization?.name || 'Select organization'}</span>+ {:else}+ {#if projectsState.currentProject}+ <FrameworkIcon framework={projectsState.currentProject.framework} class="size-6 shrink-0" />+ {/if}+ <span class="truncate">{projectsState.currentProject?.name || 'Select project'}</span>+ {/if}+ <ChevronDown class="size-4 shrink-0" />+ </DropdownMenu.Trigger>++ <DropdownMenu.Content align="start" class="w-[min(22rem,calc(100vw-1rem))]">+ {#each groups.grouped as group, index (group.organization.id)}+ {#if index > 0}+ <DropdownMenu.Separator />+ {/if}+ <DropdownMenu.Group>+ <DropdownMenu.Item+ onclick={() => selectOrganization(group.organization.id)}+ class="cursor-pointer py-2"+ >+ <Building2 class="size-5 shrink-0" />+ <div class="min-w-0 flex-1">+ <div class="truncate font-semibold">{group.organization.name}</div>+ <div class="text-xs text-muted-foreground">Organization overview</div>+ </div>+ {#if organizationContext && selectedOrganizationId === group.organization.id}+ <Check class="size-4 shrink-0" />+ {/if}+ </DropdownMenu.Item>++ {#each group.projects as project (project.id)}+ {@render projectItem(project)}+ {/each}+ {#if group.projects.length === 0}+ <DropdownMenu.Item disabled class="pl-4">No projects yet</DropdownMenu.Item>+ {/if}+ </DropdownMenu.Group>+ {/each}++ {#if groups.ungroupedProjects.length > 0}+ <DropdownMenu.Separator />+ <DropdownMenu.Group>+ <DropdownMenu.Label class="text-muted-foreground">Other projects</DropdownMenu.Label>+ {#each groups.ungroupedProjects as project (project.id)}+ {@render projectItem(project)}+ {/each}+ </DropdownMenu.Group>+ {/if}++ {#if projectsState.projects.length === 0}+ <DropdownMenu.Item disabled>No projects yet</DropdownMenu.Item>+ {/if}++ <DropdownMenu.Separator />+ {#if !organizationContext && projectsState.canManageCurrentProject}+ <DropdownMenu.Item onclick={onEditProject} class="cursor-pointer">+ <Pencil class="size-4" />+ Edit Project+ </DropdownMenu.Item>+ {/if}+ <DropdownMenu.Item onclick={onAddProject} class="cursor-pointer">+ <Plus class="size-4" />+ Add Project+ </DropdownMenu.Item>+ </DropdownMenu.Content>+</DropdownMenu.Root>diff --git a/frontend/src/lib/components/setup/setup-projects-step.svelte b/frontend/src/lib/components/setup/setup-projects-step.svelteindex 0125b032..98a4be04 100644--- a/frontend/src/lib/components/setup/setup-projects-step.svelte+++ b/frontend/src/lib/components/setup/setup-projects-step.svelte@@ -48,6 +48,7 @@function destination(): string {if (redirectTo) return redirectTo;+ if (orgProjects.length > 1) return `/organization?organizationId=${organizationId}`;const first = newProjects[0] ?? orgProjects[0];return first ? `/?projectId=${first.id}` : '/';}@@ -83,6 +84,7 @@draft = draftResponse?.draft ?? null;draftLoaded = true;} catch {+ // A later poll retries transient setup API failures.} finally {pollInFlight = false;}diff --git a/frontend/src/lib/components/traceway/resource-ring.svelte b/frontend/src/lib/components/traceway/resource-ring.sveltenew file mode 100644index 00000000..fd306b74--- /dev/null+++ b/frontend/src/lib/components/traceway/resource-ring.svelte@@ -0,0 +1,61 @@+<script lang="ts">+ interface Props {+ label: string;+ value: number | null;+ warningAt?: number;+ criticalAt?: number;+ size?: 'sm' | 'md';+ }++ let { label, value, warningAt = 80, criticalAt = 95, size = 'md' }: Props = $props();++ const normalized = $derived(value === null ? null : Math.max(0, Math.min(100, value)));+ const tone = $derived.by(() => {+ if (normalized === null) return 'text-muted-foreground/35';+ if (normalized >= criticalAt) return 'text-crit';+ if (normalized >= warningAt) return 'text-amber-500 dark:text-amber-400';+ return 'text-ok';+ });+ const dimension = $derived(size === 'sm' ? 'size-11' : 'size-13');+ const valueText = $derived(normalized === null ? '—' : `${Math.round(normalized)}`);+ const accessibleValue = $derived(+ normalized === null ? `${label}: no data` : `${label}: ${normalized.toFixed(1)} percent`+ );+</script>++<div+ class="relative grid {dimension} shrink-0 place-items-center"+ role="img"+ aria-label={accessibleValue}+ title={accessibleValue}+>+ <svg class="absolute inset-0 size-full -rotate-90" viewBox="0 0 48 48" aria-hidden="true">+ <circle+ cx="24"+ cy="24"+ r="19"+ pathLength="100"+ fill="none"+ stroke="currentColor"+ stroke-width="4"+ class="text-muted"+ />+ {#if normalized !== null}+ <circle+ cx="24"+ cy="24"+ r="19"+ pathLength="100"+ fill="none"+ stroke="currentColor"+ stroke-width="4"+ stroke-linecap="round"+ stroke-dasharray="{normalized} {100 - normalized}"+ class={tone}+ />+ {/if}+ </svg>+ <span class="font-mono text-[11px] font-semibold tracking-tight tabular-nums">+ {valueText}{#if normalized !== null}<span class="text-[8px] text-muted-foreground">%</span>{/if}+ </span>+</div>diff --git a/frontend/src/lib/components/traceway/stat-tile.svelte b/frontend/src/lib/components/traceway/stat-tile.svelteindex 48321478..f6b207bd 100644--- a/frontend/src/lib/components/traceway/stat-tile.svelte+++ b/frontend/src/lib/components/traceway/stat-tile.svelte@@ -6,12 +6,13 @@value: string | number;sub?: string;valueClass?: string;+ class?: string;}- let { label, value, sub, valueClass }: Props = $props();+ let { label, value, sub, valueClass, class: className }: Props = $props();</script>-<div class="px-6 py-4">+<div class={cn('px-6 py-4', className)}><div class="text-xs font-medium text-muted-foreground">{label}</div><div class={cn('mt-1 text-2xl font-semibold tracking-tight tabular-nums', valueClass)}>{value}diff --git a/frontend/src/lib/utils/landing.ts b/frontend/src/lib/utils/landing.tsnew file mode 100644index 00000000..0dbfcaf5--- /dev/null+++ b/frontend/src/lib/utils/landing.ts@@ -0,0 +1,51 @@+export interface LandingOrganization {+ id: number;+}++export interface LandingProject {+ id: string;+ organizationId: number | null;+}++export function safeLocalPath(raw: string | null): string {+ if (!raw) return '/';+ let decoded: string;+ try {+ decoded = decodeURIComponent(raw);+ } catch {+ return '/';+ }+ if (!decoded.startsWith('/') || decoded.startsWith('//') || decoded.startsWith('/\\')) {+ return '/';+ }+ return decoded;+}++export function defaultAuthenticatedPath(+ organizations: LandingOrganization[],+ projects: LandingProject[]+): string {+ const firstOrganization = organizations.find((organization) =>+ projects.some((project) => project.organizationId === organization.id)+ );+ if (firstOrganization) {+ const organizationProjects = projects.filter(+ (project) => project.organizationId === firstOrganization.id+ );+ if (organizationProjects.length > 1) {+ return `/organization?organizationId=${firstOrganization.id}`;+ }+ return `/?projectId=${organizationProjects[0].id}`;+ }++ return projects[0] ? `/?projectId=${projects[0].id}` : '/setup';+}++export function authenticatedLandingPath(+ returnTo: string | null,+ organizations: LandingOrganization[],+ projects: LandingProject[]+): string {+ const requestedPath = safeLocalPath(returnTo);+ return requestedPath === '/' ? defaultAuthenticatedPath(organizations, projects) : requestedPath;+}diff --git a/frontend/src/lib/utils/navigation.test.ts b/frontend/src/lib/utils/navigation.test.tsnew file mode 100644index 00000000..2dff2e8e--- /dev/null+++ b/frontend/src/lib/utils/navigation.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import { authenticatedLandingPath, defaultAuthenticatedPath } from './landing';++describe('defaultAuthenticatedPath', () => {+ it('opens the first organization when it has multiple projects', () => {+ expect(+ defaultAuthenticatedPath(+ [{ id: 10 }, { id: 20 }],+ [+ { id: 'other', organizationId: 20 },+ { id: 'first-a', organizationId: 10 },+ { id: 'first-b', organizationId: 10 }+ ]+ )+ ).toBe('/organization?organizationId=10');+ });++ it('opens the project directly when the first organization has one project', () => {+ expect(+ defaultAuthenticatedPath(+ [{ id: 10 }, { id: 20 }],+ [+ { id: 'other', organizationId: 20 },+ { id: 'only', organizationId: 10 }+ ]+ )+ ).toBe('/?projectId=only');+ });++ it('falls back to the first available project, then setup', () => {+ expect(defaultAuthenticatedPath([{ id: 10 }], [{ id: 'other', organizationId: 20 }])).toBe(+ '/?projectId=other'+ );+ expect(defaultAuthenticatedPath([], [])).toBe('/setup');+ });++ it('skips an empty organization when a later membership has projects', () => {+ expect(+ defaultAuthenticatedPath(+ [{ id: 10 }, { id: 20 }],+ [+ { id: 'second-a', organizationId: 20 },+ { id: 'second-b', organizationId: 20 }+ ]+ )+ ).toBe('/organization?organizationId=20');+ });+});++describe('authenticatedLandingPath', () => {+ it('uses the default destination for an absent or root return path', () => {+ const organizations = [{ id: 10 }];+ const projects = [+ { id: 'one', organizationId: 10 },+ { id: 'two', organizationId: 10 }+ ];++ expect(authenticatedLandingPath(null, organizations, projects)).toBe(+ '/organization?organizationId=10'+ );+ expect(authenticatedLandingPath('/', organizations, projects)).toBe(+ '/organization?organizationId=10'+ );+ });++ it('preserves a safe explicit destination', () => {+ expect(authenticatedLandingPath('/issues?projectId=one', [{ id: 10 }], [])).toBe(+ '/issues?projectId=one'+ );+ });+});diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.tsindex 7aae4a43..6ac4eb85 100644--- a/frontend/src/lib/utils/navigation.ts+++ b/frontend/src/lib/utils/navigation.ts@@ -3,6 +3,8 @@ import { resolve } from '$app/paths';import { splitHref } from './links';+export { authenticatedLandingPath, defaultAuthenticatedPath, safeLocalPath } from './landing';+export function gotoHref(href: string, options?: Parameters<typeof goto>[1]) {const { pathname, suffix } = splitHref(href);let destination = resolve((pathname || '/') as '/');@@ -10,23 +12,6 @@ export function gotoHref(href: string, options?: Parameters<typeof goto>[1]) {return goto(destination, options);}-// Only allow same-origin, absolute-path redirects. Reject absolute URLs-// (https://evil.com), protocol-relative (//evil.com), and backslash tricks-// (/\evil.com) so returnTo can't be used as an open redirect.-export function safeLocalPath(raw: string | null): string {- if (!raw) return '/';- let decoded: string;- try {- decoded = decodeURIComponent(raw);- } catch {- return '/';- }- if (!decoded.startsWith('/') || decoded.startsWith('//') || decoded.startsWith('/\\')) {- return '/';- }- return decoded;-}-// SSO logins bounce through the provider and land on /auth/callback, losing// any ?returnTo= the login page had. Stash it in sessionStorage before leaving// and consume it when the callback (or finish-setup) decides where to land.diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelteindex 99bc7043..f929ebc3 100644--- a/frontend/src/routes/+layout.svelte+++ b/frontend/src/routes/+layout.svelte@@ -3,7 +3,7 @@import './layout.css';import { goto, afterNavigate } from '$app/navigation';import { authState } from '$lib/state/auth.svelte';- import { projectsState, type Project } from '$lib/state/projects.svelte';+ import { projectsState } from '$lib/state/projects.svelte';import { themeState, initTheme, toggleTheme } from '$lib/state/theme.svelte';import { getTimezone } from '$lib/state/timezone.svelte';import { DateTime } from 'luxon';@@ -12,17 +12,15 @@import AddProjectModal from '$lib/components/add-project-modal.svelte';import EditProjectModal from '$lib/components/edit-project-modal.svelte';import DashboardCommand from '$lib/components/dashboard/dashboard-command.svelte';- import FrameworkIcon from '$lib/components/framework-icon.svelte';+ import OrganizationProjectSwitcher from '$lib/components/organization-project-switcher.svelte';import * as Sidebar from '$lib/components/ui/sidebar';import { Button } from '$lib/components/ui/button';- import { Sun, Moon, LogOut, Plus, Check, Pencil } from '@lucide/svelte';+ import { Sun, Moon, LogOut } from '@lucide/svelte';import { WarningCallout } from '$lib/components/ui/warning-callout';import { onMount } from 'svelte';- import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';- import { ChevronDown } from '@lucide/svelte';import { Toaster, toast } from 'svelte-sonner';import { page } from '$app/state';- import { gotoHref } from '$lib/utils/navigation';+ import { defaultAuthenticatedPath, gotoHref } from '$lib/utils/navigation';import { setupTraceway } from '@tracewayapp/svelte';import { captureException } from '@tracewayapp/frontend';import * as Tooltip from '$lib/components/ui/tooltip';@@ -46,7 +44,7 @@if ((e.metaKey || e.ctrlKey) && e.key === 'k') {if (!authState.isAuthenticated || isPublicPath(page.url.pathname)) return;if (isMacPlatform && !e.metaKey) return;- if (page.url.pathname === '/dashboards') return;+ if (page.url.pathname === '/dashboards' || isOrganizationPath(page.url.pathname)) return;e.preventDefault();showCommandPalette = !showCommandPalette;}@@ -56,14 +54,38 @@let sidebarOpen = $state(localStorage.getItem(SIDEBAR_OPEN_KEY) !== 'false');let CrossSiteNotificationBanner = $state<Component<{ organizationId: number }> | null>(null);- const bannerOrganizationId = $derived(projectsState.currentProject?.organizationId ?? null);+ function isOrganizationPath(pathname: string): boolean {+ return pathname === '/organization' || pathname.startsWith('/organization/');+ }++ const organizationPage = $derived(isOrganizationPath(page.url.pathname));+ const selectedOrganizationId = $derived.by(() => {+ if (!organizationPage) return null;+ const value = Number(page.url.searchParams.get('organizationId'));+ if (+ Number.isInteger(value) &&+ authState.organizations.some((organization) => organization.id === value)+ ) {+ return value;+ }+ return authState.organizations[0]?.id ?? null;+ });+ const contextOrganizationId = $derived(+ organizationPage+ ? selectedOrganizationId+ : (projectsState.currentProject?.organizationId ?? null)+ );+ const bannerOrganizationId = $derived(contextOrganizationId);// Warn when the browser's timezone renders times differently from the// organization's timezone (all timestamps are shown in the org timezone).// Compare offsets, not zone names — Europe/Berlin vs Europe/Belgrade is// not a mismatch worth warning about.const browserZone = Intl.DateTimeFormat().resolvedOptions().timeZone;- const orgZone = $derived(getTimezone());+ const orgZone = $derived(+ (contextOrganizationId ? authState.getTimezoneForOrganization(contextOrganizationId) : null) ||+ getTimezone()+ );const timezoneMismatch = $derived.by(() => {if (!orgZone || orgZone === browserZone) return false;const now = Date.now();@@ -144,6 +166,29 @@}});+ const landingOwnsRoot = $derived(+ authState.isAuthenticated &&+ projectsState.projects.length > 0 &&+ defaultAuthenticatedPath(authState.organizations, projectsState.projects).startsWith(+ '/organization'+ )+ );++ $effect(() => {+ if (+ !authState.isAuthenticated ||+ page.url.pathname !== '/' ||+ page.url.searchParams.has('projectId') ||+ projectsState.projects.length === 0+ ) {+ return;+ }+ const destination = defaultAuthenticatedPath(authState.organizations, projectsState.projects);+ if (destination !== '/') {+ gotoHref(destination, { replaceState: true });+ }+ });+// Track navigation depth for smart back buttonslet lastPathname = '';afterNavigate((navigation) => {@@ -172,6 +217,8 @@if (authState.isAuthenticated &&!isPublicPath(newPathname) &&+ !isOrganizationPath(newPathname) &&+ !(newPathname === '/' && landingOwnsRoot) &&projectsState.currentProjectId &&!newUrl.searchParams.get('projectId')) {@@ -209,10 +256,6 @@goto(resolve('/login'));}- function handleProjectSelect(projectId: string) {- gotoHref(`/?projectId=${projectId}`);- }-function handleAddProjectClick() {const orgs = authState.organizations;if (orgs.length > 0 && orgs.every((o) => o.role === 'readonly')) {@@ -224,48 +267,65 @@function handleProjectCreated() {showAddProjectModal = false;- // Optionally navigate to connection page to show tokengoto(resolve('/connection'));}-- const multiOrg = $derived(authState.organizations.length > 1);-- const groupedProjects = $derived.by(() => {- const groups: { key: string; name: string; projects: Project[] }[] = [];- for (const org of authState.organizations) {- const projects = projectsState.projects.filter((p) => p.organizationId === org.id);- if (projects.length > 0) {- groups.push({ key: `org-${org.id}`, name: org.name, projects });- }- }- const knownOrgIds = new Set(authState.organizations.map((o) => o.id));- const orphans = projectsState.projects.filter(- (p) => !p.organizationId || !knownOrgIds.has(p.organizationId)- );- if (orphans.length > 0) {- groups.push({ key: 'other', name: 'Other', projects: orphans });- }- return groups;- });</script><svelte:head><title>Traceway</title></svelte:head><svelte:window onkeydown={handleGlobalKeydown} />-{#snippet projectItem(project: Project, indent: boolean)}- <DropdownMenu.Item- onclick={() => handleProjectSelect(project.id)}- class="flex cursor-pointer items-center justify-between {indent ? 'pl-4' : ''}"- >- <div class="flex items-center gap-2">- <FrameworkIcon framework={project.framework} />- <span>{project.name}</span>+{#snippet accountActions()}+ <div class="ml-auto flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ onclick={toggleTheme}+ title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}+ >+ {#if themeState.isDark}+ <Sun class="h-5 w-5" />+ {:else}+ <Moon class="h-5 w-5" />+ {/if}+ </Button>+ <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">+ <LogOut class="h-5 w-5" />+ </Button>+ </div>+{/snippet}++{#snippet contextNotices()}+ {#if timezoneMismatch}+ <WarningCallout class="mb-4" title="Your browser's timezone differs from the organization's">+ All times are shown in the organization's timezone ({zoneLabel(orgZone)}). Your browser is on {zoneLabel(+ browserZone+ )}.+ </WarningCallout>+ {/if}+ {#if CrossSiteNotificationBanner && bannerOrganizationId !== null}+ <div class="mb-4">+ <CrossSiteNotificationBanner organizationId={bannerOrganizationId} /></div>- {#if project.id === projectsState.currentProjectId}- <Check class="h-4 w-4" />- {/if}- </DropdownMenu.Item>+ {/if}+{/snippet}++{#snippet authenticatedOverlays()}+ <AddProjectModal+ open={showAddProjectModal}+ onOpenChange={(open) => (showAddProjectModal = open)}+ onProjectCreated={handleProjectCreated}+ initialOrganizationId={organizationPage ? selectedOrganizationId : null}+ />++ <EditProjectModal+ open={showEditProjectModal}+ onOpenChange={(open) => (showEditProjectModal = open)}+ project={projectsState.currentProject}+ />++ <DashboardCommand bind:open={showCommandPalette} />+ <Toaster position="top-center" />{/snippet}<Tooltip.Provider delayDuration={0}>@@ -279,29 +339,49 @@{:else}<img src="/traceway-logo.png" alt="Traceway Logo" class="h-7 w-auto" />{/if}- <div class="flex items-center gap-2">- <Button- variant="ghost"- size="icon"- onclick={toggleTheme}- title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}- >- {#if themeState.isDark}- <Sun class="h-5 w-5" />- {:else}- <Moon class="h-5 w-5" />- {/if}- </Button>- <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">- <LogOut class="h-5 w-5" />- </Button>- </div>+ {@render accountActions()}</header><main class="flex flex-1 justify-center px-4 py-10">{@render children()}</main></div><Toaster position="top-center" />+ {:else if authState.isAuthenticated && !isPublicPath(page.url.pathname) && organizationPage}+ <div class="min-h-screen bg-background">+ <header+ class="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/80 sm:px-4"+ >+ {#if themeState.isDark}+ <img+ src="/traceway-logo-white.svg"+ alt="Traceway Logo"+ class="hidden h-7 w-auto shrink-0 sm:block"+ />+ {:else}+ <img+ src="/traceway-logo.png"+ alt="Traceway Logo"+ class="hidden h-7 w-auto shrink-0 sm:block"+ />+ {/if}+ <img+ src="/traceway-mark.png"+ alt="Traceway Logo"+ class="size-7 shrink-0 object-contain sm:hidden dark:invert"+ />+ <div class="mx-1 h-5 w-px shrink-0 bg-border"></div>+ <OrganizationProjectSwitcher+ onAddProject={handleAddProjectClick}+ onEditProject={() => (showEditProjectModal = true)}+ />+ {@render accountActions()}+ </header>+ <main class="mx-auto w-full max-w-[1600px] p-4 sm:p-6">+ {@render contextNotices()}+ {@render children()}+ </main>+ </div>+ {@render authenticatedOverlays()}{:else if authState.isAuthenticated && !isPublicPath(page.url.pathname)}<Sidebar.SidebarProviderbind:open={sidebarOpen}@@ -314,114 +394,19 @@><Sidebar.SidebarTrigger /><div class="h-4 w-px bg-border"></div>- <div class="text-lg font-semibold">- <DropdownMenu.Root>- <DropdownMenu.Trigger- class="flex flex-row items-center gap-2 rounded-md px-2 py-1 transition-colors hover:bg-accent hover:text-accent-foreground"- >- {#if projectsState.currentProject}- <FrameworkIcon- framework={projectsState.currentProject.framework}- class="size-6 shrink-0"- />- {/if}- <span>{projectsState.currentProject?.name || 'Select Project'}</span>- <ChevronDown size={16} />- </DropdownMenu.Trigger>- <DropdownMenu.Content align="start" class="w-56">- {#if multiOrg}- {#each groupedProjects as group (group.key)}- <DropdownMenu.Group>- <DropdownMenu.Label class="text-xs text-muted-foreground uppercase"- >{group.name}</DropdownMenu.Label- >- {#each group.projects as project (project.id)}- {@render projectItem(project, true)}- {/each}- </DropdownMenu.Group>- {/each}- {:else}- <DropdownMenu.Group>- <DropdownMenu.Label>Projects</DropdownMenu.Label>- <DropdownMenu.Separator />- {#each projectsState.projects as project (project.id)}- {@render projectItem(project, false)}- {/each}- </DropdownMenu.Group>- {/if}- {#if projectsState.projects.length === 0}- <DropdownMenu.Item disabled>No projects yet</DropdownMenu.Item>- {/if}- <DropdownMenu.Separator />- {#if projectsState.canManageCurrentProject}- <DropdownMenu.Item- onclick={() => (showEditProjectModal = true)}- class="cursor-pointer"- >- <Pencil class="mr-2 h-4 w-4" />- Edit Project- </DropdownMenu.Item>- {/if}- <DropdownMenu.Item onclick={handleAddProjectClick} class="cursor-pointer">- <Plus class="mr-2 h-4 w-4" />- Add Project- </DropdownMenu.Item>- </DropdownMenu.Content>- </DropdownMenu.Root>- </div>- <div class="ml-auto flex items-center gap-2">- <Button- variant="ghost"- size="icon"- onclick={toggleTheme}- title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}- >- {#if themeState.isDark}- <Sun class="h-5 w-5" />- {:else}- <Moon class="h-5 w-5" />- {/if}- </Button>- <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">- <LogOut class="h-5 w-5" />- </Button>- </div>+ <OrganizationProjectSwitcher+ onAddProject={handleAddProjectClick}+ onEditProject={() => (showEditProjectModal = true)}+ />+ {@render accountActions()}</header><main class="min-w-0 flex-1 p-4">- {#if timezoneMismatch}- <WarningCallout- class="mb-4"- title="Your browser's timezone differs from the organization's"- >- All times are shown in the organization's timezone ({zoneLabel(orgZone)}). Your- browser is on {zoneLabel(browserZone)}.- </WarningCallout>- {/if}- {#if CrossSiteNotificationBanner && bannerOrganizationId !== null}- <div class="mb-4">- <CrossSiteNotificationBanner organizationId={bannerOrganizationId} />- </div>- {/if}+ {@render contextNotices()}{@render children()}</main></Sidebar.SidebarInset></Sidebar.SidebarProvider>-- <AddProjectModal- open={showAddProjectModal}- onOpenChange={(open) => (showAddProjectModal = open)}- onProjectCreated={handleProjectCreated}- />-- <EditProjectModal- open={showEditProjectModal}- onOpenChange={(open) => (showEditProjectModal = open)}- project={projectsState.currentProject}- />-- <DashboardCommand bind:open={showCommandPalette} />-- <Toaster position="top-center" />+ {@render authenticatedOverlays()}{:else if isPublicPath(page.url.pathname)}<main class="h-screen w-screen">{@render children()}diff --git a/frontend/src/routes/auth/callback/+page.svelte b/frontend/src/routes/auth/callback/+page.svelteindex 4bd3d17f..ee196d40 100644--- a/frontend/src/routes/auth/callback/+page.svelte+++ b/frontend/src/routes/auth/callback/+page.svelte@@ -4,7 +4,7 @@import { onMount } from 'svelte';import { authState } from '$lib/state/auth.svelte';import { projectsState } from '$lib/state/projects.svelte';- import { consumeSsoReturnTo, gotoHref, safeLocalPath } from '$lib/utils/navigation';+ import { authenticatedLandingPath, consumeSsoReturnTo, gotoHref } from '$lib/utils/navigation';import { ErrorAlert } from '$lib/components/ui/error-alert';import { LoadingCircle } from '$lib/components/ui/loading-circle';@@ -42,7 +42,13 @@const data = await response.json();authState.setOrganizations(data.organizations || []);projectsState.setProjects(data.projects || []);- gotoHref(safeLocalPath(consumeSsoReturnTo()));+ gotoHref(+ authenticatedLandingPath(+ consumeSsoReturnTo(),+ data.organizations || [],+ data.projects || []+ )+ );} catch {authState.logout();error = 'Failed to load your account. Please try logging in again.';diff --git a/frontend/src/routes/dashboards/+page.svelte b/frontend/src/routes/dashboards/+page.svelteindex 6f4f9449..62a31b5f 100644--- a/frontend/src/routes/dashboards/+page.svelte+++ b/frontend/src/routes/dashboards/+page.svelte@@ -13,7 +13,8 @@import WidgetGrid from '$lib/components/dashboard/widget-grid.svelte';import WidgetConfigPanel from '$lib/components/dashboard/widget-config-panel.svelte';import DashboardCommand from '$lib/components/dashboard/dashboard-command.svelte';- import { replaceState } from '$app/navigation';+ import InstanceFilter from '$lib/components/dashboard/instance-filter.svelte';+ import { afterNavigate, replaceState } from '$app/navigation';import { page } from '$app/state';import { api } from '$lib/api';import { projectsState } from '$lib/state/projects.svelte';@@ -178,6 +179,26 @@? projectsState.projects.filter((p) => p.organizationId === activeDashboard?.organizationId): []);+ let serverScope = $state(page.url.searchParams.get('server')?.trim() ?? '');+ const scopeTagFilters = $derived.by(+ (): Record<string, string> => (serverScope ? { server_name: serverScope } : {})+ );++ function setServerScope(scope: string) {+ const normalized = scope.trim();+ const url = new URL(window.location.href);+ if (normalized) {+ url.searchParams.set('server', normalized);+ } else {+ url.searchParams.delete('server');+ }+ serverScope = normalized;+ replaceState(url.pathname + url.search + url.hash, {});+ }++ function updateDashboardUrl(params: Record<string, string>) {+ updateUrl(serverScope ? { ...params, server: serverScope } : params);+ }function reloadDashboardWidgets() {if (selectedPreset) {@@ -688,9 +709,9 @@sharedTimeDomain = [new Date(getFromDateTimeUTC()), new Date(getToDateTimeUTC())];if (selectedPreset) {- updateUrl({ preset: selectedPreset });+ updateDashboardUrl({ preset: selectedPreset });} else {- updateUrl({ from: getFromDateTimeUTC(), to: getToDateTimeUTC() });+ updateDashboardUrl({ from: getFromDateTimeUTC(), to: getToDateTimeUTC() });}}@@ -701,7 +722,7 @@toDate = new CalendarDate(to.getFullYear(), to.getMonth() + 1, to.getDate());toTime = `${String(to.getHours()).padStart(2, '0')}:${String(to.getMinutes()).padStart(2, '0')}`;sharedTimeDomain = [from, to];- updateUrl({ from: getFromDateTimeUTC(), to: getToDateTimeUTC() });+ updateDashboardUrl({ from: getFromDateTimeUTC(), to: getToDateTimeUTC() });}async function loadMetrics() {@@ -903,8 +924,15 @@const activeTabName = $derived(dashboards.find((d) => String(d.id) === activeTabId)?.name ?? '');let handledSearch = '';+ let routerReady = $state(false);++ afterNavigate(() => {+ routerReady = true;+ serverScope = page.url.searchParams.get('server')?.trim() ?? '';+ });$effect(() => {+ if (!routerReady) return;const search = page.url.search;if (search === handledSearch) return;handledSearch = search;@@ -993,6 +1021,13 @@{isMac ? '⌘' : 'Ctrl'}K</kbd></button>+ <InstanceFilter+ value={serverScope}+ from={getFromDateTimeUTC()}+ to={getToDateTimeUTC()}+ projectId={projectsState.currentProjectId}+ onValueChange={setServerScope}+ /><TimeRangePickerbind:fromDatebind:toDate@@ -1207,6 +1242,7 @@fromDateUTC={getFromDateTimeUTC()}toDateUTC={getToDateTimeUTC()}timeDomain={sharedTimeDomain}+ {scopeTagFilters}onEditWidget={(w) => openEditWidget(w as Widget)}onDeleteWidget={(w) => openDeleteWidgetDialog(w as Widget)}onReorderWidgets={handleReorderWidgets}diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelteindex aa7cd159..5de0e430 100644--- a/frontend/src/routes/login/+page.svelte+++ b/frontend/src/routes/login/+page.svelte@@ -1,7 +1,7 @@<script lang="ts">import { resolve } from '$app/paths';import { goto } from '$app/navigation';- import { gotoHref } from '$lib/utils/navigation';+ import { authenticatedLandingPath, gotoHref } from '$lib/utils/navigation';import { page } from '$app/state';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';@@ -13,7 +13,6 @@import { themeState } from '$lib/state/theme.svelte';import { toast } from 'svelte-sonner';import OauthButtons from '$lib/components/oauth-buttons.svelte';- import { safeLocalPath } from '$lib/utils/navigation';const ERROR_MESSAGES: Record<string, string> = {oauth_failed: 'Sign-in failed. Please try again.',@@ -92,8 +91,7 @@authState.setOrganizations(data.organizations || []);projectsState.setProjects(data.projects);- // Redirect to returnTo if provided (validated same-origin), otherwise dashboard- gotoHref(safeLocalPath(returnTo));+ gotoHref(authenticatedLandingPath(returnTo, data.organizations || [], data.projects || []));} catch (e) {error = e instanceof Error ? e.message : 'Invalid email or password';} finally {diff --git a/frontend/src/routes/organization/+page.svelte b/frontend/src/routes/organization/+page.sveltenew file mode 100644index 00000000..18b6a2ca--- /dev/null+++ b/frontend/src/routes/organization/+page.svelte@@ -0,0 +1,96 @@+<script lang="ts">+ import { page } from '$app/state';+ import { authState } from '$lib/state/auth.svelte';+ import { setTabParam } from '$lib/utils/url-params';+ import { gotoHref } from '$lib/utils/navigation';+ import PageTabs from '$lib/components/traceway/page-tabs.svelte';+ import InfoCallout from '$lib/components/traceway/info-callout.svelte';+ import PageHeader from '$lib/components/traceway/page-header.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import OverviewTab from './overview-tab.svelte';+ import IssuesTab from './issues-tab.svelte';+ import MonitorsTab from './monitors-tab.svelte';+ import ProjectsTab from './projects-tab.svelte';++ const TABS = [+ { value: 'overview', label: 'Overview' },+ { value: 'issues', label: 'Issues' },+ { value: 'monitors', label: 'Monitors' },+ { value: 'projects', label: 'Projects' }+ ];++ const TAB_DESCRIPTIONS: Record<string, string> = {+ issues: 'Recently active issues from every project, ordered by the last event received.',+ monitors:+ 'All monitors from every project in the organization in one list, with their current status, uptime, and recent incidents.',+ projects:+ 'Every project in the organization, with its framework and your effective access level.'+ };++ const orgs = $derived(authState.organizations);++ const currentOrganizationId = $derived.by(() => {+ const value = Number(page.url.searchParams.get('organizationId'));+ if (Number.isInteger(value) && orgs.some((organization) => organization.id === value)) {+ return value;+ }+ return orgs[0]?.id ?? null;+ });++ const currentOrganizationName = $derived(+ orgs.find((o) => o.id === currentOrganizationId)?.name ?? ''+ );++ const activeTab = $derived.by(() => {+ const tab = page.url.searchParams.get('tab') || 'overview';+ return TABS.some((t) => t.value === tab) ? tab : 'overview';+ });++ function setTab(tab: string) {+ setTabParam(tab);+ }++ $effect(() => {+ const organizationId = currentOrganizationId;+ if (organizationId === null) return;+ if (+ page.url.searchParams.get('organizationId') === String(organizationId) &&+ !page.url.searchParams.has('projectId')+ ) {+ return;+ }+ const url = new URL(page.url);+ url.searchParams.set('organizationId', String(organizationId));+ url.searchParams.delete('projectId');+ gotoHref(url.pathname + url.search, {+ replaceState: true,+ noScroll: true,+ keepFocus: true+ });+ });+</script>++<div class="space-y-4">+ <PageHeader+ title={currentOrganizationName || 'Organization'}+ description="Live instance health, active response, and telemetry across every project."+ />++ <PageTabs tabs={TABS} {activeTab} onTabChange={setTab} />++ {#if TAB_DESCRIPTIONS[activeTab]}+ <InfoCallout>{TAB_DESCRIPTIONS[activeTab]}</InfoCallout>+ {/if}++ {#if currentOrganizationId === null}+ <EmptyState message="You are not a member of any organization yet." />+ {:else if activeTab === 'overview'}+ <OverviewTab organizationId={currentOrganizationId} />+ {:else if activeTab === 'issues'}+ <IssuesTab organizationId={currentOrganizationId} />+ {:else if activeTab === 'monitors'}+ <MonitorsTab organizationId={currentOrganizationId} />+ {:else if activeTab === 'projects'}+ <ProjectsTab organizationId={currentOrganizationId} />+ {/if}+</div>diff --git a/frontend/src/routes/organization/issues-tab.svelte b/frontend/src/routes/organization/issues-tab.sveltenew file mode 100644index 00000000..25bc61d8--- /dev/null+++ b/frontend/src/routes/organization/issues-tab.svelte@@ -0,0 +1,135 @@+<script lang="ts">+ import { api } from '$lib/api';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import * as Table from '$lib/components/ui/table';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import { getErrorMessage } from '$lib/utils/errors';+ import { formatRelativeTimeAgo } from '$lib/utils/formatters';+ import { createRowClickHandler } from '$lib/utils/navigation';++ interface OrgIssueRow {+ exceptionHash: string;+ stackTrace: string;+ lastSeen: string;+ firstSeen: string;+ count: number;+ projectId: string;+ projectName: string;+ }++ let { organizationId }: { organizationId: number } = $props();++ let issues = $state<OrgIssueRow[]>([]);+ let totalGroups = $state(0);+ let loading = $state(true);+ let error = $state('');+ let loadGeneration = 0;++ function loadIssues(orgId: number) {+ const generation = ++loadGeneration;+ loading = true;+ error = '';+ api+ .get(`/organizations/${orgId}/overview/issues`)+ .then((response) => {+ if (generation !== loadGeneration) return;+ issues = response.issues || [];+ totalGroups = response.totalGroups || 0;+ })+ .catch((cause) => {+ if (generation !== loadGeneration) return;+ error = getErrorMessage(cause) || 'Failed to load issues';+ })+ .finally(() => {+ if (generation === loadGeneration) loading = false;+ });+ }++ $effect(() => {+ loadIssues(organizationId);+ });++ function issueTitle(row: OrgIssueRow): { type: string; message: string } {+ const firstLine = row.stackTrace.split('\n')[0];+ const colonIndex = firstLine.indexOf(':');+ return {+ type: colonIndex > 0 ? firstLine.slice(0, colonIndex) : firstLine,+ message: colonIndex > 0 ? firstLine.slice(colonIndex + 1).trim() : ''+ };+ }+</script>++<section class="space-y-3">+ <div class="flex flex-wrap items-baseline justify-between gap-2">+ <h2 class="text-lg font-semibold">Issues in the last 24 hours</h2>+ {#if !loading && !error}+ <span class="text-sm text-muted-foreground">+ {totalGroups.toLocaleString()}+ {totalGroups === 1 ? 'issue' : 'issues'} across the organization+ </span>+ {/if}+ </div>++ {#if loading}+ <div class="flex h-48 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {:else if error}+ <ErrorRetryBox message={error} onRetry={() => loadIssues(organizationId)} />+ {:else if issues.length === 0}+ <div class="rounded-md border py-16 text-center text-sm text-muted-foreground">+ No issues in the last 24 hours. All quiet.+ </div>+ {:else}+ <TableContainer minWidth="720px">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Issue" />+ <TracewayTableHeader label="Project" class="w-[180px]" />+ <TracewayTableHeader label="Events" class="w-[90px]" align="right" />+ <TracewayTableHeader label="Last seen" class="w-[150px]" align="right" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each issues as issue (issue.projectId + issue.exceptionHash)}+ {@const title = issueTitle(issue)}+ <Table.Row+ class="group cursor-pointer"+ onclick={createRowClickHandler(+ `/issues/${issue.exceptionHash}?projectId=${issue.projectId}`+ )}+ >+ <Table.Cell class="max-w-[520px] py-3">+ <div class="min-w-0">+ <div+ class="truncate text-[15px]/6 font-semibold text-foreground group-hover:text-primary dark:group-hover:text-blue-300"+ >+ {title.type}+ </div>+ {#if title.message}+ <div class="truncate text-sm text-muted-foreground">{title.message}</div>+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">{issue.projectName}</Table.Cell>+ <Table.Cell class="text-right font-semibold tabular-nums">+ {issue.count.toLocaleString()}+ </Table.Cell>+ <Table.Cell class="text-right text-sm text-muted-foreground">+ {formatRelativeTimeAgo(issue.lastSeen)}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ {#if totalGroups > issues.length}+ <p class="text-right text-xs text-muted-foreground">+ Showing the {issues.length} most recently active issues.+ </p>+ {/if}+ {/if}+</section>diff --git a/frontend/src/routes/organization/monitors-tab.svelte b/frontend/src/routes/organization/monitors-tab.sveltenew file mode 100644index 00000000..f6aff555--- /dev/null+++ b/frontend/src/routes/organization/monitors-tab.svelte@@ -0,0 +1,357 @@+<script lang="ts">+ import { SvelteMap } from 'svelte/reactivity';+ import { api } from '$lib/api';+ import { getErrorMessage } from '$lib/utils/errors';+ import { formatDurationMs, formatRelativeTimeAgo } from '$lib/utils/formatters';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { uptimeClass } from '$lib/utils/uptime';+ 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 { Badge } from '$lib/components/ui/badge';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import CheckStatusBadge from '$lib/components/synthetics/check-status-badge.svelte';+ import MonitorTypeBadge from '$lib/components/synthetics/monitor-type-badge.svelte';+ import {+ incidentDisplayTitle,+ type CheckOverview,+ type OrgIncident+ } from '$lib/state/monitors.svelte';+ import {+ getSortState,+ setSortState,+ handleSortClick,+ type SortDirection+ } from '$lib/utils/sort-storage';++ interface OrgMonitorRow extends CheckOverview {+ projectName: string;+ }++ type SortField = 'name' | 'project' | 'status' | 'uptime' | 'latency';++ let { organizationId }: { organizationId: number } = $props();++ let checks = $state<OrgMonitorRow[]>([]);+ let checksLoading = $state(true);+ let checksError = $state('');++ let incidents = $state<OrgIncident[]>([]);+ let incidentsLoading = $state(true);+ let incidentsError = $state('');+ let loadGeneration = 0;++ const SORT_STORAGE_KEY = 'org-monitors';+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'status', direction: 'asc' });+ let orderBy = $state<SortField>(initialSort.field as SortField);+ let sortDirection = $state<SortDirection>(initialSort.direction);++ async function loadChecks(orgId: number, generation: number) {+ checksLoading = true;+ checksError = '';+ try {+ const response = await api.get(`/organizations/${orgId}/overview/monitors`);+ if (generation !== loadGeneration) return;+ checks = response.checks || [];+ } catch (e) {+ if (generation !== loadGeneration) return;+ checksError = getErrorMessage(e) || 'Failed to load monitors';+ } finally {+ if (generation === loadGeneration) checksLoading = false;+ }+ }++ async function loadIncidents(orgId: number, generation: number) {+ incidentsLoading = true;+ incidentsError = '';+ try {+ const response = await api.get(`/organizations/${orgId}/incidents`);+ if (generation !== loadGeneration) return;+ incidents = response.incidents || [];+ } catch (e) {+ if (generation !== loadGeneration) return;+ incidentsError = getErrorMessage(e) || 'Failed to load incidents';+ } finally {+ if (generation === loadGeneration) incidentsLoading = false;+ }+ }++ $effect(() => {+ const orgId = organizationId;+ const generation = ++loadGeneration;+ loadChecks(orgId, generation);+ loadIncidents(orgId, generation);+ });++ function retryChecks() {+ loadChecks(organizationId, ++loadGeneration);+ }++ function retryIncidents() {+ loadIncidents(organizationId, ++loadGeneration);+ }++ function handleSort(field: SortField) {+ const newSort = handleSortClick(field, orderBy, sortDirection);+ orderBy = newSort.field as SortField;+ sortDirection = newSort.direction;+ setSortState(SORT_STORAGE_KEY, newSort);+ }++ function uptimePct(check: OrgMonitorRow): number | null {+ const agg = check.aggregates;+ if (!agg || agg.total === 0) return null;+ const measured = agg.total - agg.missed;+ if (measured === 0) return null;+ return (agg.up / measured) * 100;+ }++ const statusRank: Record<string, number> = { down: 0, unknown: 1, up: 2 };++ const lastIncidentByCheck = $derived.by(() => {+ const byCheck = new SvelteMap<number, OrgIncident>();+ for (const incident of incidents) {+ if (incident.checkId === null) continue;+ const existing = byCheck.get(incident.checkId);+ if (!existing || new Date(incident.startedAt) > new Date(existing.startedAt)) {+ byCheck.set(incident.checkId, incident);+ }+ }+ return byCheck;+ });++ const sortedChecks = $derived.by(() => {+ const direction = sortDirection === 'asc' ? 1 : -1;+ return [...checks].sort((a, b) => {+ switch (orderBy) {+ case 'project':+ return direction * a.projectName.localeCompare(b.projectName);+ case 'status': {+ const rankA = a.enabled ? statusRank[a.currentStatus] : 3;+ const rankB = b.enabled ? statusRank[b.currentStatus] : 3;+ return direction * (rankA - rankB);+ }+ case 'uptime':+ return direction * ((uptimePct(a) ?? -1) - (uptimePct(b) ?? -1));+ case 'latency':+ return (+ direction * ((a.aggregates?.avgLatencyMs ?? -1) - (b.aggregates?.avgLatencyMs ?? -1))+ );+ default:+ return direction * a.name.localeCompare(b.name);+ }+ });+ });+</script>++<div class="space-y-6">+ <section class="space-y-3">+ {#if checksLoading}+ <div class="flex h-48 items-center justify-center">+ <LoadingCircle size="xlg" />+ </div>+ {:else if checksError}+ <ErrorRetryBox message={checksError} onRetry={retryChecks} />+ {:else if checks.length === 0}+ <div class="rounded-md border py-16 text-center text-sm text-muted-foreground">+ No monitors in this organization yet. Create monitors from a project's Monitors page.+ </div>+ {:else}+ <TableContainer minWidth="920px">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader+ label="Name"+ sortField="name"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ />+ <TracewayTableHeader label="Type" class="w-[100px]" />+ <TracewayTableHeader+ label="Project"+ sortField="project"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[160px]"+ />+ <TracewayTableHeader+ label="Status"+ tooltip="Current state from the most recent probes"+ sortField="status"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[110px]"+ />+ <TracewayTableHeader+ label="Uptime"+ tooltip="Share of successful probes over the last 30 days (missed probes excluded)"+ sortField="uptime"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[160px]"+ />+ <TracewayTableHeader+ label="Avg latency"+ tooltip="Average probe latency over the last 30 days"+ sortField="latency"+ currentSortField={orderBy}+ {sortDirection}+ onSort={(field) => handleSort(field as SortField)}+ class="w-[120px]"+ />+ <TracewayTableHeader label="Last incident" class="w-[160px]" align="right" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each sortedChecks as check (check.id)}+ {@const uptime = uptimePct(check)}+ {@const lastIncident = lastIncidentByCheck.get(check.id)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `/monitors/${check.id}?projectId=${check.projectId}`+ )}+ >+ <Table.Cell class="font-medium whitespace-normal">+ {check.name}+ <div+ class="mt-0.5 max-w-[420px] truncate font-mono text-xs font-normal text-muted-foreground"+ >+ {#if check.checkType === 'http'}+ {check.config?.method || 'GET'}+ {check.config?.url}+ {:else if check.checkType === 'tcp'}+ {check.config?.host}:{check.config?.port}+ {:else}+ Playwright script+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell>+ <MonitorTypeBadge type={check.checkType} />+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">{check.projectName}</Table.Cell>+ <Table.Cell>+ <CheckStatusBadge status={check.currentStatus} enabled={check.enabled} />+ </Table.Cell>+ <Table.Cell>+ {#if uptime === null}+ <span class="text-muted-foreground">—</span>+ {:else}+ <div class="flex items-center gap-2">+ <span+ class="w-16 shrink-0 font-mono text-sm tabular-nums {uptimeClass(uptime)}"+ >+ {uptime.toFixed(uptime === 100 ? 0 : 2)}%+ </span>+ <div class="h-1.5 w-14 shrink-0 overflow-hidden rounded-full bg-muted">+ <div+ class="h-full rounded-full {uptime >= 99.9+ ? 'bg-green-500'+ : uptime >= 99+ ? 'bg-amber-500'+ : 'bg-red-500'}"+ style="width: {Math.max(uptime, 4)}%"+ ></div>+ </div>+ </div>+ {/if}+ </Table.Cell>+ <Table.Cell class="font-mono text-sm text-muted-foreground tabular-nums">+ {check.aggregates && check.aggregates.total - check.aggregates.missed > 0+ ? formatDurationMs(check.aggregates.avgLatencyMs)+ : '—'}+ </Table.Cell>+ <Table.Cell class="text-right text-sm text-muted-foreground">+ {#if lastIncident}+ {#if lastIncident.resolvedAt === null}+ <Badge variant="destructive">ongoing</Badge>+ {:else}+ {formatRelativeTimeAgo(lastIncident.startedAt)}+ {/if}+ {:else}+ —+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ {/if}+ </section>++ <section class="space-y-3">+ <h2 class="text-lg font-semibold">Recent incidents</h2>+ {#if incidentsLoading}+ <div class="flex h-32 items-center justify-center">+ <LoadingCircle size="lg" />+ </div>+ {:else if incidentsError}+ <ErrorRetryBox message={incidentsError} onRetry={retryIncidents} />+ {:else if incidents.length === 0}+ <div class="rounded-md border py-8 text-center text-sm text-muted-foreground">+ No incidents in the last 90 days.+ </div>+ {:else}+ <TableContainer minWidth="720px">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Incident" />+ <TracewayTableHeader label="Monitor" class="w-[200px]" />+ <TracewayTableHeader label="Started" class="w-[150px]" align="right" />+ <TracewayTableHeader label="Resolved" class="w-[150px]" align="right" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each incidents as incident (incident.id)}+ <Table.Row+ class={incident.checkId !== null && incident.projectId !== null+ ? 'cursor-pointer'+ : ''}+ onclick={incident.checkId !== null && incident.projectId !== null+ ? createRowClickHandler(+ `/monitors/${incident.checkId}?projectId=${incident.projectId}`+ )+ : undefined}+ >+ <Table.Cell class="max-w-[420px] py-3">+ <div class="min-w-0">+ <div class="truncate font-medium">{incidentDisplayTitle(incident)}</div>+ {#if incident.errorMessage}+ <div class="truncate text-xs text-muted-foreground">+ {incident.errorMessage}+ </div>+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ {incident.checkName || incident.statusPageName || '—'}+ </Table.Cell>+ <Table.Cell class="text-right text-sm text-muted-foreground">+ {formatRelativeTimeAgo(incident.startedAt)}+ </Table.Cell>+ <Table.Cell class="text-right text-sm">+ {#if incident.resolvedAt === null}+ <Badge variant="destructive">ongoing</Badge>+ {:else}+ <span class="text-muted-foreground">+ {formatRelativeTimeAgo(incident.resolvedAt)}+ </span>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ {/if}+ </section>+</div>diff --git a/frontend/src/routes/organization/overview-tab.svelte b/frontend/src/routes/organization/overview-tab.sveltenew file mode 100644index 00000000..2ad1b12e--- /dev/null+++ b/frontend/src/routes/organization/overview-tab.svelte@@ -0,0 +1,863 @@+<script lang="ts">+ import { resolve } from '$app/paths';+ import { api } from '$lib/api';+ import { getErrorMessage } from '$lib/utils/errors';+ import { formatRelativeTimeAgo } from '$lib/utils/formatters';+ import { createRowClickHandler } from '$lib/utils/navigation';+ import { getServerColor } from '$lib/utils/server-colors';+ import * as Table from '$lib/components/ui/table';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import PageBadges from '$lib/components/traceway/page-badges.svelte';+ import ResourceRing from '$lib/components/traceway/resource-ring.svelte';+ import Sparkline from '$lib/components/dashboard/sparkline.svelte';+ import type { MetricTrendPoint } from '$lib/types/dashboard';+ import type { OncallPage } from '$lib/state/oncall.svelte';+ import {+ Activity,+ ArrowDown,+ ArrowRight,+ ArrowUp,+ Boxes,+ CircleCheck,+ Cloud,+ RefreshCw,+ Search,+ Server,+ TriangleAlert+ } from '@lucide/svelte';++ interface OrgServerRow {+ serverName: string;+ projectId: string;+ projectName: string;+ cpuPct: number | null;+ memoryPct: number | null;+ diskPct: number | null;+ networkRxBps: number | null;+ networkTxBps: number | null;+ lastReportedAt: string;+ trend: { timestamp: string; value: number }[];+ telemetrySource: 'otel' | 'sdk';+ dashboardId: number | null;+ hostName: string;+ hostId: string;+ hostArch: string;+ osType: string;+ osDescription: string;+ cloudProvider: string;+ cloudRegion: string;+ k8sClusterName: string;+ k8sNodeName: string;+ }++ interface OrgPageRow extends OncallPage {+ projectName: string;+ }++ type FleetFilter = 'all' | 'attention' | 'stale' | 'healthy';+ type GroupMode = 'project' | 'cluster' | 'none';+ type InstanceState = 'critical' | 'warning' | 'stale' | 'healthy';++ interface ServerGroup {+ key: string;+ label: string;+ subtitle: string;+ servers: OrgServerRow[];+ }++ let { organizationId }: { organizationId: number } = $props();++ const FRESH_MS = 3 * 60 * 1000;+ const REFRESH_MS = 60 * 1000;++ let servers = $state<OrgServerRow[]>([]);+ let serversLoading = $state(true);+ let serversError = $state('');+ let serversPartial = $state(false);+ let refreshedAt = $state<string | null>(null);+ let refreshing = $state(false);++ let totalGroups = $state(0);+ let issuesLoading = $state(true);+ let issuesError = $state('');++ let pages = $state<OrgPageRow[]>([]);+ let openPagesCount = $state(0);+ let downMonitorsCount = $state(0);+ let pagesLoading = $state(true);+ let pagesError = $state('');++ let searchQuery = $state('');+ let fleetFilter = $state<FleetFilter>('all');+ let projectFilter = $state('all');+ let groupMode = $state<GroupMode>('project');+ let groupPreferenceInitializedFor = $state<number | null>(null);++ let now = $state(Date.now());+ let loadGeneration = 0;+ let activeOrganizationId: number | null = null;++ async function loadServers(orgId: number, generation: number, background: boolean) {+ if (!background) serversLoading = true;+ serversError = '';+ try {+ const response = await api.get(`/organizations/${orgId}/overview/servers`);+ if (generation !== loadGeneration) return;+ servers = response.servers || [];+ serversPartial = response.partial === true;+ refreshedAt = response.refreshedAt || new Date().toISOString();+ now = Date.now();+ } catch (e) {+ if (generation !== loadGeneration) return;+ serversError = getErrorMessage(e) || 'Failed to load instance health';+ } finally {+ if (generation === loadGeneration) serversLoading = false;+ }+ }++ async function loadIssues(orgId: number, generation: number, background: boolean) {+ if (!background) issuesLoading = true;+ issuesError = '';+ try {+ const response = await api.get(`/organizations/${orgId}/overview/issues`);+ if (generation !== loadGeneration) return;+ totalGroups = response.totalGroups || 0;+ } catch (e) {+ if (generation !== loadGeneration) return;+ issuesError = getErrorMessage(e) || 'Failed to load issues';+ } finally {+ if (generation === loadGeneration) issuesLoading = false;+ }+ }++ async function loadPages(orgId: number, generation: number, background: boolean) {+ if (!background) pagesLoading = true;+ pagesError = '';+ try {+ const response = await api.get(`/organizations/${orgId}/overview/pages`);+ if (generation !== loadGeneration) return;+ pages = response.pages || [];+ openPagesCount = response.openPagesCount || 0;+ downMonitorsCount = response.downMonitorsCount || 0;+ } catch (e) {+ if (generation !== loadGeneration) return;+ pagesError = getErrorMessage(e) || 'Failed to load on-call pages';+ } finally {+ if (generation === loadGeneration) pagesLoading = false;+ }+ }++ type RefreshMode = 'initial' | 'background' | 'manual';++ async function refreshOverview(orgId: number, mode: RefreshMode) {+ const generation = ++loadGeneration;+ const background = mode !== 'initial';+ if (mode === 'manual') refreshing = true;+ await Promise.all([+ loadServers(orgId, generation, background),+ loadIssues(orgId, generation, background),+ loadPages(orgId, generation, background)+ ]);+ if (generation === loadGeneration) refreshing = false;+ }++ $effect(() => {+ const orgId = organizationId;+ if (activeOrganizationId !== orgId) {+ activeOrganizationId = orgId;+ servers = [];+ serversPartial = false;+ refreshedAt = null;+ totalGroups = 0;+ pages = [];+ openPagesCount = 0;+ downMonitorsCount = 0;+ searchQuery = '';+ fleetFilter = 'all';+ projectFilter = 'all';+ groupMode = 'project';+ groupPreferenceInitializedFor = null;+ }+ void refreshOverview(orgId, 'initial');+ const timer = window.setInterval(() => void refreshOverview(orgId, 'background'), REFRESH_MS);+ return () => window.clearInterval(timer);+ });++ function isFresh(server: OrgServerRow): boolean {+ return now - new Date(server.lastReportedAt).getTime() <= FRESH_MS;+ }++ function atLeast(value: number | null, threshold: number): boolean {+ return value !== null && value >= threshold;+ }++ function instanceState(server: OrgServerRow): InstanceState {+ if (!isFresh(server)) return 'stale';+ if (+ atLeast(server.cpuPct, 95) ||+ atLeast(server.memoryPct, 95) ||+ atLeast(server.diskPct, 90)+ ) {+ return 'critical';+ }+ if (+ atLeast(server.cpuPct, 80) ||+ atLeast(server.memoryPct, 85) ||+ atLeast(server.diskPct, 80)+ ) {+ return 'warning';+ }+ return 'healthy';+ }++ const freshCount = $derived(servers.filter(isFresh).length);+ const staleCount = $derived(servers.length - freshCount);+ const attentionCount = $derived(+ servers.filter((server) => instanceState(server) !== 'healthy').length+ );+ const totalNetworkBps = $derived(+ servers.reduce(+ (total, server) => total + (server.networkRxBps ?? 0) + (server.networkTxBps ?? 0),+ 0+ )+ );+ const allServerNames = $derived(servers.map((server) => server.serverName));+ const hasKubernetesMetadata = $derived(servers.some((server) => !!server.k8sClusterName));+ const projectOptions = $derived.by(() => {+ const projects = new Map<string, string>();+ for (const server of servers) projects.set(server.projectId, server.projectName);+ return [...projects.entries()]+ .map(([id, name]) => ({ id, name }))+ .sort((a, b) => a.name.localeCompare(b.name));+ });++ $effect(() => {+ if (serversLoading || groupPreferenceInitializedFor === organizationId) return;+ groupMode = hasKubernetesMetadata ? 'cluster' : 'project';+ groupPreferenceInitializedFor = organizationId;+ });++ function stateRank(state: InstanceState): number {+ return { critical: 0, stale: 1, warning: 2, healthy: 3 }[state];+ }++ const visibleServers = $derived.by(() => {+ const query = searchQuery.trim().toLowerCase();+ return servers+ .filter((server) => {+ const state = instanceState(server);+ if (projectFilter !== 'all' && server.projectId !== projectFilter) return false;+ if (fleetFilter === 'attention' && state === 'healthy') return false;+ if (fleetFilter === 'stale' && state !== 'stale') return false;+ if (fleetFilter === 'healthy' && state !== 'healthy') return false;+ if (!query) return true;+ return [+ server.serverName,+ server.projectName,+ server.hostName,+ server.hostId,+ server.osType,+ server.osDescription,+ server.hostArch,+ server.cloudProvider,+ server.cloudRegion,+ server.k8sClusterName,+ server.k8sNodeName+ ]+ .join(' ')+ .toLowerCase()+ .includes(query);+ })+ .sort((a, b) => {+ const rank = stateRank(instanceState(a)) - stateRank(instanceState(b));+ if (rank !== 0) return rank;+ return a.serverName.localeCompare(b.serverName);+ });+ });++ const serverGroups = $derived.by((): ServerGroup[] => {+ if (groupMode === 'none') {+ return [{ key: 'all', label: 'All instances', subtitle: '', servers: visibleServers }];+ }++ const grouped = new Map<string, ServerGroup>();+ for (const server of visibleServers) {+ const cluster = server.k8sClusterName.trim();+ const key =+ groupMode === 'cluster'+ ? cluster+ ? `cluster:${cluster}`+ : 'cluster:ungrouped'+ : `project:${server.projectId}`;+ const label =+ groupMode === 'cluster' ? cluster || 'Not in a Kubernetes cluster' : server.projectName;+ let group = grouped.get(key);+ if (!group) {+ group = {+ key,+ label,+ subtitle: groupMode === 'cluster' && cluster ? 'Kubernetes cluster' : '',+ servers: []+ };+ grouped.set(key, group);+ }+ group.servers.push(server);+ }+ return [...grouped.values()].sort((a, b) => {+ if (a.key === 'cluster:ungrouped') return 1;+ if (b.key === 'cluster:ungrouped') return -1;+ return a.label.localeCompare(b.label);+ });+ });++ function toTrendPoints(trend: OrgServerRow['trend']): MetricTrendPoint[] {+ return (trend || []).map((point) => ({+ timestamp: new Date(point.timestamp),+ value: point.value+ }));+ }++ function formatByteRate(value: number | null): string {+ if (value === null) return '—';+ const units = ['B/s', 'KB/s', 'MB/s', 'GB/s'];+ let amount = Math.max(0, value);+ let unit = 0;+ while (amount >= 1000 && unit < units.length - 1) {+ amount /= 1000;+ unit++;+ }+ const precision = amount >= 100 ? 0 : amount >= 10 ? 1 : 2;+ return `${amount.toFixed(precision)} ${units[unit]}`;+ }++ function formatTotalNetwork(value: number): string {+ return servers.some((server) => server.networkRxBps !== null || server.networkTxBps !== null)+ ? formatByteRate(value)+ : '—';+ }++ function stateLabel(state: InstanceState): string {+ return { critical: 'Critical', warning: 'Warning', stale: 'Stale', healthy: 'Healthy' }[state];+ }++ function stateClasses(state: InstanceState): string {+ return {+ critical: 'bg-rose-500/10 text-rose-600 ring-rose-500/20 dark:text-rose-400',+ warning: 'bg-amber-500/10 text-amber-700 ring-amber-500/20 dark:text-amber-400',+ stale: 'bg-muted text-muted-foreground ring-border',+ healthy: 'bg-emerald-500/10 text-emerald-700 ring-emerald-500/20 dark:text-emerald-400'+ }[state];+ }++ function instanceHref(server: OrgServerRow): string {+ const params = new URLSearchParams({+ projectId: server.projectId,+ server: server.serverName,+ preset: '30m'+ });+ if (server.dashboardId) params.set('dashboard', String(server.dashboardId));+ return `${resolve('/dashboards')}?${params.toString()}`;+ }++ function organizationTabHref(tab: string): string {+ return `${resolve('/organization')}?organizationId=${organizationId}&tab=${tab}`;+ }++ function osLabel(server: OrgServerRow): string {+ const type = server.osType.trim();+ if (!type) return '';+ return type.charAt(0).toUpperCase() + type.slice(1);+ }++ const fleetHeadline = $derived.by(() => {+ if (serversLoading && servers.length === 0) return 'Reading the fleet heartbeat';+ if (serversError && servers.length === 0) return 'Fleet signal unavailable';+ if (servers.length === 0) return 'No instance telemetry yet';+ if (attentionCount > 0) {+ return `${attentionCount} ${attentionCount === 1 ? 'instance needs' : 'instances need'} attention`;+ }+ return 'Fleet is reporting normally';+ });+</script>++<div class="space-y-6">+ <section+ class="overflow-hidden rounded-xl border bg-card shadow-xs"+ aria-labelledby="fleet-pulse"+ >+ <div+ class="flex flex-col gap-4 px-5 py-5 sm:flex-row sm:items-start sm:justify-between sm:px-6"+ >+ <div class="flex min-w-0 items-start gap-3.5">+ <div+ class="mt-0.5 grid size-10 shrink-0 place-items-center rounded-xl {attentionCount > 0+ ? 'bg-amber-500/10 text-amber-600 dark:text-amber-400'+ : 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'}"+ >+ {#if attentionCount > 0}+ <TriangleAlert class="size-5" />+ {:else}+ <Activity class="size-5" />+ {/if}+ </div>+ <div class="min-w-0">+ <div class="text-xs font-semibold tracking-[0.16em] text-muted-foreground uppercase">+ Operational pulse+ </div>+ <h2 id="fleet-pulse" class="mt-1 text-xl font-semibold tracking-tight">+ {fleetHeadline}+ </h2>+ <p class="mt-1 text-sm text-muted-foreground">+ {#if refreshedAt}+ Updated {formatRelativeTimeAgo(refreshedAt)} · refreshes every minute+ {:else}+ Live resource health across every project+ {/if}+ </p>+ </div>+ </div>+ <Button+ variant="outline"+ size="sm"+ disabled={refreshing}+ onclick={() => void refreshOverview(organizationId, 'manual')}+ >+ <RefreshCw class="size-4 {refreshing ? 'animate-spin' : ''}" />+ Refresh+ </Button>+ </div>++ <div class="grid grid-cols-2 border-t sm:grid-cols-3 xl:grid-cols-6">+ <div class="border-r border-b px-5 py-4 xl:border-b-0">+ <div class="text-xs text-muted-foreground">Reporting now</div>+ <div+ class="mt-1 font-mono text-xl font-semibold text-emerald-600 tabular-nums dark:text-emerald-400"+ >+ {serversLoading && servers.length === 0 ? '—' : freshCount}+ </div>+ </div>+ <div class="border-r border-b px-5 py-4 sm:border-r xl:border-b-0">+ <div class="text-xs text-muted-foreground">Needs attention</div>+ <div+ class="mt-1 font-mono text-xl font-semibold tabular-nums {attentionCount > 0+ ? 'text-amber-600 dark:text-amber-400'+ : ''}"+ >+ {serversLoading && servers.length === 0 ? '—' : attentionCount}+ </div>+ </div>+ <div class="border-r border-b px-5 py-4 sm:border-r-0 xl:border-r xl:border-b-0">+ <div class="text-xs text-muted-foreground">Stale signals</div>+ <div class="mt-1 font-mono text-xl font-semibold tabular-nums">+ {serversLoading && servers.length === 0 ? '—' : staleCount}+ </div>+ </div>+ <div class="border-r border-b px-5 py-4 sm:border-b-0 xl:border-r">+ <div class="text-xs text-muted-foreground">Network I/O</div>+ <div class="mt-1 font-mono text-xl font-semibold tabular-nums">+ {formatTotalNetwork(totalNetworkBps)}+ </div>+ </div>+ <a+ href={organizationTabHref('issues')}+ class="group border-r px-5 py-4 transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none focus-visible:ring-inset"+ >+ <div class="flex items-center justify-between text-xs text-muted-foreground">+ Issues · 24h+ <ArrowRight class="size-3.5 opacity-0 transition-opacity group-hover:opacity-100" />+ </div>+ <div class="mt-1 font-mono text-xl font-semibold tabular-nums">+ {issuesLoading || issuesError ? '—' : totalGroups}+ </div>+ </a>+ <a+ href={organizationTabHref('monitors')}+ class="group px-5 py-4 transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none focus-visible:ring-inset"+ >+ <div class="flex items-center justify-between text-xs text-muted-foreground">+ Active response+ <ArrowRight class="size-3.5 opacity-0 transition-opacity group-hover:opacity-100" />+ </div>+ <div+ class="mt-1 font-mono text-xl font-semibold tabular-nums {openPagesCount ++ downMonitorsCount >+ 0+ ? 'text-rose-600 dark:text-rose-400'+ : ''}"+ >+ {pagesLoading || pagesError ? '—' : openPagesCount + downMonitorsCount}+ </div>+ </a>+ </div>+ </section>++ <section class="space-y-3" aria-labelledby="instances-heading">+ <div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">+ <div>+ <div class="flex items-center gap-2">+ <h2 id="instances-heading" class="text-lg font-semibold">Instances</h2>+ {#if !serversLoading}+ <span+ class="rounded-full bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground tabular-nums"+ >{servers.length}</span+ >+ {/if}+ </div>+ <p class="mt-0.5 text-sm text-muted-foreground">+ CPU, memory, storage, and network from the latest 30 minutes.+ </p>+ </div>++ {#if servers.length > 0}+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center">+ <div class="relative min-w-0 sm:w-56">+ <Search+ class="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"+ />+ <Input bind:value={searchQuery} placeholder="Find an instance" class="h-9 pl-9" />+ </div>+ <select+ bind:value={fleetFilter}+ aria-label="Filter instances by health"+ class="h-9 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <option value="all">All health states</option>+ <option value="attention">Needs attention</option>+ <option value="stale">Stale</option>+ <option value="healthy">Healthy</option>+ </select>+ {#if projectOptions.length > 1}+ <select+ bind:value={projectFilter}+ aria-label="Filter instances by project"+ class="h-9 max-w-48 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <option value="all">All projects</option>+ {#each projectOptions as project (project.id)}+ <option value={project.id}>{project.name}</option>+ {/each}+ </select>+ {/if}+ <select+ bind:value={groupMode}+ aria-label="Group instances"+ class="h-9 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <option value="project">Group by project</option>+ {#if hasKubernetesMetadata}+ <option value="cluster">Group by Kubernetes cluster</option>+ {/if}+ <option value="none">No grouping</option>+ </select>+ </div>+ {/if}+ </div>++ {#if serversPartial || (serversError && servers.length > 0)}+ <div+ class="flex items-center gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 px-4 py-2.5 text-sm text-amber-700 dark:text-amber-300"+ >+ <TriangleAlert class="size-4 shrink-0" />+ {serversPartial+ ? 'Some projects could not be read. The instances shown are still current.'+ : 'The last refresh failed. Showing the most recent snapshot.'}+ </div>+ {/if}++ {#if serversLoading && servers.length === 0}+ <div class="flex h-48 items-center justify-center rounded-xl border">+ <LoadingCircle size="lg" />+ </div>+ {:else if serversError && servers.length === 0}+ <div+ class="flex flex-col items-center justify-center gap-3 rounded-xl border py-12 text-center"+ >+ <TriangleAlert class="size-6 text-rose-500" />+ <div>+ <p class="font-medium">Instance health could not be loaded</p>+ <p class="mt-1 text-sm text-muted-foreground">{serversError}</p>+ </div>+ <Button+ variant="outline"+ size="sm"+ onclick={() => void refreshOverview(organizationId, 'initial')}>Retry</Button+ >+ </div>+ {:else if servers.length === 0}+ <div+ class="flex flex-col items-center justify-center rounded-xl border border-dashed py-12 text-center"+ >+ <div class="grid size-11 place-items-center rounded-xl bg-muted text-muted-foreground">+ <Server class="size-5" />+ </div>+ <p class="mt-3 font-medium">No instance telemetry in the last 30 minutes</p>+ <p class="mt-1 max-w-md text-sm text-muted-foreground">+ Install the Traceway OTel Agent on a host, or send server metrics with a unique service+ name.+ </p>+ </div>+ {:else if visibleServers.length === 0}+ <div class="rounded-xl border border-dashed py-10 text-center">+ <p class="font-medium">No instances match these filters</p>+ <button+ class="mt-2 text-sm font-medium text-primary hover:underline"+ onclick={() => {+ searchQuery = '';+ fleetFilter = 'all';+ projectFilter = 'all';+ }}+ >+ Clear filters+ </button>+ </div>+ {:else}+ <div class="overflow-hidden rounded-xl border bg-card shadow-xs">+ <div+ class="hidden grid-cols-[minmax(250px,1.7fr)_104px_104px_104px_minmax(155px,0.9fr)_125px_28px] items-center border-b bg-muted/30 px-4 py-2.5 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase lg:grid"+ >+ <div>Instance</div>+ <div class="text-center">CPU</div>+ <div class="text-center">Memory</div>+ <div class="text-center">Disk</div>+ <div>Network</div>+ <div>Last signal</div>+ <div></div>+ </div>++ {#each serverGroups as group (group.key)}+ <div+ class="flex items-center justify-between border-b bg-muted/20 px-4 py-2.5 last:border-b-0"+ >+ <div class="flex min-w-0 items-center gap-2">+ {#if groupMode === 'cluster' && group.key !== 'cluster:ungrouped'}+ <Boxes class="size-4 shrink-0 text-muted-foreground" />+ {:else}+ <Cloud class="size-4 shrink-0 text-muted-foreground" />+ {/if}+ <span class="truncate text-sm font-semibold">{group.label}</span>+ {#if group.subtitle}+ <span class="hidden text-xs text-muted-foreground sm:inline">{group.subtitle}</span>+ {/if}+ </div>+ <span class="font-mono text-xs text-muted-foreground tabular-nums"+ >{group.servers.length}</span+ >+ </div>++ {#each group.servers as server (server.projectId + server.serverName)}+ {@const state = instanceState(server)}+ <a+ href={instanceHref(server)}+ class="group/instance grid gap-4 border-b px-4 py-4 transition-colors last:border-b-0 hover:bg-muted/35 focus-visible:bg-muted/35 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none focus-visible:ring-inset lg:grid-cols-[minmax(250px,1.7fr)_104px_104px_104px_minmax(155px,0.9fr)_125px_28px] lg:items-center lg:gap-0 lg:py-3"+ >+ <div class="flex min-w-0 items-center gap-3">+ <div+ class="relative grid size-9 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground"+ >+ {#if server.k8sClusterName}+ <Boxes class="size-4" />+ {:else}+ <Server class="size-4" />+ {/if}+ <span+ class="absolute -right-0.5 -bottom-0.5 size-2.5 rounded-full border-2 border-card {state ===+ 'healthy'+ ? 'bg-emerald-500'+ : state === 'warning'+ ? 'bg-amber-500'+ : state === 'critical'+ ? 'bg-rose-500'+ : 'bg-muted-foreground'}"+ ></span>+ </div>+ <div class="min-w-0 flex-1">+ <div class="flex min-w-0 items-center gap-2">+ <span class="truncate font-mono text-sm font-semibold">{server.serverName}</span+ >+ <span+ class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1 ring-inset {stateClasses(+ state+ )}">{stateLabel(state)}</span+ >+ </div>+ <div+ class="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground"+ >+ {#if groupMode !== 'project'}<span class="truncate">{server.projectName}</span+ >{/if}+ {#if server.hostName && server.hostName !== server.serverName}<span+ class="font-mono">{server.hostName}</span+ >{/if}+ {#if osLabel(server)}<span title={server.osDescription || undefined}+ >{osLabel(server)}{#if server.hostArch}+ · {server.hostArch}{/if}</span+ >{/if}+ {#if server.cloudRegion}<span>{server.cloudRegion}</span>{/if}+ {#if server.k8sNodeName}<span>node {server.k8sNodeName}</span>{/if}+ <span>{server.telemetrySource === 'otel' ? 'OTel Agent' : 'SDK metrics'}</span>+ </div>+ </div>+ </div>++ <div class="grid grid-cols-3 gap-3 lg:contents">+ <div class="flex flex-col items-center gap-1">+ <span+ class="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase lg:hidden"+ >CPU</span+ >+ <ResourceRing label="CPU" value={server.cpuPct} size="sm" />+ {#if server.trend.length > 1}+ <div class="hidden h-3 w-14 lg:block">+ <Sparkline+ data={toTrendPoints(server.trend)}+ color={getServerColor(server.serverName, allServerNames)}+ height={12}+ />+ </div>+ {/if}+ </div>+ <div class="flex flex-col items-center gap-1">+ <span+ class="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase lg:hidden"+ >Memory</span+ >+ <ResourceRing label="Memory" value={server.memoryPct} warningAt={85} size="sm" />+ </div>+ <div class="flex flex-col items-center gap-1">+ <span+ class="text-[10px] font-semibold tracking-wider text-muted-foreground uppercase lg:hidden"+ >Disk</span+ >+ <ResourceRing+ label="Disk"+ value={server.diskPct}+ warningAt={80}+ criticalAt={90}+ size="sm"+ />+ </div>+ </div>++ <div+ class="grid grid-cols-2 gap-2 border-t pt-3 font-mono text-xs tabular-nums lg:block lg:border-0 lg:pt-0"+ >+ <div class="flex items-center gap-1.5 text-muted-foreground">+ <ArrowDown class="size-3.5 text-cyan-500" />+ <span>{formatByteRate(server.networkRxBps)}</span>+ </div>+ <div class="mt-0 flex items-center gap-1.5 text-muted-foreground lg:mt-1">+ <ArrowUp class="size-3.5 text-violet-500" />+ <span>{formatByteRate(server.networkTxBps)}</span>+ </div>+ </div>++ <div+ class="flex items-center justify-between gap-2 text-xs text-muted-foreground lg:block"+ >+ <span class="lg:hidden">Last signal</span>+ <span class="font-mono tabular-nums"+ >{formatRelativeTimeAgo(server.lastReportedAt)}</span+ >+ </div>+ <ArrowRight+ class="hidden size-4 text-muted-foreground transition-transform group-hover/instance:translate-x-0.5 group-hover/instance:text-foreground lg:block"+ />+ </a>+ {/each}+ {/each}+ </div>+ {/if}+ </section>++ <section class="space-y-3" aria-labelledby="pages-heading">+ <div class="flex items-center justify-between">+ <div>+ <h2 id="pages-heading" class="text-lg font-semibold">Active on-call response</h2>+ <p class="mt-0.5 text-sm text-muted-foreground">+ Pages that still need acknowledgement or resolution.+ </p>+ </div>+ {#if openPagesCount > 0}+ <span+ class="rounded-full bg-rose-500/10 px-2.5 py-1 font-mono text-xs font-semibold text-rose-600 tabular-nums dark:text-rose-400"+ >{openPagesCount} open</span+ >+ {/if}+ </div>++ {#if pagesLoading && pages.length === 0}+ <div class="flex h-28 items-center justify-center rounded-xl border">+ <LoadingCircle size="lg" />+ </div>+ {:else if pagesError && pages.length === 0}+ <div class="rounded-xl border py-8 text-center text-sm text-rose-500">{pagesError}</div>+ {:else if pages.length === 0}+ <div class="flex items-center gap-3 rounded-xl border bg-card px-5 py-4">+ <div+ class="grid size-9 shrink-0 place-items-center rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ >+ <CircleCheck class="size-5" />+ </div>+ <div>+ <p class="text-sm font-medium">No active pages</p>+ <p class="text-xs text-muted-foreground">Nobody is being paged right now.</p>+ </div>+ </div>+ {:else}+ <TableContainer minWidth="760px">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Page" />+ <TracewayTableHeader label="Project" class="w-[180px]" />+ <TracewayTableHeader label="Severity" class="w-[160px]" />+ <TracewayTableHeader label="Status" class="w-[130px]" />+ <TracewayTableHeader label="Opened" class="w-[150px]" align="right" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each pages as oncallPage (oncallPage.id)}+ <Table.Row+ class="cursor-pointer"+ onclick={createRowClickHandler(+ `/on-call?tab=pages&page=${oncallPage.id}&projectId=${oncallPage.projectId}`+ )}+ >+ <Table.Cell class="max-w-[420px] py-3">+ <div class="min-w-0">+ <div class="truncate font-medium">{oncallPage.subject}</div>+ {#if oncallPage.ruleName}+ <div class="truncate text-xs text-muted-foreground">+ {oncallPage.ruleName}+ </div>+ {/if}+ </div>+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ {oncallPage.projectName || '—'}+ </Table.Cell>+ <Table.Cell>+ <div class="flex flex-wrap gap-1">+ <PageBadges+ severity={oncallPage.severity}+ urgency={oncallPage.urgency}+ fallback+ />+ </div>+ </Table.Cell>+ <Table.Cell><PageBadges status={oncallPage.status} /></Table.Cell>+ <Table.Cell class="text-right text-sm text-muted-foreground">+ {formatRelativeTimeAgo(oncallPage.createdAt)}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ {/if}+ </section>+</div>diff --git a/frontend/src/routes/organization/projects-tab.svelte b/frontend/src/routes/organization/projects-tab.sveltenew file mode 100644index 00000000..034fd621--- /dev/null+++ b/frontend/src/routes/organization/projects-tab.svelte@@ -0,0 +1,96 @@+<script lang="ts">+ import { ArrowUpRight } from '@lucide/svelte';+ import { Badge } from '$lib/components/ui/badge';+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';+ import * as Table from '$lib/components/ui/table';+ import FrameworkIcon from '$lib/components/framework-icon.svelte';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import { authState } from '$lib/state/auth.svelte';+ import { getFrameworkLabel, projectsState, type Project } from '$lib/state/projects.svelte';+ import { formatRelativeTimeAgo } from '$lib/utils/formatters';+ import { createRowClickHandler } from '$lib/utils/navigation';++ let { organizationId }: { organizationId: number } = $props();++ const projects = $derived(+ projectsState.projects.filter((project) => project.organizationId === organizationId)+ );++ function projectRole(project: Project): string {+ return project.role || authState.getRoleForOrganization(organizationId) || 'user';+ }++ function roleLabel(role: string): string {+ switch (role) {+ case 'owner':+ return 'Owner';+ case 'admin':+ return 'Admin';+ case 'readonly':+ return 'Read only';+ default:+ return 'Member';+ }+ }+</script>++<section class="space-y-3">+ <div class="flex flex-wrap items-baseline justify-between gap-2">+ <h2 class="text-lg font-semibold">Projects</h2>+ <span class="text-sm text-muted-foreground">+ {projects.length.toLocaleString()}+ {projects.length === 1 ? 'project' : 'projects'} in this organization+ </span>+ </div>++ {#if projects.length === 0}+ <div class="rounded-md border py-16 text-center text-sm text-muted-foreground">+ No projects have been added to this organization yet.+ </div>+ {:else}+ <TableContainer minWidth="680px">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Project" />+ <TracewayTableHeader label="Framework" class="w-[200px]" />+ <TracewayTableHeader label="Access" class="w-[130px]" />+ <TracewayTableHeader label="Added" class="w-[150px]" align="right" />+ <TracewayTableHeader label="" class="w-[48px]" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each projects as project (project.id)}+ <Table.Row+ class="group cursor-pointer"+ onclick={createRowClickHandler(`/?projectId=${project.id}`)}+ >+ <Table.Cell>+ <div class="flex items-center gap-3">+ <div+ class="flex size-9 shrink-0 items-center justify-center rounded-md border bg-muted/30"+ >+ <FrameworkIcon framework={project.framework} class="size-5" />+ </div>+ <span class="font-medium group-hover:text-primary">{project.name}</span>+ </div>+ </Table.Cell>+ <Table.Cell class="text-sm text-muted-foreground">+ {getFrameworkLabel(project.framework)}+ </Table.Cell>+ <Table.Cell>+ <Badge variant="outline">{roleLabel(projectRole(project))}</Badge>+ </Table.Cell>+ <Table.Cell class="text-right text-sm text-muted-foreground">+ {formatRelativeTimeAgo(project.createdAt)}+ </Table.Cell>+ <Table.Cell>+ <ArrowUpRight class="size-4 text-muted-foreground group-hover:text-foreground" />+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ {/if}+</section>diff --git a/skills/traceway-setup/SKILL.md b/skills/traceway-setup/SKILL.mdindex 63679796..be90dea6 100644--- a/skills/traceway-setup/SKILL.md+++ b/skills/traceway-setup/SKILL.md@@ -679,7 +679,7 @@ curl -fsSL https://install.tracewayapp.com/install.sh | \- Re-running the installer upgrades in place, so the command is safe to keep in provisioning scripts.- If the repo has host provisioning or deploy scripts (cloud-init, Ansible, Terraform `user_data`, `deploy.sh`), add the command there with the token referenced from a secret. Otherwise hand the operator the filled-in one-liner; do not modify the repo.-Metrics arrive within ~60s under their hostmetrics names (`system.cpu.utilization`, `system.memory.usage`, ...). The host is identified by the `server_name` tag, which comes from `TRACEWAY_SERVICE_NAME`. Resource attributes such as `host.name` are not stored as tags at all, so give every host a distinct `TRACEWAY_SERVICE_NAME` or the hosts cannot be told apart. The metrics do NOT populate the built-in CPU/memory charts (those read the Go SDK's exact names). Install the **OTelemetry Server Agent** dashboard template instead: open the command palette with Cmd K, search for it, and it installs a dashboard already wired to `system.cpu.utilization`, `system.memory.*`, `system.filesystem.*`, `system.disk.*` and `system.network.*`. Custom widgets cover anything the template misses. Agent repo: https://github.com/tracewayapp/traceway-otel-agent+Metrics arrive within ~60s under their hostmetrics names (`system.cpu.utilization`, `system.memory.usage`, ...). The host is identified by the `server_name` tag, which comes from `TRACEWAY_SERVICE_NAME`; resource metadata such as `host.name`, `host.id`, `host.arch`, `os.type`, and cloud region is also retained, but it does not replace that canonical identity. Give every host a distinct `TRACEWAY_SERVICE_NAME` or the hosts cannot be told apart. The organization overview recognizes these hostmetrics directly, but the legacy Go SDK CPU/memory widgets still read their exact SDK metric names. Install the **OTelemetry Server Agent** dashboard template for the full set: open the command palette with Cmd K, search for it, and it installs a dashboard already wired to `system.cpu.utilization`, `system.memory.*`, `system.filesystem.*`, `system.disk.*` and `system.network.*`. Custom widgets cover anything the template misses. Agent repo: https://github.com/tracewayapp/traceway-otel-agent## Step 9: Verifydiff --git a/skills/traceway-setup/data-model.md b/skills/traceway-setup/data-model.mdindex 54127739..e01cc792 100644--- a/skills/traceway-setup/data-model.md+++ b/skills/traceway-setup/data-model.md@@ -193,7 +193,7 @@ Quirks:- **Histograms lose their buckets.** Only the average and count survive. You cannot compute true percentiles from an OTLP histogram in Traceway. An idle export interval (count 0) writes only the `.count` series, so `<name>.avg` has gaps rather than zeros.- **No percentile aggregations on metrics at all.** Metric queries support `avg`, `sum`, `count`, `min`, `max` and `last` only; anything else silently falls back to `avg`. `last` is special: it always reads the raw table, so it only works inside the 7-day raw retention window. Latency percentiles (P50/P95/P99) exist for Endpoints and Tasks because those are computed from raw span durations. If you need percentiles on a measurement, model it as a span, not a metric.-- **Tags come from data-point attributes plus a small resource allowlist.** Resource attributes are not copied onto metric points, with these exceptions. `service.name` becomes the `server_name` tag (and overwrites a data-point attribute of that name). And this fixed allowlist is lifted so per-process, per-container and per-pod series stay distinguishable when the receiver puts identity on the Resource: `process.pid`, `process.executable.name`, `process.command_line`, `process.owner`, `container.name`, `container.image.name`, `k8s.pod.name`, `k8s.namespace.name`, `k8s.node.name`, `k8s.deployment.name`, `k8s.container.name`, `postgresql.database.name`. Every other resource attribute (`host.name`, `deployment.environment`, and so on) is dropped. A data-point attribute wins over the resource value when both use the same key. Any other per-series dimension must be a data-point attribute, and keep its cardinality low.+- **Tags come from data-point attributes plus a small resource allowlist.** Resource attributes are not copied onto metric points, with these exceptions. `service.name` becomes the `server_name` tag (and overwrites a data-point attribute of that name). The fixed allowlist retains host/platform metadata (`host.name`, `host.id`, `host.arch`, `os.type`, `os.description`, cloud provider/region/availability zone) and grouping identity for processes, containers, Kubernetes (`k8s.cluster.name`, pod, namespace, node, deployment, container), and PostgreSQL databases. Every other resource attribute (`deployment.environment`, for example) is dropped. A data-point attribute wins over the resource value when both use the same key. Any other per-series dimension must be a data-point attribute, and keep its cardinality low.- **Raw metric points expire after 7 days** (ClickHouse TTL). Queries over wider ranges read pre-aggregated rollups instead (1-minute rollups are kept 30 days, 1-hour rollups 1 year, 1-day rollups indefinitely), so older metrics lose granularity rather than disappearing.### Built-in metric names