Skip to content

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

feat: organization level improvements (#357)

narrow-adventuref6b3bf1dc78f
diff --git a/CLAUDE.md b/CLAUDE.md
index 48bb9258..500ff152 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -670,7 +670,7 @@ backend/
| GET | `/api/metrics/application` | App | Application metrics |
| GET | `/api/metrics/stats` | App | Stats metrics |
| GET | `/api/metrics/server` | App | Server metrics |
-| POST | `/api/metrics/query` | App | Custom metric queries. Bounded in `metric_query.controller.go`: 256KB body, max 50 queries and 20 tag filters each, range at most 731 days and `to >= from` (422), buckets widened so no series exceeds 2000 points (the effective `intervalMinutes` is returned at the top level of the response), at most 200 groups per query (the repositories return one extra so the result carries `truncatedGroups: true`), and a 30s deadline for the whole request that answers 504. The discovery endpoints validate their `from`/`to` the same way |
+| POST | `/api/metrics/query` | App | Custom metric queries. Aggregations avg/min/max/sum/count/last plus `rate`, which differences every series (full tag set = identity) against its previous sample, drops resets, and sums the deltas per bucket as a per-second rate; the reported unit gains `/s` (`By/s`), a counter of seconds becomes the ratio `1`, and on ClickHouse `rate` follows `selectTable` like every other aggregation: past 6h it reads the rollups through `maxMerge(max_val)` (a counter only grows, so a rollup bucket's max is its last sample), never `metric_points_1d`, with the chart bucket clamped to the rollup step and the lookback widened by it (`rateSource`). The `traceway-otel-agent` template relies on it (plus `state` filters, `groupBy: server_name`, and the per-source `complement` flag that the widget renderer applies as 1 − value); `backfill.RunOtelAgentDashboardSources` upgrades installed copies whose widgets still carry the original plain-average source. Bounded in `metric_query.controller.go`: 256KB body, max 50 queries and 20 tag filters each, range at most 731 days and `to >= from` (422), buckets widened so no series exceeds 2000 points (the effective `intervalMinutes` is returned at the top level of the response), at most 200 groups per query (the repositories return one extra so the result carries `truncatedGroups: true`), and a 30s deadline for the whole request that answers 504. The discovery endpoints validate their `from`/`to` the same way |
| GET | `/api/metrics/discover` | App | Discover available metrics |
| GET | `/api/metrics/discover/tags` | App | Discover metric tags |
| GET | `/api/metrics/discover/instances` | App | Distinct `server_name` values in a range (dashboard instance filter) |
@@ -766,15 +766,17 @@ Frontend routes: `/ai-traces` (tabs: Traces, Conversations, Users), `/ai-traces/
| GET | `/api/organizations/:orgId/members/:userId/project-roles` | Admin | List member's per-project role overrides |
| PUT | `/api/organizations/:orgId/members/:userId/project-roles/:projectId` | Admin | Set/clear a per-project role override |
-**Organization Overview** (`/organization` frontend route, tabs Overview | Issues | Monitors | Projects)
+**Organization Overview** (frontend routes `/organization` = Servers, `/organization/issues`, `/organization/monitors`, `/organization/on-call`, `/organization/projects`)
-Org-wide read views that fan out over every project of the org, in `organization_overview.controller.go`. `RequireOrganizationAccess` (any org role) gates them; the servers/issues/monitors handlers deliberately skip `Transactional` because they run per-project telemetry queries and must not hold the single-connection SQLite main DB across them (they open their own short `db.ExecuteTransaction` for the project list first). The pure main-DB pages endpoint keeps `Transactional`. The frontend renders `/organization` without the project sidebar and auto-lands there after login when the first org has more than one project (`frontend/src/lib/utils/landing.ts`). A single-project organization never shows the view: `/organization` redirects into that project and the switcher renders the org as a plain label, since the project's own pages already cover everything it would aggregate. When none of the org's projects is a backend project (`isBackendFramework` in `projects.svelte.ts`, i.e. every project is a browser or mobile framework), the Monitors tab and the Instances section are hidden and the pulse header only counts issues and open pages.
+Org-wide read views that fan out over every project of the org, in `organization_overview.controller.go`. `RequireOrganizationAccess` (any org role) gates them; the servers/issues/monitors handlers deliberately skip `Transactional` because they run per-project telemetry queries and must not hold the single-connection SQLite main DB across them (they open their own short `db.ExecuteTransaction` for the project list first). The pure main-DB pages endpoint keeps `Transactional`. The frontend renders the organization routes in the same sidebar shell as project pages, with the sidebar switched to organization items (Servers, Issues, Monitors, On-Call, Projects under an "Organization" label; badges come from `/overview/counts`). The selected organization is the shared `organizationContext` in `frontend/src/lib/state/organization-context.svelte.ts` (the `organizationId` query param, else the first membership), and `src/routes/organization/+layout.svelte` owns the redirects: a single-project org into that project, legacy `?tab=` links to the new paths, and frontend-only orgs from Servers/Monitors to Issues. Login auto-lands on `/organization` when the first org has more than one project (`frontend/src/lib/utils/landing.ts`). A single-project organization never shows the view: `/organization` redirects into that project and the switcher renders the org as a plain label, since the project's own pages already cover everything it would aggregate. When none of the org's projects is a backend project (`isBackendFramework` in `projects.svelte.ts`, i.e. every project is a browser or mobile framework), the Servers and Monitors sidebar items are hidden and `/organization` redirects to `/organization/issues`.
| Method | Endpoint | Auth | Purpose |
|--------|----------|------|---------|
| GET | `/api/organizations/:organizationId/overview/servers` | Member | One row per `server_name` per project over the last 30 min: CPU/memory/disk/network + a CPU sparkline, plus host/os/cloud/k8s metadata lifted from metric tags. Reads OTel hostmetrics (`system.cpu.utilization` state=idle inverted, `system.memory.utilization` state=used, `system.filesystem.utilization` state=used, `system.network.io` by direction) and falls back to the legacy SDK names (`cpu.used_pcnt`, `mem.used`/`mem.total`). A project that fails to read sets `partial: true` instead of failing the request |
-| GET | `/api/organizations/:organizationId/overview/issues` | Member | Recently active issues across all projects, last 24h, max 50, plus the true `totalGroups`; a project that fails to read sets `partial: true` like the servers endpoint |
-| GET | `/api/organizations/:organizationId/overview/pages` | Member | Active on-call pages across all projects + open-page and down-monitor counts |
+| POST | `/api/organizations/:organizationId/overview/issues` | Member | Paginated issues across all projects. Body mirrors `/api/exception-stack-traces` (`fromDate`, `toDate`, `orderBy`, `search`, `searchType`, `pagination`); every project contributes its top `page*pageSize` groups in the requested order and the page is a slice of their merged order, so it equals what one combined project would return. That per-project fetch is capped at 1000 rows (`orgOverviewMaxIssueFetch`): a deeper page answers 422 and `totalPages` is clamped so the footer never offers one; `FindGrouped` orders ties by `exception_hash` on every backend so the merge is stable across pages. Returns `{data, pagination, partial}` with 24h hourly trends attached; a project that fails to read sets `partial: true` like the servers endpoint |
+| POST | `/api/organizations/:organizationId/overview/pages` | Member | Paginated on-call pages across all projects: body `{status, search, fromDate, toDate, pagination}` (status active/open/acknowledged/resolved, search over subject + rule name, range on `created_at`); returns `{data, pagination, openPagesCount}` |
+| GET | `/api/organizations/:organizationId/overview/counts` | Member | `openPagesCount` + `downMonitorsCount` for the organization sidebar badges |
+| POST | `/api/organizations/:organizationId/overview/incidents` | Member | Paginated incidents across monitors and status pages: body `{search, fromDate, toDate, pagination}`; an incident matches when it overlaps the range (`started_at <= to` and unresolved or `resolved_at >= from`), search covers title, monitor, status page, and error message |
| GET | `/api/organizations/:organizationId/overview/monitors` | Member | Every synthetic check in the org with 30-day aggregates; a project whose results fail to read sets `partial: true` like the servers endpoint |
Instance identity is the `server_name` tag, which comes from the OTLP `service.name` resource attribute; grouping by Kubernetes cluster keys off the `k8s.cluster.name` tag and the group selector only offers it when at least one instance carries one. Clicking a row opens `/dashboards?projectId=&server=&preset=30m` (plus `dashboard=` when the project has the `traceway-otel-agent` template applied); `server` scopes every widget query via `scopeTagFilters` in `widget-grid`/`widget-renderer`. Cluster-wide instrumentation manifests live in `examples/kubernetes/`, documented at `docs/pages/learn/kubernetes.mdx`.
diff --git a/README.md b/README.md
index 47e98da1..6cd891d4 100644
--- a/README.md
+++ b/README.md
@@ -293,7 +293,7 @@ Full documentation at **[docs.tracewayapp.com](https://docs.tracewayapp.com)**:
- [**Concepts**](https://docs.tracewayapp.com/learn): How tracing, exception fingerprinting, metrics, and alerts work
- [**Embedded Mode**](https://docs.tracewayapp.com/learn/embedded-mode): Run Traceway inside your Go app
- [**Kubernetes**](https://docs.tracewayapp.com/learn/kubernetes): Instrument a whole cluster with the manifests in [`examples/kubernetes`](./examples/kubernetes)
-- [**Organization Overview**](https://docs.tracewayapp.com/learn/organization-overview): Fleet health and cross-project triage on one page
+- [**Organization Overview**](https://docs.tracewayapp.com/learn/organization-overview): Servers, issues, monitors, and on-call pages across every project, one sidebar click apart
## Community
diff --git a/backend/app/backfill/otel_agent_sources.go b/backend/app/backfill/otel_agent_sources.go
new file mode 100644
index 00000000..8850b2fd
--- /dev/null
+++ b/backend/app/backfill/otel_agent_sources.go
@@ -0,0 +1,190 @@
+package backfill
+
+import (
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"
+ dashboardsvc "github.com/tracewayapp/traceway/backend/app/services/dashboards"
+)
+
+const otelAgentSourcesBackfillName = "otel-agent-dashboard-sources-v2"
+
+const otelAgentTemplateKey = "traceway-otel-agent"
+
+func RunOtelAgentDashboardSources() error {
+ updated, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {
+ if !db.IsSQLite() {
+ if _, err := tx.Exec("SELECT pg_advisory_xact_lock(824737006)"); err != nil {
+ return 0, fmt.Errorf("failed to take backfill lock: %w", err)
+ }
+ }
+
+ marker, err := lit.SelectSingleNamed[models.CountResult](
+ tx,
+ "SELECT COUNT(*) as count FROM backfill_runs WHERE name = :name",
+ lit.P{"name": otelAgentSourcesBackfillName},
+ )
+ if err != nil {
+ return 0, fmt.Errorf("failed to check backfill marker: %w", err)
+ }
+ if marker != nil && marker.Count > 0 {
+ return 0, nil
+ }
+
+ updated := 0
+ template, err := transactional.DashboardTemplateRepository.FindByKey(tx, otelAgentTemplateKey)
+ if err != nil {
+ return 0, fmt.Errorf("failed to load the OTel agent template: %w", err)
+ }
+ if template != nil {
+ templateSources, err := templateSourcesByMetric(template.Definition)
+ if err != nil {
+ return 0, fmt.Errorf("failed to read the OTel agent template: %w", err)
+ }
+ dashboards, err := lit.SelectNamed[models.Dashboard](
+ tx,
+ "SELECT id, organization_id, name, description, definition, template_key, created_by, created_at, updated_at FROM dashboards WHERE template_key = :key",
+ lit.P{"key": otelAgentTemplateKey},
+ )
+ if err != nil {
+ return 0, fmt.Errorf("failed to list OTel agent dashboards: %w", err)
+ }
+ for _, dashboard := range dashboards {
+ changed, err := upgradeOtelAgentDashboard(dashboard, templateSources)
+ if err != nil {
+ return 0, fmt.Errorf("dashboard %d: %w", dashboard.Id, err)
+ }
+ if !changed {
+ continue
+ }
+ dashboard.UpdatedAt = time.Now().UTC()
+ if err := transactional.DashboardRepository.Update(tx, dashboard); err != nil {
+ return 0, fmt.Errorf("failed to update dashboard %d: %w", dashboard.Id, err)
+ }
+ updated++
+ }
+ }
+
+ if err := lit.DeleteNamed(
+ db.Driver,
+ tx,
+ "INSERT INTO backfill_runs (name, ran_at) VALUES (:name, :ran_at)",
+ lit.P{"name": otelAgentSourcesBackfillName, "ran_at": time.Now().UTC()},
+ ); err != nil {
+ return 0, fmt.Errorf("failed to record backfill marker: %w", err)
+ }
+ return updated, nil
+ })
+ if err != nil {
+ return err
+ }
+ if updated > 0 {
+ config.Logf("Backfill: updated the widget sources of %d OTel agent dashboard(s)", updated)
+ }
+ return nil
+}
+
+type widgetConfig map[string]json.RawMessage
+
+func templateSourcesByMetric(definition models.JSONText) (map[string]json.RawMessage, error) {
+ def, err := dashboardsvc.ParseDefinition([]byte(definition))
+ if err != nil {
+ return nil, err
+ }
+ byMetric := make(map[string]json.RawMessage)
+ for _, widget := range def.Widgets {
+ var cfg widgetConfig
+ if err := json.Unmarshal(widget.Config, &cfg); err != nil {
+ return nil, err
+ }
+ sources, ok := cfg["sources"]
+ if !ok {
+ continue
+ }
+ var probe []struct {
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(sources, &probe); err != nil || len(probe) == 0 || probe[0].Name == "" {
+ continue
+ }
+ byMetric[probe[0].Name] = sources
+ }
+ return byMetric, nil
+}
+
+func originalSource(sources json.RawMessage) (string, bool) {
+ var probe []map[string]json.RawMessage
+ if err := json.Unmarshal(sources, &probe); err != nil || len(probe) != 1 {
+ return "", false
+ }
+ source := probe[0]
+ for key := range source {
+ switch key {
+ case "type", "name", "aggregation":
+ default:
+ return "", false
+ }
+ }
+ var name, aggregation string
+ if err := json.Unmarshal(source["name"], &name); err != nil || name == "" {
+ return "", false
+ }
+ if raw, ok := source["aggregation"]; ok {
+ if err := json.Unmarshal(raw, &aggregation); err != nil {
+ return "", false
+ }
+ }
+ if aggregation != "" && aggregation != "avg" {
+ return "", false
+ }
+ return name, true
+}
+
+func upgradeOtelAgentDashboard(dashboard *models.Dashboard, templateSources map[string]json.RawMessage) (bool, error) {
+ def, err := dashboardsvc.ParseDefinition([]byte(dashboard.Definition))
+ if err != nil {
+ return false, err
+ }
+ changed := false
+ for i := range def.Widgets {
+ var cfg widgetConfig
+ if err := json.Unmarshal(def.Widgets[i].Config, &cfg); err != nil {
+ return false, err
+ }
+ sources, ok := cfg["sources"]
+ if !ok {
+ continue
+ }
+ name, ok := originalSource(sources)
+ if !ok {
+ continue
+ }
+ replacement, ok := templateSources[name]
+ if !ok || string(replacement) == string(sources) {
+ continue
+ }
+ cfg["sources"] = replacement
+ raw, err := json.Marshal(cfg)
+ if err != nil {
+ return false, err
+ }
+ def.Widgets[i].Config = raw
+ changed = true
+ }
+ if !changed {
+ return false, nil
+ }
+ raw, err := dashboardsvc.MarshalDefinition(def)
+ if err != nil {
+ return false, err
+ }
+ dashboard.Definition = models.JSONText(raw)
+ return true, nil
+}
diff --git a/backend/app/backfill/otel_agent_sources_test.go b/backend/app/backfill/otel_agent_sources_test.go
new file mode 100644
index 00000000..fe579c3d
--- /dev/null
+++ b/backend/app/backfill/otel_agent_sources_test.go
@@ -0,0 +1,99 @@
+package backfill
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/models"
+ dashboardsvc "github.com/tracewayapp/traceway/backend/app/services/dashboards"
+)
+
+const otelAgentTemplateFixture = `{"schemaVersion":1,"widgets":[
+ {"title":"CPU Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.utilization","aggregation":"avg","tagFilters":{"state":"idle"},"groupBy":"server_name","label":"CPU","complement":true}]}},
+ {"title":"Network I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}}
+]}`
+
+func TestUpgradeOtelAgentDashboard(t *testing.T) {
+ templateSources, err := templateSourcesByMetric(models.JSONText(otelAgentTemplateFixture))
+ if err != nil {
+ t.Fatalf("templateSourcesByMetric: %v", err)
+ }
+ if len(templateSources) != 2 {
+ t.Fatalf("expected 2 template metrics, got %d", len(templateSources))
+ }
+
+ installed := `{"schemaVersion":1,"widgets":[
+ {"id":"w_cpu","title":"CPU Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.utilization","aggregation":"avg"}],"showLegend":true}},
+ {"id":"w_net","title":"Network I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.io","aggregation":"avg","groupBy":"device"}]}},
+ {"id":"w_custom","title":"Requests","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"http.requests","aggregation":"sum"}]}},
+ {"id":"w_text","title":"Notes","widgetType":"text","config":{"text":"hello"}}
+ ]}`
+ dashboard := &models.Dashboard{Id: 1, Definition: models.JSONText(installed)}
+
+ changed, err := upgradeOtelAgentDashboard(dashboard, templateSources)
+ if err != nil {
+ t.Fatalf("upgradeOtelAgentDashboard: %v", err)
+ }
+ if !changed {
+ t.Fatal("expected the dashboard to change")
+ }
+
+ def, err := dashboardsvc.ParseDefinition([]byte(dashboard.Definition))
+ if err != nil {
+ t.Fatalf("ParseDefinition: %v", err)
+ }
+ configs := map[string]map[string]json.RawMessage{}
+ for _, widget := range def.Widgets {
+ var cfg map[string]json.RawMessage
+ if err := json.Unmarshal(widget.Config, &cfg); err != nil {
+ t.Fatalf("widget %s config: %v", widget.Id, err)
+ }
+ configs[widget.Id] = cfg
+ }
+
+ if !strings.Contains(string(configs["w_cpu"]["sources"]), `"complement":true`) {
+ t.Errorf("CPU widget should carry the template's inverted idle source, got %s", configs["w_cpu"]["sources"])
+ }
+ if string(configs["w_cpu"]["showLegend"]) != "true" {
+ t.Errorf("CPU widget lost its other config: %s", configs["w_cpu"]["showLegend"])
+ }
+ if !strings.Contains(string(configs["w_net"]["sources"]), `"groupBy":"device"`) {
+ t.Errorf("edited network widget should be untouched, got %s", configs["w_net"]["sources"])
+ }
+ if !strings.Contains(string(configs["w_custom"]["sources"]), `"aggregation":"sum"`) {
+ t.Errorf("custom widget should be untouched, got %s", configs["w_custom"]["sources"])
+ }
+ if string(configs["w_text"]["text"]) != `"hello"` {
+ t.Errorf("text widget should be untouched, got %s", configs["w_text"]["text"])
+ }
+
+ changedAgain, err := upgradeOtelAgentDashboard(dashboard, templateSources)
+ if err != nil {
+ t.Fatalf("second upgrade: %v", err)
+ }
+ if changedAgain {
+ t.Error("second upgrade should be a no-op")
+ }
+}
+
+func TestOriginalSource(t *testing.T) {
+ cases := []struct {
+ sources string
+ name string
+ ok bool
+ }{
+ {`[{"type":"metric","name":"system.memory.usage","aggregation":"avg"}]`, "system.memory.usage", true},
+ {`[{"type":"metric","name":"system.memory.usage"}]`, "system.memory.usage", true},
+ {`[{"type":"metric","name":"system.memory.usage","aggregation":"max"}]`, "", false},
+ {`[{"type":"metric","name":"system.memory.usage","aggregation":"avg","tagFilters":{"state":"used"}}]`, "", false},
+ {`[{"type":"metric","name":"a","aggregation":"avg"},{"type":"metric","name":"b","aggregation":"avg"}]`, "", false},
+ {`[]`, "", false},
+ }
+ for _, c := range cases {
+ name, ok := originalSource(json.RawMessage(c.sources))
+ if ok != c.ok || name != c.name {
+ t.Errorf("originalSource(%s) = (%q, %v), want (%q, %v)", c.sources, name, ok, c.name, c.ok)
+ }
+ }
+}
diff --git a/backend/app/controllers/metric_query.controller.go b/backend/app/controllers/metric_query.controller.go
index 484c72e5..787774fa 100644
--- a/backend/app/controllers/metric_query.controller.go
+++ b/backend/app/controllers/metric_query.controller.go
@@ -182,7 +182,7 @@ func (c *metricQueryController) Query(ctx *gin.Context) {
}
truncated := trimGroupSeries(series)
- resultUnit := unitMap[q.Name]
+ resultUnit := rateUnit(agg, unitMap[q.Name])
if agg == "count" {
resultUnit = "count"
}
@@ -459,3 +459,16 @@ func (c *metricQueryController) UpdateRegistry(ctx *gin.Context) {
}
var MetricQueryController = metricQueryController{}
+
+func rateUnit(aggregation string, unit string) string {
+ if aggregation != "rate" {
+ return unit
+ }
+ switch unit {
+ case "s":
+ return "1"
+ case "":
+ return "count/s"
+ }
+ return unit + "/s"
+}
diff --git a/backend/app/controllers/organization_overview.controller.go b/backend/app/controllers/organization_overview.controller.go
index 36d5a5f5..d448a9c6 100644
--- a/backend/app/controllers/organization_overview.controller.go
+++ b/backend/app/controllers/organization_overview.controller.go
@@ -7,6 +7,7 @@ import (
"math"
"net/http"
"sort"
+ "strings"
"time"
"github.com/tracewayapp/traceway/backend/app/db"
@@ -25,8 +26,7 @@ type organizationOverviewController struct{}
var OrganizationOverviewController = organizationOverviewController{}
-const orgOverviewMaxIssues = 50
-const orgOverviewMaxPages = 50
+const orgOverviewMaxIssueFetch = 1000
// orgOverviewProjects loads the organization's projects in one short
// transaction: the fan-out handlers run their telemetry queries outside any
@@ -380,43 +380,142 @@ type orgIssueRow struct {
ProjectName string `json:"projectName"`
}
+type orgIssuesRequest struct {
+ FromDate time.Time `json:"fromDate"`
+ ToDate time.Time `json:"toDate"`
+ OrderBy string `json:"orderBy"`
+ Pagination PaginationParams `json:"pagination" binding:"required"`
+ Search string `json:"search"`
+ SearchType string `json:"searchType"`
+}
+
+func normalizeIssueOrderBy(orderBy string) string {
+ switch strings.TrimSuffix(orderBy, "_asc") {
+ case "last_seen", "first_seen", "count":
+ return orderBy
+ }
+ return "last_seen"
+}
+
+func orgIssueLess(orderBy string) func(a, b orgIssueRow) bool {
+ ascending := strings.HasSuffix(orderBy, "_asc")
+ field := strings.TrimSuffix(orderBy, "_asc")
+ return func(a, b orgIssueRow) bool {
+ var less, equal bool
+ switch field {
+ case "count":
+ less, equal = a.Count < b.Count, a.Count == b.Count
+ case "first_seen":
+ less, equal = a.FirstSeen.Before(b.FirstSeen), a.FirstSeen.Equal(b.FirstSeen)
+ default:
+ less, equal = a.LastSeen.Before(b.LastSeen), a.LastSeen.Equal(b.LastSeen)
+ }
+ if equal {
+ if a.ExceptionHash != b.ExceptionHash {
+ return a.ExceptionHash < b.ExceptionHash
+ }
+ return a.ProjectId.String() < b.ProjectId.String()
+ }
+ if ascending {
+ return less
+ }
+ return !less
+ }
+}
+
+func attachOrgIssueTrends(ctx *gin.Context, rows []orgIssueRow) (partial bool) {
+ hashesByProject := map[uuid.UUID][]string{}
+ for _, row := range rows {
+ hashesByProject[row.ProjectId] = append(hashesByProject[row.ProjectId], row.ExceptionHash)
+ }
+ now := time.Now()
+ start24h := now.Add(-24 * time.Hour)
+ trends := map[uuid.UUID]map[string][]models.ExceptionTrendPoint{}
+ for projectId, hashes := range hashesByProject {
+ span := traceway.StartSpan(ctx, fmt.Sprintf("org overview issue trends: project %s", projectId))
+ projectTrends, err := telemetry.ExceptionStackTraceRepository.GetHourlyTrendForHashes(ctx, projectId, hashes, start24h, now)
+ span.End()
+ if err != nil {
+ partial = true
+ traceway.CaptureException(traceway.NewStackTraceErrorf("failed to load issue trends for project %s: %w", projectId, err))
+ continue
+ }
+ trends[projectId] = projectTrends
+ }
+ for i := range rows {
+ if trend, ok := trends[rows[i].ProjectId][rows[i].ExceptionHash]; ok {
+ rows[i].HourlyTrend = trend
+ } else {
+ rows[i].HourlyTrend = []models.ExceptionTrendPoint{}
+ }
+ }
+ return partial
+}
+
func (c *organizationOverviewController) Issues(ctx *gin.Context) {
organizationId := middleware.GetOrganizationId(ctx)
+ var request orgIssuesRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ middleware.RejectBindError(ctx, err, "Invalid request body")
+ return
+ }
+ if request.ToDate.Before(request.FromDate) {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The end of the range must not be before its start"})
+ return
+ }
+ orderBy := normalizeIssueOrderBy(request.OrderBy)
+ page, pageSize := request.Pagination.Page, request.Pagination.PageSize
+ maxPages := orgOverviewMaxIssueFetch / pageSize
+ if page > maxPages {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("Only the first %d issues can be paged; narrow the time range or search", orgOverviewMaxIssueFetch)})
+ return
+ }
+
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
+ fetch := page * pageSize
+ candidates := make([]orgIssueRow, 0)
+ var total int64
partial := false
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)
+ groups, projectTotal, err := telemetry.ExceptionStackTraceRepository.FindGrouped(ctx, project.Id, request.FromDate, request.ToDate, 1, fetch, orderBy, request.Search, request.SearchType, false)
span.End()
if err != nil {
partial = true
traceway.CaptureException(traceway.NewStackTraceErrorf("failed to load issues for project %s: %w", project.Id, err))
continue
}
- totalGroups += total
+ total += projectTotal
for _, group := range groups {
- issues = append(issues, orgIssueRow{ExceptionGroup: group, ProjectId: project.Id, ProjectName: project.Name})
+ candidates = append(candidates, 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]
+ less := orgIssueLess(orderBy)
+ sort.Slice(candidates, func(i, j int) bool { return less(candidates[i], candidates[j]) })
+ offset := (page - 1) * pageSize
+ rows := []orgIssueRow{}
+ if offset < len(candidates) {
+ rows = candidates[offset:min(offset+pageSize, len(candidates))]
+ }
+ if attachOrgIssueTrends(ctx, rows) {
+ partial = true
+ }
+ pagination := buildPagination(page, pageSize, int(total))
+ if pagination.TotalPages > int64(maxPages) {
+ pagination.TotalPages = int64(maxPages)
}
- ctx.JSON(http.StatusOK, gin.H{"issues": issues, "totalGroups": totalGroups, "partial": partial})
+ ctx.JSON(http.StatusOK, gin.H{
+ "data": rows,
+ "pagination": pagination,
+ "partial": partial,
+ })
}
type orgPageRow struct {
@@ -424,23 +523,48 @@ type orgPageRow struct {
ProjectName string `json:"projectName"`
}
+type orgPagesRequest struct {
+ Status string `json:"status"`
+ Search string `json:"search"`
+ FromDate *time.Time `json:"fromDate"`
+ ToDate *time.Time `json:"toDate"`
+ Pagination PaginationParams `json:"pagination" binding:"required"`
+}
+
func (c *organizationOverviewController) Pages(ctx *gin.Context) {
tx := db.GetTx(ctx)
organizationId := middleware.GetOrganizationId(ctx)
+ var request orgPagesRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ middleware.RejectBindError(ctx, err, "Invalid request body")
+ return
+ }
+ if request.Status == "" {
+ request.Status = "active"
+ }
+ if !validPageStatusFilters[request.Status] {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status filter"})
+ return
+ }
+ if request.FromDate != nil && request.ToDate != nil && request.ToDate.Before(*request.FromDate) {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The end of the range must not be before its start"})
+ return
+ }
+ page, pageSize := request.Pagination.Page, request.Pagination.PageSize
- pages, err := transactional.PageRepository.FindByOrganization(tx, organizationId, "active", orgOverviewMaxPages, 0)
+ total, err := transactional.PageRepository.CountByOrganizationFiltered(tx, organizationId, request.Status, request.Search, request.FromDate, request.ToDate)
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization pages: %w", err))
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count organization pages: %w", err))
return
}
- openCount, err := transactional.PageRepository.CountByOrganization(tx, organizationId, models.PageStatusOpen)
+ pages, err := transactional.PageRepository.FindByOrganizationFiltered(tx, organizationId, request.Status, request.Search, request.FromDate, request.ToDate, pageSize, (page-1)*pageSize)
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count open pages: %w", err))
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization pages: %w", err))
return
}
- downCount, err := transactional.SyntheticCheckRepository.CountDownByOrganization(tx, organizationId)
+ openCount, err := transactional.PageRepository.CountByOrganization(tx, organizationId, models.PageStatusOpen)
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count down monitors: %w", err))
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count open pages: %w", err))
return
}
projects, err := transactional.ProjectRepository.FindByOrganizationId(tx, organizationId)
@@ -454,8 +578,8 @@ func (c *organizationOverviewController) Pages(ctx *gin.Context) {
}
names := map[int]string{}
- for _, page := range pages {
- if page.AcknowledgedBy != nil || page.ResolvedBy != nil {
+ for _, p := range pages {
+ if p.AcknowledgedBy != nil || p.ResolvedBy != nil {
names, err = memberNames(tx, organizationId)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load members: %w", err))
@@ -466,11 +590,72 @@ func (c *organizationOverviewController) Pages(ctx *gin.Context) {
}
items := make([]orgPageRow, 0, len(pages))
- for _, page := range pages {
- items = append(items, orgPageRow{pageResponse: toPageResponse(page, names), ProjectName: projectNames[page.ProjectId]})
+ for _, p := range pages {
+ items = append(items, orgPageRow{pageResponse: toPageResponse(p, names), ProjectName: projectNames[p.ProjectId]})
}
- ctx.JSON(http.StatusOK, gin.H{"pages": items, "openPagesCount": openCount, "downMonitorsCount": downCount})
+ ctx.JSON(http.StatusOK, gin.H{
+ "data": items,
+ "pagination": buildPagination(page, pageSize, total),
+ "openPagesCount": openCount,
+ })
+}
+
+func (c *organizationOverviewController) Counts(ctx *gin.Context) {
+ tx := db.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+ 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
+ }
+ ctx.JSON(http.StatusOK, gin.H{"openPagesCount": openCount, "downMonitorsCount": downCount})
+}
+
+type orgIncidentsRequest struct {
+ Search string `json:"search"`
+ FromDate *time.Time `json:"fromDate"`
+ ToDate *time.Time `json:"toDate"`
+ Pagination PaginationParams `json:"pagination" binding:"required"`
+}
+
+func (c *organizationOverviewController) Incidents(ctx *gin.Context) {
+ tx := db.GetTx(ctx)
+ organizationId := middleware.GetOrganizationId(ctx)
+ var request orgIncidentsRequest
+ if err := ctx.ShouldBindJSON(&request); err != nil {
+ middleware.RejectBindError(ctx, err, "Invalid request body")
+ return
+ }
+ if request.FromDate != nil && request.ToDate != nil && request.ToDate.Before(*request.FromDate) {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The end of the range must not be before its start"})
+ return
+ }
+ page, pageSize := request.Pagination.Page, request.Pagination.PageSize
+
+ total, err := transactional.CheckIncidentRepository.CountByOrganizationFiltered(tx, organizationId, request.Search, request.FromDate, request.ToDate)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to count organization incidents: %w", err))
+ return
+ }
+ incidents, err := transactional.CheckIncidentRepository.FindByOrganizationPaged(tx, organizationId, request.Search, request.FromDate, request.ToDate, pageSize, (page-1)*pageSize)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list organization incidents: %w", err))
+ return
+ }
+ if incidents == nil {
+ incidents = []*models.OrgIncident{}
+ }
+ views, ok := buildIncidentViews(ctx, tx, incidents)
+ if !ok {
+ return
+ }
+ ctx.JSON(http.StatusOK, gin.H{"data": views, "pagination": buildPagination(page, pageSize, total)})
}
type orgMonitorRow struct {
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 00530230..ef6d6b91 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -295,8 +295,10 @@ func RegisterControllers(router *gin.RouterGroup) {
// 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.POST("/organizations/:organizationId/overview/issues", middleware.UseAppAuth, middleware.RequireOrganizationAccess, OrganizationOverviewController.Issues)
+ router.POST("/organizations/:organizationId/overview/pages", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, OrganizationOverviewController.Pages)
+ router.GET("/organizations/:organizationId/overview/counts", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, OrganizationOverviewController.Counts)
+ router.POST("/organizations/:organizationId/overview/incidents", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, OrganizationOverviewController.Incidents)
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)
diff --git a/backend/app/migrations/pg/0142_update_template_traceway_otel_agent_sources.up.sql b/backend/app/migrations/pg/0142_update_template_traceway_otel_agent_sources.up.sql
new file mode 100644
index 00000000..f4d0d7e0
--- /dev/null
+++ b/backend/app/migrations/pg/0142_update_template_traceway_otel_agent_sources.up.sql
@@ -0,0 +1 @@
+UPDATE dashboard_templates SET definition = '{"schemaVersion":1,"widgets":[{"title":"CPU Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.utilization","aggregation":"avg","tagFilters":{"state":"idle"},"groupBy":"server_name","label":"CPU","complement":true}]}},{"title":"Memory Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.memory.utilization","aggregation":"avg","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Memory"}]}},{"title":"Memory Usage","widgetType":"area_chart","config":{"sources":[{"type":"metric","name":"system.memory.usage","aggregation":"avg","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Load Avg (1m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.1m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Load Avg (5m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.5m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Load Avg (15m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.15m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Filesystem Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.filesystem.utilization","aggregation":"max","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Filesystem Usage","widgetType":"area_chart","config":{"sources":[{"type":"metric","name":"system.filesystem.usage","aggregation":"max","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Disk I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.io","aggregation":"rate","tagFilters":{"direction":"read"},"groupBy":"server_name","label":"Read"},{"type":"metric","name":"system.disk.io","aggregation":"rate","tagFilters":{"direction":"write"},"groupBy":"server_name","label":"Write"}]}},{"title":"Disk IOPS","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.operations","aggregation":"rate","tagFilters":{"direction":"read"},"groupBy":"server_name","label":"Read"},{"type":"metric","name":"system.disk.operations","aggregation":"rate","tagFilters":{"direction":"write"},"groupBy":"server_name","label":"Write"}]}},{"title":"Disk I/O Time","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.io_time","aggregation":"rate","groupBy":"server_name","label":"Busy"}]}},{"title":"Network I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Network Packets","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.packets","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.packets","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Network Errors","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.errors","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.errors","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Open Connections","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.connections","aggregation":"last","tagFilters":{"protocol":"tcp","state":"ESTABLISHED"},"groupBy":"server_name","label":"Established"}]}}]}', updated_at = now() WHERE key = 'traceway-otel-agent'
diff --git a/backend/app/migrations/sqlite/0076_update_template_traceway_otel_agent_sources.up.sql b/backend/app/migrations/sqlite/0076_update_template_traceway_otel_agent_sources.up.sql
new file mode 100644
index 00000000..44890409
--- /dev/null
+++ b/backend/app/migrations/sqlite/0076_update_template_traceway_otel_agent_sources.up.sql
@@ -0,0 +1 @@
+UPDATE dashboard_templates SET definition = '{"schemaVersion":1,"widgets":[{"title":"CPU Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.utilization","aggregation":"avg","tagFilters":{"state":"idle"},"groupBy":"server_name","label":"CPU","complement":true}]}},{"title":"Memory Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.memory.utilization","aggregation":"avg","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Memory"}]}},{"title":"Memory Usage","widgetType":"area_chart","config":{"sources":[{"type":"metric","name":"system.memory.usage","aggregation":"avg","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Load Avg (1m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.1m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Load Avg (5m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.5m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Load Avg (15m)","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.cpu.load_average.15m","aggregation":"avg","groupBy":"server_name","label":"Load"}]}},{"title":"Filesystem Utilization","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.filesystem.utilization","aggregation":"max","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Filesystem Usage","widgetType":"area_chart","config":{"sources":[{"type":"metric","name":"system.filesystem.usage","aggregation":"max","tagFilters":{"state":"used"},"groupBy":"server_name","label":"Used"}]}},{"title":"Disk I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.io","aggregation":"rate","tagFilters":{"direction":"read"},"groupBy":"server_name","label":"Read"},{"type":"metric","name":"system.disk.io","aggregation":"rate","tagFilters":{"direction":"write"},"groupBy":"server_name","label":"Write"}]}},{"title":"Disk IOPS","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.operations","aggregation":"rate","tagFilters":{"direction":"read"},"groupBy":"server_name","label":"Read"},{"type":"metric","name":"system.disk.operations","aggregation":"rate","tagFilters":{"direction":"write"},"groupBy":"server_name","label":"Write"}]}},{"title":"Disk I/O Time","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.disk.io_time","aggregation":"rate","groupBy":"server_name","label":"Busy"}]}},{"title":"Network I/O","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.io","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Network Packets","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.packets","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.packets","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Network Errors","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.errors","aggregation":"rate","tagFilters":{"direction":"receive"},"groupBy":"server_name","label":"Receive"},{"type":"metric","name":"system.network.errors","aggregation":"rate","tagFilters":{"direction":"transmit"},"groupBy":"server_name","label":"Transmit"}]}},{"title":"Open Connections","widgetType":"line_chart","config":{"sources":[{"type":"metric","name":"system.network.connections","aggregation":"last","tagFilters":{"protocol":"tcp","state":"ESTABLISHED"},"groupBy":"server_name","label":"Established"}]}}]}', updated_at = datetime('now') WHERE key = 'traceway-otel-agent'
diff --git a/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.go b/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.go
index b2646b03..1bb46cf1 100644
--- a/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.go
+++ b/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.go
@@ -174,7 +174,7 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, project
` + archiveSubquery + `
WHERE ` + whereClause + `
GROUP BY e.exception_hash` + havingClause + `
- ORDER BY ` + orderBy + ` ` + sortDirection + ` LIMIT ? OFFSET ?`
+ ORDER BY ` + orderBy + ` ` + sortDirection + `, e.exception_hash LIMIT ? OFFSET ?`
queryArgs := append([]interface{}{projectId}, args...)
queryArgs = append(queryArgs, pageSize, offset)
diff --git a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
index 709f2773..222b985e 100644
--- a/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go
@@ -48,8 +48,11 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
if aggregation == "last" {
table = "metric_points"
}
-
- aggFunc := aggregationFunc(aggregation, table)
+ isRate := aggregation == "rate"
+ var lookback time.Duration
+ if isRate {
+ table, intervalMinutes, lookback = rateSource(table, intervalMinutes)
+ }
query := "SELECT toStartOfInterval(recorded_at, INTERVAL ? MINUTE) AS bucket"
@@ -70,12 +73,21 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
query += " AS group_key"
}
- query += ", " + aggFunc + " AS agg_value FROM " + table + " WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?"
- args = append(args, projectId, name, from, to)
-
+ where := " WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?"
+ whereArgs := []interface{}{projectId, name, from.Add(-lookback), to}
for k, v := range tagFilters {
- query += " AND tags[?] = ?"
- args = append(args, k, v)
+ where += " AND tags[?] = ?"
+ whereArgs = append(whereArgs, k, v)
+ }
+
+ if isRate {
+ query += ", sum(greatest(delta, 0)) / ? AS agg_value FROM (" + rateDeltasSelect(table, where) + ") WHERE rn > 1 AND recorded_at >= ?"
+ args = append(args, float64(intervalMinutes*60))
+ args = append(args, whereArgs...)
+ args = append(args, from)
+ } else {
+ query += ", " + aggregationFunc(aggregation, table) + " AS agg_value FROM " + table + where
+ args = append(args, whereArgs...)
}
query += " GROUP BY bucket"
@@ -189,6 +201,28 @@ func selectTable(duration time.Duration) string {
}
}
+var rollupStepMinutes = map[string]int{"metric_points_1m": 1, "metric_points_1h": 60}
+
+func rateSource(table string, intervalMinutes int) (string, int, time.Duration) {
+ if table == "metric_points_1d" {
+ table = "metric_points_1h"
+ }
+ step := rollupStepMinutes[table]
+ if intervalMinutes < step {
+ intervalMinutes = step
+ }
+ return table, intervalMinutes, shared.RateLookback + time.Duration(step)*time.Minute
+}
+
+func rateDeltasSelect(table, where string) string {
+ source := table + where
+ if table != "metric_points" {
+ source = "(SELECT recorded_at, tags, maxMerge(max_val) AS value FROM " + table + where + " GROUP BY recorded_at, tags)"
+ }
+ return "SELECT recorded_at, tags, value - lagInFrame(value) OVER w AS delta, row_number() OVER w AS rn FROM " + source +
+ " WINDOW w AS (PARTITION BY mapSort(tags) ORDER BY recorded_at ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)"
+}
+
func aggregationFunc(agg string, table string) string {
if table == "metric_points" {
switch agg {
diff --git a/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go b/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go
index 8335c4c9..206e3b2d 100644
--- a/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go
+++ b/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go
@@ -221,7 +221,7 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, project
FROM exception_stack_traces e ` + archiveSubquery + `
WHERE ` + whereClause + `
GROUP BY e.exception_hash` + havingClause + `
- ORDER BY ` + orderBy + ` ` + sortDirection + ` LIMIT :limit OFFSET :offset`
+ ORDER BY ` + orderBy + ` ` + sortDirection + `, e.exception_hash LIMIT :limit OFFSET :offset`
params["limit"] = pageSize
params["offset"] = offset
diff --git a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
index 454133d5..a9f91f5c 100644
--- a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go
@@ -88,7 +88,12 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
}
selectClause += ", " + strings.Join(exprs, " || :group_sep || ") + " AS group_key"
}
- selectClause += ", " + aggFunc + " AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
+ isRate := aggregation == "rate"
+ if isRate {
+ selectClause += ", " + aggFunc + " AS agg_value FROM (" + duckdbRateDeltasQuery + ") WHERE recorded_at >= :from AND delta IS NOT NULL"
+ } else {
+ selectClause += ", " + aggFunc + " AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
+ }
params := lit.P{
"project_id": projectId,
@@ -96,6 +101,10 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
"from": from.UTC(),
"to": to.UTC(),
}
+ if isRate {
+ params["lookback"] = from.Add(-shared.RateLookback).UTC()
+ params["secs"] = float64(secs)
+ }
for i, key := range groupKeys {
params[fmt.Sprintf("group_by_%d", i)] = key
}
@@ -360,8 +369,12 @@ func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Contex
return result, nil
}
+const duckdbRateDeltasQuery = "SELECT recorded_at, tags, value - lag(value) OVER (PARTITION BY tags ORDER BY recorded_at) AS delta FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :lookback AND recorded_at <= :to"
+
func duckdbAggregationFunc(agg string) string {
switch agg {
+ case "rate":
+ return "sum(CASE WHEN delta > 0 THEN delta ELSE 0 END) / :secs"
case "min":
return "min(value)"
case "max":
diff --git a/backend/app/repositories/telemetry/metric_point.repository_clickhouse_test.go b/backend/app/repositories/telemetry/metric_point.repository_clickhouse_test.go
new file mode 100644
index 00000000..6bf4c860
--- /dev/null
+++ b/backend/app/repositories/telemetry/metric_point.repository_clickhouse_test.go
@@ -0,0 +1,43 @@
+//go:build telemetry_ch
+
+package telemetry
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func TestMetricPointRepository_QueryTimeSeries_RateClampsBucketToRollupStep(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
+
+ tags := map[string]string{"server_name": "web-1"}
+ var points []models.MetricPoint
+ for hour, value := range []float64{1000, 1600, 2200, 2800} {
+ points = append(points, makeMetricPoint(projectId, "system.network.io", value, tags, base.Add(time.Duration(hour)*time.Hour)))
+ }
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "system.network.io", base.Add(-4*24*time.Hour), base.Add(4*time.Hour), 15, "rate", nil, "", 0)
+ if err != nil {
+ t.Fatalf("QueryTimeSeries failed: %v", err)
+ }
+ all := result["__all__"]
+ if len(all) != 3 {
+ t.Fatalf("expected 3 hourly buckets, got %d: %+v", len(all), all)
+ }
+ for i, p := range all {
+ if !p.Timestamp.Equal(base.Add(time.Duration(i+1) * time.Hour)) {
+ t.Fatalf("expected the 15-minute request to widen to hourly buckets, got %+v", all)
+ }
+ assertApproxEqual(t, "hourly bucket", p.Value, 600.0/3600, 0.001)
+ }
+}
diff --git a/backend/app/repositories/telemetry/metric_point_repository_test.go b/backend/app/repositories/telemetry/metric_point_repository_test.go
index af8d6427..719bca54 100644
--- a/backend/app/repositories/telemetry/metric_point_repository_test.go
+++ b/backend/app/repositories/telemetry/metric_point_repository_test.go
@@ -593,3 +593,107 @@ func TestMetricPointRepository_QueryTimeSeries_GroupByKeyWithComma(t *testing.T)
t.Fatalf("a comma in groupBy must name one tag key literally, got %v", result)
}
}
+
+func TestMetricPointRepository_QueryTimeSeries_Rate(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour)
+
+ sample := func(server, device string, value float64, offset time.Duration) models.MetricPoint {
+ return makeMetricPoint(projectId, "system.network.io", value, map[string]string{
+ "server_name": server, "device": device, "direction": "receive",
+ }, base.Add(offset))
+ }
+ points := []models.MetricPoint{
+ sample("web-1", "eth0", 1000, 0), sample("web-1", "eth0", 1600, 30*time.Second),
+ sample("web-1", "eth0", 2200, 60*time.Second), sample("web-1", "eth0", 2800, 90*time.Second),
+ sample("web-1", "eth0", 3400, 120*time.Second),
+ sample("web-1", "eth1", 500, 0), sample("web-1", "eth1", 800, 30*time.Second),
+ sample("web-1", "eth1", 1100, 60*time.Second), sample("web-1", "eth1", 1400, 90*time.Second),
+ sample("web-1", "eth1", 1700, 120*time.Second),
+ sample("web-2", "eth0", 1000, 0), sample("web-2", "eth0", 1500, 30*time.Second),
+ sample("web-2", "eth0", 100, 60*time.Second), sample("web-2", "eth0", 400, 90*time.Second),
+ }
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "system.network.io", base, base.Add(3*time.Minute), 1, "rate", nil, "server_name", 0)
+ if err != nil {
+ t.Fatalf("QueryTimeSeries failed: %v", err)
+ }
+
+ web1 := result["web-1"]
+ if len(web1) != 3 {
+ t.Fatalf("expected 3 buckets for web-1, got %d: %+v", len(web1), web1)
+ }
+ assertApproxEqual(t, "web-1 first bucket", web1[0].Value, 15.0, 0.01)
+ assertApproxEqual(t, "web-1 second bucket", web1[1].Value, 30.0, 0.01)
+ assertApproxEqual(t, "web-1 third bucket", web1[2].Value, 15.0, 0.01)
+
+ web2 := result["web-2"]
+ if len(web2) != 2 {
+ t.Fatalf("expected 2 buckets for web-2, got %d: %+v", len(web2), web2)
+ }
+ assertApproxEqual(t, "web-2 first bucket", web2[0].Value, 500.0/60, 0.01)
+ assertApproxEqual(t, "web-2 reset bucket", web2[1].Value, 300.0/60, 0.01)
+
+ later, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "system.network.io", base.Add(time.Minute), base.Add(3*time.Minute), 1, "rate", map[string]string{"server_name": "web-1"}, "", 0)
+ if err != nil {
+ t.Fatalf("QueryTimeSeries with lookback failed: %v", err)
+ }
+ all := later["__all__"]
+ if len(all) != 2 {
+ t.Fatalf("expected 2 buckets from the later range, got %d: %+v", len(all), all)
+ }
+ assertApproxEqual(t, "lookback bucket", all[0].Value, 30.0, 0.01)
+}
+
+func TestMetricPointRepository_QueryTimeSeries_RateOverLongRanges(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
+
+ sample := func(server string, value float64, hour int) models.MetricPoint {
+ return makeMetricPoint(projectId, "system.network.io", value, map[string]string{
+ "server_name": server, "device": "eth0", "direction": "receive",
+ }, base.Add(time.Duration(hour)*time.Hour))
+ }
+ points := []models.MetricPoint{
+ sample("web-1", 1000, 0), sample("web-1", 1600, 1), sample("web-1", 2200, 2), sample("web-1", 2800, 3),
+ sample("web-2", 1000, 0), sample("web-2", 1500, 1), sample("web-2", 100, 2), sample("web-2", 400, 3),
+ }
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ for _, span := range []time.Duration{12 * time.Hour, 4 * 24 * time.Hour, 40 * 24 * time.Hour} {
+ t.Run(span.String(), func(t *testing.T) {
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "system.network.io", base.Add(-span), base.Add(4*time.Hour), 60, "rate", nil, "server_name", 0)
+ if err != nil {
+ t.Fatalf("QueryTimeSeries failed: %v", err)
+ }
+
+ web1 := result["web-1"]
+ if len(web1) != 3 {
+ t.Fatalf("expected 3 hourly buckets for web-1, got %d: %+v", len(web1), web1)
+ }
+ for i, p := range web1 {
+ if !p.Timestamp.Equal(base.Add(time.Duration(i+1) * time.Hour)) {
+ t.Fatalf("expected hourly buckets starting one hour in, got %+v", web1)
+ }
+ assertApproxEqual(t, "web-1 bucket", p.Value, 600.0/3600, 0.001)
+ }
+
+ web2 := result["web-2"]
+ if len(web2) != 3 {
+ t.Fatalf("expected 3 hourly buckets for web-2, got %d: %+v", len(web2), web2)
+ }
+ assertApproxEqual(t, "web-2 first bucket", web2[0].Value, 500.0/3600, 0.001)
+ assertApproxEqual(t, "web-2 reset bucket", web2[1].Value, 0, 0.001)
+ assertApproxEqual(t, "web-2 last bucket", web2[2].Value, 300.0/3600, 0.001)
+ })
+ }
+}
diff --git a/backend/app/repositories/telemetry/shared/rate.go b/backend/app/repositories/telemetry/shared/rate.go
new file mode 100644
index 00000000..acd9e70c
--- /dev/null
+++ b/backend/app/repositories/telemetry/shared/rate.go
@@ -0,0 +1,5 @@
+package shared
+
+import "time"
+
+const RateLookback = 10 * time.Minute
diff --git a/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.go b/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.go
index 84479747..daa7ab71 100644
--- a/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.go
+++ b/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.go
@@ -198,7 +198,7 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, project
FROM exception_stack_traces e ` + archiveSubquery + `
WHERE ` + whereClause + `
GROUP BY e.exception_hash` + havingClause + `
- ORDER BY ` + orderBy + ` ` + sortDirection + ` LIMIT :limit OFFSET :offset`
+ ORDER BY ` + orderBy + ` ` + sortDirection + `, e.exception_hash LIMIT :limit OFFSET :offset`
params["limit"] = pageSize
params["offset"] = offset
diff --git a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
index 641fbda9..03260c90 100644
--- a/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
+++ b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go
@@ -100,7 +100,12 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
if isLast {
selectClause += ", max(recorded_at) AS last_ts"
}
- selectClause += " FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
+ isRate := aggregation == "rate"
+ if isRate {
+ selectClause += " FROM (" + sqliteRateDeltasQuery + ") WHERE recorded_at >= :from AND delta IS NOT NULL"
+ } else {
+ selectClause += " FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"
+ }
params := lit.P{
"project_id": projectId,
@@ -108,6 +113,10 @@ func (r *metricPointRepository) queryTimeSeries(ctx context.Context, projectId u
"from": sqlitetypes.NewSQLiteTime(from),
"to": sqlitetypes.NewSQLiteTime(to),
}
+ if isRate {
+ params["lookback"] = sqlitetypes.NewSQLiteTime(from.Add(-shared.RateLookback))
+ params["secs"] = float64(secs)
+ }
for i, key := range groupKeys {
params[fmt.Sprintf("group_by_%d", i)] = key
}
@@ -403,8 +412,12 @@ func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Contex
return result, nil
}
+const sqliteRateDeltasQuery = "SELECT recorded_at, tags, value - lag(value) OVER (PARTITION BY tags ORDER BY recorded_at) AS delta FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :lookback AND recorded_at <= :to"
+
func sqliteAggregationFunc(agg string) string {
switch agg {
+ case "rate":
+ return "sum(CASE WHEN delta > 0 THEN delta ELSE 0 END) / :secs"
case "min":
return "min(value)"
case "max":
diff --git a/backend/app/repositories/transactional/pg/check_incident.repository.go b/backend/app/repositories/transactional/pg/check_incident.repository.go
index da5d055c..2e023f33 100644
--- a/backend/app/repositories/transactional/pg/check_incident.repository.go
+++ b/backend/app/repositories/transactional/pg/check_incident.repository.go
@@ -4,6 +4,7 @@ package pg
import (
"database/sql"
+ "strings"
"time"
"github.com/tracewayapp/traceway/backend/app/db"
@@ -169,3 +170,48 @@ func (r *checkIncidentRepository) DeleteManual(tx *sql.Tx, id int) error {
}
var CheckIncidentRepository = checkIncidentRepository{}
+
+func orgIncidentCondition(organizationId int, search string, from, to *time.Time, params lit.P) string {
+ condition := "(p.organization_id = :organization_id OR sp.organization_id = :organization_id)"
+ params["organization_id"] = organizationId
+ if from != nil {
+ condition += " AND (i.resolved_at IS NULL OR i.resolved_at >= :from)"
+ params["from"] = from.UTC()
+ }
+ if to != nil {
+ condition += " AND i.started_at <= :to"
+ params["to"] = to.UTC()
+ }
+ if search != "" {
+ condition += ` AND (LOWER(i.title) LIKE :search ESCAPE '\' OR LOWER(c.name) LIKE :search ESCAPE '\' OR LOWER(sp.name) LIKE :search ESCAPE '\' OR LOWER(i.error_message) LIKE :search ESCAPE '\')`
+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"
+ }
+ return condition
+}
+
+func (r *checkIncidentRepository) FindByOrganizationPaged(tx *sql.Tx, organizationId int, search string, from, to *time.Time, limit int, offset int) ([]*models.OrgIncident, error) {
+ params := lit.P{"limit": limit, "offset": offset}
+ condition := orgIncidentCondition(organizationId, search, from, to, params)
+ return lit.SelectNamed[models.OrgIncident](
+ tx,
+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE "+condition+" ORDER BY i.started_at DESC, i.id DESC LIMIT :limit OFFSET :offset",
+ params,
+ )
+}
+
+func (r *checkIncidentRepository) CountByOrganizationFiltered(tx *sql.Tx, organizationId int, search string, from, to *time.Time) (int, error) {
+ params := lit.P{}
+ condition := orgIncidentCondition(organizationId, search, from, to, params)
+ result, err := lit.SelectSingleNamed[models.CountResult](
+ tx,
+ "SELECT COUNT(*) as count "+checkIncidentOrgJoin+" WHERE "+condition,
+ params,
+ )
+ if err != nil {
+ return 0, err
+ }
+ if result == nil {
+ return 0, nil
+ }
+ return result.Count, nil
+}
diff --git a/backend/app/repositories/transactional/pg/page.repository.go b/backend/app/repositories/transactional/pg/page.repository.go
index 691afeb7..2263582c 100644
--- a/backend/app/repositories/transactional/pg/page.repository.go
+++ b/backend/app/repositories/transactional/pg/page.repository.go
@@ -4,6 +4,7 @@ package pg
import (
"database/sql"
+ "strings"
"time"
"github.com/tracewayapp/traceway/backend/app/db"
@@ -200,3 +201,47 @@ func (r *pageRepository) ResolveSystem(tx *sql.Tx, id int, now time.Time) (bool,
}
var PageRepository = pageRepository{}
+
+func pageListCondition(status string, search string, from, to *time.Time, params lit.P) string {
+ condition := "(" + statusCondition(status) + ")"
+ if from != nil {
+ condition += " AND created_at >= :from"
+ params["from"] = from.UTC()
+ }
+ if to != nil {
+ condition += " AND created_at <= :to"
+ params["to"] = to.UTC()
+ }
+ if search != "" {
+ condition += ` AND (LOWER(subject) LIKE :search ESCAPE '\' OR LOWER(rule_name) LIKE :search ESCAPE '\')`
+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"
+ }
+ return condition
+}
+
+func (r *pageRepository) FindByOrganizationFiltered(tx *sql.Tx, organizationId int, status string, search string, from, to *time.Time, limit int, offset int) ([]*models.Page, error) {
+ params := lit.P{"organization_id": organizationId, "limit": limit, "offset": offset}
+ condition := pageListCondition(status, search, from, to, params)
+ return lit.SelectNamed[models.Page](
+ tx,
+ "SELECT "+pageColumns+" FROM pages WHERE organization_id = :organization_id AND "+condition+" ORDER BY created_at DESC, id DESC LIMIT :limit OFFSET :offset",
+ params,
+ )
+}
+
+func (r *pageRepository) CountByOrganizationFiltered(tx *sql.Tx, organizationId int, status string, search string, from, to *time.Time) (int, error) {
+ params := lit.P{"organization_id": organizationId}
+ condition := pageListCondition(status, search, from, to, params)
+ result, err := lit.SelectSingleNamed[models.CountResult](
+ tx,
+ "SELECT COUNT(*) as count FROM pages WHERE organization_id = :organization_id AND "+condition,
+ params,
+ )
+ if err != nil {
+ return 0, err
+ }
+ if result == nil {
+ return 0, nil
+ }
+ return result.Count, nil
+}
diff --git a/backend/app/repositories/transactional/sqlite/check_incident.repository.go b/backend/app/repositories/transactional/sqlite/check_incident.repository.go
index c8406b9f..aa3fb61f 100644
--- a/backend/app/repositories/transactional/sqlite/check_incident.repository.go
+++ b/backend/app/repositories/transactional/sqlite/check_incident.repository.go
@@ -4,6 +4,7 @@ package sqlite
import (
"database/sql"
+ "strings"
"time"
"github.com/tracewayapp/traceway/backend/app/db"
@@ -169,3 +170,48 @@ func (r *checkIncidentRepository) DeleteManual(tx *sql.Tx, id int) error {
}
var CheckIncidentRepository = checkIncidentRepository{}
+
+func orgIncidentCondition(organizationId int, search string, from, to *time.Time, params lit.P) string {
+ condition := "(p.organization_id = :organization_id OR sp.organization_id = :organization_id)"
+ params["organization_id"] = organizationId
+ if from != nil {
+ condition += " AND (i.resolved_at IS NULL OR i.resolved_at >= :from)"
+ params["from"] = from.UTC()
+ }
+ if to != nil {
+ condition += " AND i.started_at <= :to"
+ params["to"] = to.UTC()
+ }
+ if search != "" {
+ condition += ` AND (LOWER(i.title) LIKE :search ESCAPE '\' OR LOWER(c.name) LIKE :search ESCAPE '\' OR LOWER(sp.name) LIKE :search ESCAPE '\' OR LOWER(i.error_message) LIKE :search ESCAPE '\')`
+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"
+ }
+ return condition
+}
+
+func (r *checkIncidentRepository) FindByOrganizationPaged(tx *sql.Tx, organizationId int, search string, from, to *time.Time, limit int, offset int) ([]*models.OrgIncident, error) {
+ params := lit.P{"limit": limit, "offset": offset}
+ condition := orgIncidentCondition(organizationId, search, from, to, params)
+ return lit.SelectNamed[models.OrgIncident](
+ tx,
+ "SELECT "+checkIncidentJoinedColumns+", c.name AS check_name, sp.name AS status_page_name "+checkIncidentOrgJoin+" WHERE "+condition+" ORDER BY i.started_at DESC, i.id DESC LIMIT :limit OFFSET :offset",
+ params,
+ )
+}
+
+func (r *checkIncidentRepository) CountByOrganizationFiltered(tx *sql.Tx, organizationId int, search string, from, to *time.Time) (int, error) {
+ params := lit.P{}
+ condition := orgIncidentCondition(organizationId, search, from, to, params)
+ result, err := lit.SelectSingleNamed[models.CountResult](
+ tx,
+ "SELECT COUNT(*) as count "+checkIncidentOrgJoin+" WHERE "+condition,
+ params,
+ )
+ if err != nil {
+ return 0, err
+ }
+ if result == nil {
+ return 0, nil
+ }
+ return result.Count, nil
+}
diff --git a/backend/app/repositories/transactional/sqlite/page.repository.go b/backend/app/repositories/transactional/sqlite/page.repository.go
index ab0f505c..de78b3e2 100644
--- a/backend/app/repositories/transactional/sqlite/page.repository.go
+++ b/backend/app/repositories/transactional/sqlite/page.repository.go
@@ -4,6 +4,7 @@ package sqlite
import (
"database/sql"
+ "strings"
"time"
"github.com/tracewayapp/traceway/backend/app/db"
@@ -200,3 +201,47 @@ func (r *pageRepository) ResolveSystem(tx *sql.Tx, id int, now time.Time) (bool,
}
var PageRepository = pageRepository{}
+
+func pageListCondition(status string, search string, from, to *time.Time, params lit.P) string {
+ condition := "(" + statusCondition(status) + ")"
+ if from != nil {
+ condition += " AND created_at >= :from"
+ params["from"] = from.UTC()
+ }
+ if to != nil {
+ condition += " AND created_at <= :to"
+ params["to"] = to.UTC()
+ }
+ if search != "" {
+ condition += ` AND (LOWER(subject) LIKE :search ESCAPE '\' OR LOWER(rule_name) LIKE :search ESCAPE '\')`
+ params["search"] = "%" + likeEscaper.Replace(strings.ToLower(search)) + "%"
+ }
+ return condition
+}
+
+func (r *pageRepository) FindByOrganizationFiltered(tx *sql.Tx, organizationId int, status string, search string, from, to *time.Time, limit int, offset int) ([]*models.Page, error) {
+ params := lit.P{"organization_id": organizationId, "limit": limit, "offset": offset}
+ condition := pageListCondition(status, search, from, to, params)
+ return lit.SelectNamed[models.Page](
+ tx,
+ "SELECT "+pageColumns+" FROM pages WHERE organization_id = :organization_id AND "+condition+" ORDER BY created_at DESC, id DESC LIMIT :limit OFFSET :offset",
+ params,
+ )
+}
+
+func (r *pageRepository) CountByOrganizationFiltered(tx *sql.Tx, organizationId int, status string, search string, from, to *time.Time) (int, error) {
+ params := lit.P{"organization_id": organizationId}
+ condition := pageListCondition(status, search, from, to, params)
+ result, err := lit.SelectSingleNamed[models.CountResult](
+ tx,
+ "SELECT COUNT(*) as count FROM pages WHERE organization_id = :organization_id AND "+condition,
+ params,
+ )
+ if err != nil {
+ return 0, err
+ }
+ if result == nil {
+ return 0, nil
+ }
+ return result.Count, nil
+}
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index ce3d8b3d..be09d6de 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -124,6 +124,9 @@ func Run(opts ...Option) {
if err := backfill.RunDashboards(); err != nil {
panic(fmt.Errorf("dashboards backfill failed: %w", err))
}
+ if err := backfill.RunOtelAgentDashboardSources(); err != nil {
+ panic(fmt.Errorf("OTel agent dashboard backfill failed: %w", err))
+ }
if o != nil {
if err := seed(o); err != nil {
diff --git a/docs/pages/client/otel/metrics.mdx b/docs/pages/client/otel/metrics.mdx
index b0935cf2..74a93a35 100644
--- a/docs/pages/client/otel/metrics.mdx
+++ b/docs/pages/client/otel/metrics.mdx
@@ -43,7 +43,7 @@ Two other things live on the **Resource** rather than on the data point, and Tra
The first is the identity of the thing being measured. The hostmetrics process scraper emits one `ResourceMetrics` block per process, and docker_stats, kubeletstats and the postgresql receiver do the same for containers, pods, nodes and databases. Without lifting those, every `process.cpu.utilization` point would look identical.
-The second is host and platform metadata, which is what the [organization overview](/learn/organization-overview) shows next to each instance.
+The second is host and platform metadata, which is what the [organization overview](/learn/organization-overview) shows next to each server.
| Attribute | Typical source |
|-----------|----------------|
diff --git a/docs/pages/learn/dashboards.mdx b/docs/pages/learn/dashboards.mdx
index 18b34c48..c67bf217 100644
--- a/docs/pages/learn/dashboards.mdx
+++ b/docs/pages/learn/dashboards.mdx
@@ -48,7 +48,17 @@ The instance picker in the dashboard header narrows every widget on the page to
The scope is applied as an extra tag filter on each widget's queries, on top of whatever filters the widget already has. Nothing is saved to the dashboard, so it does not change what teammates see; it lives in the URL as `?server=<name>` and survives time-range changes, which makes the filtered view shareable.
-This is where a row in the [organization overview](/learn/organization-overview) leads. Selecting an instance there opens its project's dashboards already scoped to that machine over the last 30 minutes, jumping straight to the **OTelemetry Server Agent** tab when the project has it installed. Clear the picker to go back to the whole project.
+With **All instances** selected a widget shows whatever its sources define. The **OTelemetry Server Agent** template groups every widget by `server_name`, so its charts draw one line per server until you narrow the picker to one; a widget of your own does the same once you set its **Group By** to `server_name`.
+
+This is where a row on the organization's [Servers page](/learn/organization-overview#servers) leads. Selecting a server there opens its project's dashboards already scoped to that machine over the last 30 minutes, jumping straight to the **OTelemetry Server Agent** tab when the project has it installed. Clear the picker to go back to the whole project.
+
+## Counters, rates and inverted values
+
+Host metrics such as `system.network.io` and `system.disk.io` are cumulative counters: the value only ever grows. Charted as an average they climb forever, so give such a source the **rate** aggregation. Each series (every distinct tag set, so a counter per device or direction stays on its own) is differenced against its previous sample, resets are dropped, and the result is a per-second rate with a matching unit: bytes become `B/s`, packets become packets per second. A rate keeps the same reach as any other aggregation. On ClickHouse a range over six hours reads the minute rollup and one over three days reads the hourly rollup, so buckets there are at least an hour wide.
+
+A source can also be **inverted**, which charts 1 − value. The OTel agent reports `system.cpu.utilization` per state, and the `idle` state inverted is the busy share; that is how the Server Agent template draws CPU. The template's other widgets carry the matching state filters (`used` for memory and filesystem, `ESTABLISHED` TCP for open connections) so a widget never averages unrelated states together.
+
+Dashboards installed from the Server Agent template before these sources existed are upgraded once at startup: a widget that still carries the original plain average takes the template's current sources for its metric, a widget you have edited is left as it is.
## Dashboards as code
diff --git a/docs/pages/learn/index.mdx b/docs/pages/learn/index.mdx
index 3921f50c..9bd4689b 100644
--- a/docs/pages/learn/index.mdx
+++ b/docs/pages/learn/index.mdx
@@ -40,7 +40,7 @@ See [Data Flow](/learn/data-flow) for how these connect during request processin
## Above a single project
-Everything above is scoped to one project. The [Organization Overview](/learn/organization-overview) sits above them all: every instance reporting into the organization, every recently active issue, every monitor, and every open on-call page, on one page. It is how a fleet of servers or a [Kubernetes cluster](/learn/kubernetes) is read at a glance before you drill into the project that owns the problem.
+Everything above is scoped to one project. The [Organization Overview](/learn/organization-overview) sits above them all: every server reporting into the organization, every recently active issue, every monitor, and every open on-call page, each one a sidebar click apart. It is how a fleet of servers or a [Kubernetes cluster](/learn/kubernetes) is read at a glance before you drill into the project that owns the problem.
## Authentication
diff --git a/docs/pages/learn/kubernetes.mdx b/docs/pages/learn/kubernetes.mdx
index 0bc94cda..897b1953 100644
--- a/docs/pages/learn/kubernetes.mdx
+++ b/docs/pages/learn/kubernetes.mdx
@@ -10,7 +10,7 @@ Ready-to-apply manifests live in the repository at [`examples/kubernetes`](https
| Workload | Reads | Shows up as |
|---|---|---|
-| `traceway-node-agent` (DaemonSet) | Host CPU, memory, disk, filesystem, network of each node | One [instance row per node](/learn/organization-overview#instances), grouped by cluster |
+| `traceway-node-agent` (DaemonSet) | Host CPU, memory, disk, filesystem, network of each node | One [server row per node](/learn/organization-overview#servers), grouped by cluster |
| `traceway-node-agent` | Kubelet node and pod resource usage | `k8s.pod.*` metrics for [dashboard widgets](/learn/dashboards) |
| `traceway-node-agent` | Every container's stdout and stderr | The [Logs](/learn/logs) page, tagged with pod, namespace and container |
| `traceway-cluster-agent` (Deployment) | Pod phases, deployment replicas, node conditions, allocatable resources | `k8s.*` cluster metrics |
@@ -19,7 +19,7 @@ Ready-to-apply manifests live in the repository at [`examples/kubernetes`](https
The applications keep their own instrumentation. The collectors describe the cluster the applications run on; they do not replace [OpenTelemetry in the app](/client/otel).
-<img src="/organization-overview.png" alt="The organization overview with instances grouped by Kubernetes cluster, plus plain hosts under Not in a Kubernetes cluster" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+<img src="/organization-overview.png" alt="The organization Servers page with servers grouped by Kubernetes cluster, plus plain hosts under Not in a Kubernetes cluster" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
Nodes from every cluster and every plain host land in the same table, grouped by cluster. Machines with no `k8s.cluster.name` collect under **Not in a Kubernetes cluster**, so a half-migrated fleet still reads as one fleet.
@@ -62,7 +62,7 @@ data:
TRACEWAY_ENDPOINT: https://traceway.mycompany.com/api/otel
```
-`TRACEWAY_CLUSTER_NAME` becomes `k8s.cluster.name` on everything the cluster reports, and it is the string the organization overview groups instances by. Give every cluster a distinct one.
+`TRACEWAY_CLUSTER_NAME` becomes `k8s.cluster.name` on everything the cluster reports, and it is the string the organization's Servers page groups servers by. Give every cluster a distinct one.
`TRACEWAY_ENDPOINT` is the OTLP/HTTP base URL of your instance, ending in `/api/otel`. On Traceway Cloud that is `https://cloud.tracewayapp.com/api/otel`. The collector appends `/v1/metrics`, `/v1/logs` and `/v1/traces` itself.
@@ -81,7 +81,7 @@ kubectl -n traceway rollout status daemonset/traceway-node-agent
kubectl -n traceway logs -l app.kubernetes.io/name=traceway-node-agent --tail=50
```
-Metrics arrive within about 30 seconds. Open the organization overview: every node appears as its own instance, grouped under your cluster name.
+Metrics arrive within about 30 seconds. Open the organization's Servers page: every node appears as its own server, grouped under your cluster name.
</Steps>
@@ -110,7 +110,7 @@ The same `traceway-token` Secret and `traceway-settings` ConfigMap are expected.
The chart's `hostMetrics` preset wires up the scrapers but leaves
`system.cpu.utilization`, `system.memory.utilization` and
`system.filesystem.utilization` **disabled**, because that is the receiver's
- default. Those three are exactly what the organization overview reads. Both
+ default. Those three are exactly what the organization's Servers page reads. Both
values files turn them on; if you write your own, do the same or the instance
rings stay empty.
</Callout>
@@ -279,7 +279,7 @@ Separate from monitoring a cluster, Traceway can run in one. The repository ship
## Next steps
-- [Organization Overview](/learn/organization-overview) for what the instance table does with all this
+- [Organization Overview](/learn/organization-overview) for what the Servers page does with all this
- [OpenTelemetry](/client/otel) for instrumenting the applications
- [Resource Attributes](/client/otel/metrics#resource-attributes) for the full allowlist
- [Dashboards](/learn/dashboards) for building pod and namespace views
diff --git a/docs/pages/learn/metrics.mdx b/docs/pages/learn/metrics.mdx
index 5219ff5d..a83c26b3 100644
--- a/docs/pages/learn/metrics.mdx
+++ b/docs/pages/learn/metrics.mdx
@@ -38,7 +38,7 @@ Tags come from the data-point attributes you pass when recording a value, plus t
## Visualizing Metrics
-Server metrics also drive the instance table on the [Organization Overview](/learn/organization-overview), which reads `system.cpu.utilization`, `system.memory.utilization`, `system.filesystem.utilization` and `system.network.io` per `server_name`.
+Server metrics also drive the Servers page of the [Organization Overview](/learn/organization-overview), which reads `system.cpu.utilization`, `system.memory.utilization`, `system.filesystem.utilization` and `system.network.io` per `server_name`.
Metrics are visualized on [Dashboards](/learn/dashboards): organization-owned, JSON-defined tabs of chart widgets that you can apply to any of your projects, install from the built-in template marketplace (host metrics, Go runtime, Traceway self-monitoring), or import from Grafana.
diff --git a/docs/pages/learn/on-call.mdx b/docs/pages/learn/on-call.mdx
index 75cf8a75..e651f8da 100644
--- a/docs/pages/learn/on-call.mdx
+++ b/docs/pages/learn/on-call.mdx
@@ -4,7 +4,7 @@ On-Call turns an alert into a person's phone ringing. Alerts on their own post t
Traceway ships the full paging stack: teams, rotating schedules, escalation policies, per-responder contact methods, and a no-login acknowledge link. It lives under **On-Call** in the sidebar, and the badge there counts the pages still open on the current project.
-That badge and that queue are per project. For pages across every project in the organization at once, use the [Organization Overview](/learn/organization-overview).
+That badge and that queue are per project. For pages across every project in the organization at once, use the organization's [On-Call page](/learn/organization-overview#on-call).
<img src="/on-call/oncall-pages.png" alt="The On-Call page showing the incident queue" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
diff --git a/docs/pages/learn/organization-overview.mdx b/docs/pages/learn/organization-overview.mdx
index 0b0bfd83..50b47aab 100644
--- a/docs/pages/learn/organization-overview.mdx
+++ b/docs/pages/learn/organization-overview.mdx
@@ -2,51 +2,44 @@
import { Callout } from "nextra/components";
-Every other page in Traceway is scoped to one project. The organization overview is the one that is not: it puts every instance, issue, monitor, and open on-call page across all of your organization's projects on a single screen.
+Every other page in Traceway is scoped to one project. The organization pages are the ones that are not: they put every server, issue, monitor, and open on-call page across all of your organization's projects one sidebar click apart.
-It is the page for the question a project view cannot answer. Which box is about to run out of memory? What is already paging someone? Is anything on fire anywhere?
+They answer the questions a project view cannot. Which box is about to run out of memory? What is already paging someone? Is anything on fire anywhere?
-<img src="/organization-overview.png" alt="The Traceway organization overview: operational pulse counters, an instance table grouped by Kubernetes cluster, and open on-call pages" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+<img src="/organization-overview.png" alt="The organization Servers page: a fleet health bar with state filters above a server table grouped by Kubernetes cluster" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
## Getting there
-Open the switcher in the top-left header. Organizations are the headings; their projects are listed underneath. Selecting the organization itself opens the overview, selecting a project opens that project's dashboard.
+Open the switcher in the top-left header. Organizations are the headings; their projects are listed underneath. Selecting the organization itself opens its pages, selecting a project opens that project's dashboard.
<img src="/organization-switcher.png" alt="The header switcher, listing organizations with their projects nested underneath" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
-The overview replaces the project sidebar with a plain header, because nothing on it is project-scoped. Pick a project from the switcher to get the sidebar back.
+The sidebar stays where it is and switches to the organization's pages, under an **Organization** label: **Servers**, **Issues**, **Monitors**, **On-Call**, and **Projects**. Each one fans out over all of the organization's projects. The **Monitors** badge counts monitors currently down and the **On-Call** badge counts open pages, across the whole organization. Pick a project from the switcher, or select a row on any of the pages, to get back into a project.
-After signing in you land on the overview automatically when your first organization has more than one project. With a single project you go straight to that project's dashboard, since an overview of one thing is not worth a click. That organization has no overview at all: the switcher lists it as a plain heading, and opening `/organization` for it sends you into the project.
+After signing in you land on the Servers page automatically when your first organization has more than one project. With a single project you go straight to that project's dashboard, since an overview of one thing is not worth a click. That organization has no organization pages at all: the switcher lists it as a plain heading, and opening `/organization` for it sends you into the project.
-The page also adapts to what the organization contains. Instances and monitors are backend features, so when every project is a browser or mobile app the **Instances** section, the **Monitors** tab, and the four instance counters disappear, and the pulse strip keeps only issues and open on-call pages.
+The sidebar also adapts to what the organization contains. Servers and monitors are backend features, so when every project is a browser or mobile app the **Servers** and **Monitors** items disappear and **Issues** becomes the first page.
-Every organization member can open it, read-only members included. It shows the projects you can already see, so it grants no access you did not have.
+Every organization member can open these pages, read-only members included. They show the projects you can already see, so they grant no access you did not have.
<Callout type="info">
- The overview is per organization, not global. If you belong to more than one,
- each has its own page; switch between them from the same menu.
+ The pages are per organization, not global. If you belong to more than one,
+ each has its own set; switch between them from the same menu.
</Callout>
-## Operational pulse
+## Servers
-The strip across the top is the summary you read first.
+The Servers page is a live view of every server reporting into the organization over the last 30 minutes. One row per distinct `server_name`, per project.
-| Counter | Meaning |
-|---|---|
-| **Reporting now** | Instances whose last metric arrived within 3 minutes |
-| **Needs attention** | Instances that are critical, warning, or stale |
-| **Stale signals** | Instances that have gone quiet for more than 3 minutes |
-| **Network I/O** | Combined receive plus transmit rate across every instance |
-| **Issues · 24h** | Distinct issues seen across all projects in the last 24 hours; opens the Issues tab |
-| **Active response** | Open on-call pages plus monitors currently down; opens the Monitors tab |
+Rows come from server metrics, not from any registry, so a server appears when it starts reporting and disappears when it stops. Nothing to register, nothing to clean up.
-The Overview tab refreshes itself every minute, and **Refresh** forces it. A refresh that fails leaves the last good snapshot on screen with a warning rather than blanking the page, and on every tab, if one project's telemetry cannot be read the others still render with a notice.
+### Fleet health
-## Instances
+The bar under the title is the summary you read first: one segment per health state, sized by how many servers are in it, worst first. The line above it says how many servers need attention, and the chips beside it carry the counts. Selecting a chip filters the table to that state; select it again to clear the filter.
-The instance table is a live view of every server reporting into the organization, over the last 30 minutes. One row per distinct `server_name`, per project.
+The page refreshes itself every minute, and **Refresh** forces it. A refresh that fails leaves the last good snapshot on screen with a warning rather than blanking the page, and on every organization page, if one project's telemetry cannot be read the others still render with a notice.
-Rows come from server metrics, not from any registry, so an instance appears when it starts reporting and disappears when it stops. Nothing to register, nothing to clean up.
+### Columns
| Column | Source |
|---|---|
@@ -54,9 +47,9 @@ Rows come from server metrics, not from any registry, so an instance appears whe
| Memory | `system.memory.utilization` where `state=used` |
| Disk | `system.filesystem.utilization` where `state=used` |
| Network | `system.network.io` split by `direction`, as a rate |
-| Last signal | Most recent metric point from that instance |
+| Last signal | Most recent metric point from that server |
-Hosts running the [Traceway OTel Agent](/learn/otel-agent) or any OpenTelemetry Collector with the hostmetrics receiver fill in all four. Instances still on the older Traceway Go SDK metric names (`cpu.used_pcnt`, `mem.used`, `mem.total`) fill in CPU and memory, and the row is labelled **SDK metrics** instead of **OTel Agent**.
+Hosts running the [Traceway OTel Agent](/learn/otel-agent) or any OpenTelemetry Collector with the hostmetrics receiver fill in all four. Servers still on the older Traceway Go SDK metric names (`cpu.used_pcnt`, `mem.used`, `mem.total`) fill in CPU and memory, and the row is labelled **SDK metrics** instead of **OTel Agent**.
<Callout type="warning">
The three `system.*.utilization` metrics are **off by default** in the
@@ -76,56 +69,60 @@ Each row carries a state, computed from the latest values:
| **Stale** | No metric in the last 3 minutes, whatever the last values were |
| **Healthy** | Everything else |
-Rows sort worst-first inside their group: critical, then stale, then warning, then healthy. Stale outranks warning deliberately. An instance that stopped talking is a bigger unknown than one running warm.
+Rows sort worst-first inside their group, and the health bar reads the same way: critical, then stale, then warning, then healthy. Stale outranks warning deliberately. A server that stopped talking is a bigger unknown than one running warm.
### The metadata line
-Under each instance name is whatever the telemetry knows about it: the project, the host name when it differs from the instance name, OS and architecture, cloud region, the Kubernetes node, and whether the numbers came from the OTel Agent or the SDK. All of it comes from resource attributes on the metrics themselves (see [Resource Attributes](/client/otel/metrics#resource-attributes)), so richer instrumentation means a more useful line, and nothing needs configuring in Traceway.
+Under each server name is whatever the telemetry knows about it: the project, the host name when it differs from the server name, OS and architecture, cloud region, the Kubernetes node, and whether the numbers came from the OTel Agent or the SDK. All of it comes from resource attributes on the metrics themselves (see [Resource Attributes](/client/otel/metrics#resource-attributes)), so richer instrumentation means a more useful line, and nothing needs configuring in Traceway.
### Search, filter, group
-- **Find an instance** matches the instance name, project, host name, host id, OS, architecture, cloud region, Kubernetes cluster, and node name.
-- **Health state** narrows to needs attention, stale, or healthy.
-- **Project** appears once instances span more than one project.
+- **Find a server** matches the server name, project, host name, host id, OS, architecture, cloud region, Kubernetes cluster, and node name.
+- **Health chips** narrow to critical, stale, warning, or healthy servers.
+- **Project** appears once servers span more than one project.
- **Group by** switches between project, Kubernetes cluster, and no grouping.
-Grouping defaults to project. When any instance carries a `k8s.cluster.name` attribute, the page starts grouped by Kubernetes cluster instead, and instances without one collect under **Not in a Kubernetes cluster**. See [Kubernetes](/learn/kubernetes) for how that attribute gets set.
+Grouping defaults to project. When any server carries a `k8s.cluster.name` attribute, the page starts grouped by Kubernetes cluster instead, and servers without one collect under **Not in a Kubernetes cluster**. See [Kubernetes](/learn/kubernetes) for how that attribute gets set.
### Clicking through
-Selecting a row opens that instance's dashboard: the project's dashboards page, scoped to that one `server_name`, over the last 30 minutes. If the project has the **OTelemetry Server Agent** dashboard installed, that tab opens directly.
+Selecting a row opens that server's dashboard: the project's dashboards page, scoped to that one `server_name`, over the last 30 minutes. If the project has the **OTelemetry Server Agent** dashboard installed, that tab opens directly.
The scope is a normal URL parameter (`?server=<name>`), so the link is shareable and the page keeps the filter while you change the time range. Clear it from the instance picker in the dashboard header. See [Dashboards](/learn/dashboards#filtering-by-instance).
-## Active on-call response
-
-Under the instances is every page that still needs acknowledgement or resolution, across all projects: title, project, severity, status, and how long it has been open. It is the same queue as the [On-Call](/learn/on-call) page, without the per-project filter. Acknowledged pages stay listed until they are resolved, so nothing quietly falls off the screen.
-
## Issues
-<img src="/organization-issues.png" alt="The organization Issues tab: recently active issues from every project" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+<img src="/organization-issues.png" alt="The organization Issues page: recently active issues from every project" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
-Recently active issues from every project in the last 24 hours, newest event first, with the project each belongs to. Capped at 50 rows; the counter above the table is the true total across the organization. This is a triage feed, not the [Issues](/learn/issues) page, which is where you filter, search, and archive.
+Issues from every project in the selected time range, with the project each belongs to. The page works like the project-level [Issues](/learn/issues) page: a time range picker (last 24 hours by default), a search box that matches issues, messages, or both, sortable **Events** and **Last seen** columns, and pagination. The counter next to the title is the total across the organization for that range. Every project contributes its own top groups and the page is cut from their merged order, so a page here is exactly what one combined project would show. Selecting a row opens the issue in its project, where you archive it.
## Monitors
-<img src="/organization-monitors.png" alt="The organization Monitors tab: every monitor across projects with status, uptime and average latency, plus recent incidents" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+<img src="/organization-monitors.png" alt="The organization Monitors page: every monitor across projects with status, uptime and average latency, plus recent incidents" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+
+Every [monitor](/learn/monitors) in the organization in one sortable list: type, project, current status, 30-day uptime, 30-day average latency, and last run. Search narrows the list by name, project, or target, and the type dropdown keeps only HTTP, TCP, or browser monitors. The counters next to the title show how many monitors there are and how many are down right now. Monitors deliberately carry no time filter, like the project page.
-Every [monitor](/learn/monitors) in the organization in one sortable list: type, project, current status, 30-day uptime, 30-day average latency, and when it last had an incident. Underneath is the organization's incident history for the last 90 days, across monitors and status pages, with the ongoing ones marked.
+Underneath is the organization's incident history across monitors and status pages, with its own time range picker (last 3 months by default), a search over title, monitor, status page, and error message, and pagination. An incident is listed when it was open at any point in the range, so the ongoing ones are always there, marked as such.
Uptime excludes missed probes, so a window where Traceway itself was down reads as unknown rather than as a fabricated 100%.
+## On-Call
+
+<img src="/organization-on-call.png" alt="The organization On-Call page: every page that still needs acknowledgement or resolution, across projects" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+
+Pages from every project: title, project, severity, status, and when each was opened. It is the same queue as the [On-Call](/learn/on-call) page, without the per-project filter, and it refreshes itself every minute. The status chips switch between all active, open, acknowledged, and resolved pages; the search box matches subject and rule name; the time range picker filters by when a page was opened and defaults to the last month, wide enough that an ageing open page does not quietly fall off the screen. Acknowledged pages stay active until they are resolved. Selecting a row opens the page in its project.
+
## Projects
-<img src="/organization-projects.png" alt="The organization Projects tab, listing each project with its framework and your effective access level" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
+<img src="/organization-projects.png" alt="The organization Projects page, listing each project with its framework and your effective access level" style={{ maxWidth: '100%', height: 'auto', marginTop: '16px', borderRadius: '8px', border: '1px solid #e5e7eb' }} />
Every project in the organization with its framework, when it was added, and your **effective** access level on it: your organization role, unless a [per-project override](/learn/projects) changes it. Selecting a row opens that project.
## Multi-organization setups
-A user can belong to several organizations, and each carries its own overview, members, dashboards, teams, schedules, and escalation policies. Nothing is shared across the boundary, which is what makes an organization the right shape for an agency's clients or a company's independent business units.
+A user can belong to several organizations, and each carries its own organization pages, members, dashboards, teams, schedules, and escalation policies. Nothing is shared across the boundary, which is what makes an organization the right shape for an agency's clients or a company's independent business units.
-Within one organization, prefer more projects over more organizations. Projects are the isolation boundary for telemetry, but the overview, dashboards, on-call rotations, and status pages are all organization-wide, so splitting a fleet across organizations means giving up exactly the view that makes a fleet manageable.
+Within one organization, prefer more projects over more organizations. Projects are the isolation boundary for telemetry, but the organization pages, dashboards, on-call rotations, and status pages are all organization-wide, so splitting a fleet across organizations means giving up exactly the view that makes a fleet manageable.
## Next steps
diff --git a/docs/pages/learn/otel-agent.mdx b/docs/pages/learn/otel-agent.mdx
index 31accc12..46f7d606 100644
--- a/docs/pages/learn/otel-agent.mdx
+++ b/docs/pages/learn/otel-agent.mdx
@@ -60,7 +60,7 @@ Metrics are tagged with `server_name`, which comes from `TRACEWAY_SERVICE_NAME`
The agent also attaches resource attributes to the OTLP payload: `service.name`, `host.name`, `os.type`, and on cloud VMs `cloud.provider`, `cloud.region`, and `cloud.account.id` (EC2 / GCE / Azure are auto-detected). Traceway lifts `service.name` onto metric tags, renamed to `server_name`. Every other resource attribute is dropped unless it is on a fixed allowlist, which covers host and platform metadata (`host.name`, `host.id`, `host.arch`, `os.type`, `os.description`, `cloud.provider`, `cloud.region`, `cloud.availability_zone`) and per-process identity when `TRACEWAY_PROCESS_NAMES` is set (`process.pid`, `process.executable.name`, `process.command_line`, `process.owner`, which is what keeps the per-process series apart). See [Resource Attributes](/client/otel/metrics#resource-attributes) for the full allowlist.
-The retained metadata is what the [organization overview](/learn/organization-overview) shows beside each instance: OS, architecture, cloud region, and the host name when it differs from `TRACEWAY_SERVICE_NAME`. It is descriptive only. `server_name` remains the identity, so two hosts sharing a `TRACEWAY_SERVICE_NAME` still collapse into one instance no matter how different their metadata is.
+The retained metadata is what the [organization overview](/learn/organization-overview) shows beside each server: OS, architecture, cloud region, and the host name when it differs from `TRACEWAY_SERVICE_NAME`. It is descriptive only. `server_name` remains the identity, so two hosts sharing a `TRACEWAY_SERVICE_NAME` still collapse into one instance no matter how different their metadata is.
## What it opens
diff --git a/docs/pages/learn/projects.mdx b/docs/pages/learn/projects.mdx
index 40b49916..4ccd8459 100644
--- a/docs/pages/learn/projects.mdx
+++ b/docs/pages/learn/projects.mdx
@@ -27,7 +27,7 @@ There is no Gin, Django, Laravel, or Hono entry, because the language and web fr
## Organizations
-Projects live inside an **organization**, which is the boundary for everything that is not telemetry: members and roles, dashboards, teams, on-call schedules, escalation policies, and status pages. It is also what the [organization overview](/learn/organization-overview) summarizes, putting every instance, issue, monitor, and open page across all of the organization's projects on one screen.
+Projects live inside an **organization**, which is the boundary for everything that is not telemetry: members and roles, dashboards, teams, on-call schedules, escalation policies, and status pages. It is also what the [organization overview](/learn/organization-overview) summarizes, putting every server, issue, monitor, and open page across all of the organization's projects one sidebar click apart.
Split by project first. A second organization is right when two groups of projects should share no members, no dashboards, and no on-call rotation, an agency's separate clients for example. Splitting one fleet across organizations costs you the single view of it.
diff --git a/docs/public/organization-issues.png b/docs/public/organization-issues.png
index db20c63a..a6540d18 100644
Binary files a/docs/public/organization-issues.png and b/docs/public/organization-issues.png differ
diff --git a/docs/public/organization-monitors.png b/docs/public/organization-monitors.png
index 3dd4d1d9..12472fcb 100644
Binary files a/docs/public/organization-monitors.png and b/docs/public/organization-monitors.png differ
diff --git a/docs/public/organization-on-call.png b/docs/public/organization-on-call.png
new file mode 100644
index 00000000..8824b8e7
Binary files /dev/null and b/docs/public/organization-on-call.png differ
diff --git a/docs/public/organization-overview.png b/docs/public/organization-overview.png
index 3ce8ba33..fc2d409c 100644
Binary files a/docs/public/organization-overview.png and b/docs/public/organization-overview.png differ
diff --git a/docs/public/organization-projects.png b/docs/public/organization-projects.png
index 56208d2a..37b721f4 100644
Binary files a/docs/public/organization-projects.png and b/docs/public/organization-projects.png differ
diff --git a/docs/public/organization-switcher.png b/docs/public/organization-switcher.png
index d39802b9..25f75dce 100644
Binary files a/docs/public/organization-switcher.png and b/docs/public/organization-switcher.png differ
diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelte
index 5dc9805b..ec0f2d3e 100644
--- a/frontend/src/lib/components/app-sidebar.svelte
+++ b/frontend/src/lib/components/app-sidebar.svelte
@@ -3,6 +3,7 @@
import { useSidebar } from '$lib/components/ui/sidebar';
import { oncallState } from '$lib/state/oncall.svelte';
import { monitorsState } from '$lib/state/monitors.svelte';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
import {
Activity,
Bell,
@@ -13,9 +14,11 @@
FileText,
Film,
Flame,
+ FolderKanban,
Gauge,
ListEnd,
PhoneCall,
+ Server,
Settings,
BookOpen,
KeyRound
@@ -28,7 +31,8 @@
} from '$lib/state/projects.svelte';
import { LayoutDashboard } from '@lucide/svelte';
import { page } from '$app/state';
- import { createRowClickHandler } from '$lib/utils/navigation';
+ import { addStickyParamsToHref, createRowClickHandler } from '$lib/utils/navigation';
+ import { resolveHref } from '$lib/utils/links';
import { cn } from '$lib/utils';
interface SidebarItem {
@@ -38,6 +42,7 @@
stickyParams: string[];
adminOnly?: boolean;
external?: boolean;
+ exact?: boolean;
}
const hiddenForFrontend = new Set([
@@ -98,6 +103,44 @@
: allSidebarItems.filter((item) => !frontendOnly.has(item.title))
);
+ const allOrganizationItems: SidebarItem[] = [
+ {
+ Icon: Server,
+ href: '/organization',
+ title: 'Servers',
+ stickyParams: ['organizationId'],
+ exact: true
+ },
+ { Icon: Bug, href: '/organization/issues', title: 'Issues', stickyParams: ['organizationId'] },
+ {
+ Icon: Activity,
+ href: '/organization/monitors',
+ title: 'Monitors',
+ stickyParams: ['organizationId']
+ },
+ {
+ Icon: PhoneCall,
+ href: '/organization/on-call',
+ title: 'On-Call',
+ stickyParams: ['organizationId']
+ },
+ {
+ Icon: FolderKanban,
+ href: '/organization/projects',
+ title: 'Projects',
+ stickyParams: ['organizationId']
+ }
+ ];
+ const backendOnlyOrganizationItems = new Set(['Servers', 'Monitors']);
+
+ const organizationItems = $derived(
+ organizationContext.hasBackendProjects
+ ? allOrganizationItems
+ : allOrganizationItems.filter((item) => !backendOnlyOrganizationItems.has(item.title))
+ );
+
+ const items = $derived(organizationContext.active ? organizationItems : sidebarItems);
+
const allSidebarItemsBottom: SidebarItem[] = [
{ Icon: KeyRound, href: '/account', title: 'Account', stickyParams: [] },
{
@@ -114,10 +157,58 @@
allSidebarItemsBottom.filter((item) => !item.adminOnly || projectsState.canManageCurrentProject)
);
+ const organizationProjectParam = $derived.by(() => {
+ const project = organizationContext.projects[0];
+ return project ? `?projectId=${project.id}` : '';
+ });
+
+ const itemsBottom = $derived.by((): SidebarItem[] => {
+ if (!organizationContext.active) return sidebarItemsBottom;
+ return allSidebarItemsBottom
+ .filter((item) => !item.adminOnly || organizationContext.canManage)
+ .map((item) =>
+ item.external ? item : { ...item, href: item.href + organizationProjectParam }
+ );
+ });
+
const sidebar = useSidebar();
+ const homeItem = $derived(items[0]);
+ const homeHref = $derived.by(() => {
+ void page.url;
+ return homeItem ? addStickyParamsToHref(homeItem.href, ...homeItem.stickyParams) : '/';
+ });
+
+ function goHome(event: MouseEvent) {
+ event.preventDefault();
+ if (!homeItem) return;
+ sidebar.setOpenMobile(false);
+ createRowClickHandler(homeItem.href, ...homeItem.stickyParams)(event);
+ }
+
+ function isActive(item: SidebarItem): boolean {
+ if (page.url.pathname === item.href) return true;
+ if (item.exact) return false;
+ return page.url.pathname.startsWith(item.href + '/');
+ }
+
+ function badgeCount(item: SidebarItem): number {
+ if (item.title === 'Monitors') {
+ return organizationContext.active
+ ? organizationContext.downMonitorsCount
+ : monitorsState.downChecksCount;
+ }
+ if (item.title === 'On-Call') {
+ return organizationContext.active
+ ? organizationContext.openPagesCount
+ : oncallState.openPagesCount;
+ }
+ return 0;
+ }
+
// Synchronous read so the badge tracks project switches.
$effect(() => {
+ if (organizationContext.active) return;
const projectId = projectsState.currentProjectId;
if (!projectId) return;
const hasMonitors = sidebarItems.some((item) => item.title === 'Monitors');
@@ -130,6 +221,15 @@
return () => clearInterval(interval);
});
+ $effect(() => {
+ if (!organizationContext.active) return;
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null) return;
+ organizationContext.refreshCounts(organizationId);
+ const interval = setInterval(() => organizationContext.refreshCounts(organizationId), 60000);
+ return () => clearInterval(interval);
+ });
+
function navFlyoutProps(active: boolean) {
return {
sideOffset: 8,
@@ -146,35 +246,49 @@
<Sidebar.SidebarHeader
class="flex items-start overflow-hidden p-4 transition-[padding] duration-200 ease-linear group-data-[collapsible=icon]:items-center group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-2.5"
>
- {#if themeState.isDark}
- <img
- src="/traceway-logo-white.svg"
- alt="Traceway Logo"
- class="h-9 w-auto max-w-none shrink-0 group-data-[collapsible=icon]:hidden"
- />
- {:else}
+ <a
+ {...{ href: resolveHref(homeHref) }}
+ onclick={goHome}
+ aria-label={homeItem ? `Go to ${homeItem.title}` : 'Home'}
+ data-testid="sidebar-home"
+ class="flex shrink-0 rounded-md focus-visible:ring-2 focus-visible:ring-sidebar-ring focus-visible:outline-none"
+ >
+ {#if themeState.isDark}
+ <img
+ src="/traceway-logo-white.svg"
+ alt="Traceway Logo"
+ class="h-9 w-auto max-w-none shrink-0 group-data-[collapsible=icon]:hidden"
+ />
+ {:else}
+ <img
+ src="/traceway-logo.png"
+ alt="Traceway Logo"
+ class="h-9 w-auto max-w-none shrink-0 group-data-[collapsible=icon]:hidden"
+ />
+ {/if}
<img
- src="/traceway-logo.png"
+ src="/traceway-mark.png"
alt="Traceway Logo"
- class="h-9 w-auto max-w-none shrink-0 group-data-[collapsible=icon]:hidden"
+ class="mt-1 hidden size-9 shrink-0 object-contain group-data-[collapsible=icon]:block dark:invert"
/>
- {/if}
- <img
- src="/traceway-mark.png"
- alt="Traceway Logo"
- class="mt-1 hidden size-9 shrink-0 object-contain group-data-[collapsible=icon]:block dark:invert"
- />
+ </a>
</Sidebar.SidebarHeader>
<Sidebar.SidebarContent>
<Sidebar.SidebarGroup
class="p-4 pt-0 pb-0 transition-[padding] duration-200 ease-linear group-data-[collapsible=icon]:px-2.5 group-data-[collapsible=icon]:pt-2"
>
+ {#if organizationContext.active}
+ <Sidebar.SidebarGroupLabel
+ class="mb-1 text-[11px] font-semibold tracking-[0.14em] text-muted-foreground uppercase"
+ >
+ Organization
+ </Sidebar.SidebarGroupLabel>
+ {/if}
<Sidebar.SidebarGroupContent>
<Sidebar.SidebarMenu>
- {#each sidebarItems as sidebarItem, __index (__index)}
- {@const active =
- page.url.pathname === sidebarItem.href ||
- page.url.pathname.startsWith(sidebarItem.href + '/')}
+ {#each items as sidebarItem (sidebarItem.href)}
+ {@const active = isActive(sidebarItem)}
+ {@const badge = badgeCount(sidebarItem)}
<Sidebar.SidebarMenuItem>
<Sidebar.SidebarMenuButton
isActive={active}
@@ -188,18 +302,11 @@
<sidebarItem.Icon />
<span>{sidebarItem.title}</span>
</Sidebar.SidebarMenuButton>
- {#if sidebarItem.title === 'Monitors' && monitorsState.downChecksCount > 0}
- <Sidebar.MenuBadge
- class="rounded-full bg-destructive text-[10px] text-white peer-hover/menu-button:text-white peer-data-[active=true]/menu-button:text-white"
- >
- {monitorsState.downChecksCount}
- </Sidebar.MenuBadge>
- {/if}
- {#if sidebarItem.title === 'On-Call' && oncallState.openPagesCount > 0}
+ {#if badge > 0}
<Sidebar.MenuBadge
class="rounded-full bg-destructive text-[10px] text-white peer-hover/menu-button:text-white peer-data-[active=true]/menu-button:text-white"
>
- {oncallState.openPagesCount}
+ {badge}
</Sidebar.MenuBadge>
{/if}
</Sidebar.SidebarMenuItem>
@@ -208,7 +315,7 @@
</Sidebar.SidebarGroupContent>
</Sidebar.SidebarGroup>
- {#if sidebarItemsBottom.length}
+ {#if itemsBottom.length}
<div class="flex-1"></div>
<Sidebar.SidebarGroup
@@ -216,7 +323,7 @@
>
<Sidebar.SidebarGroupContent>
<Sidebar.SidebarMenu>
- {#each sidebarItemsBottom as sidebarItem, __index (__index)}
+ {#each itemsBottom as sidebarItem (sidebarItem.title)}
<Sidebar.SidebarMenuItem>
{#if sidebarItem.external}
<Sidebar.SidebarMenuButton
@@ -231,9 +338,7 @@
<span>{sidebarItem.title}</span>
</Sidebar.SidebarMenuButton>
{:else}
- {@const active =
- page.url.pathname === sidebarItem.href ||
- page.url.pathname.startsWith(sidebarItem.href + '/')}
+ {@const active = isActive(sidebarItem)}
<Sidebar.SidebarMenuButton
isActive={active}
tooltipContent={sidebarItem.title}
diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
index 38fc2fc9..611bc62b 100644
--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte
+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
@@ -409,6 +409,7 @@
<Select.Item value="max">max</Select.Item>
<Select.Item value="sum">sum</Select.Item>
<Select.Item value="count">count</Select.Item>
+ <Select.Item value="rate">rate</Select.Item>
</Select.Content>
</Select.Root>
</div>
@@ -419,6 +420,17 @@
class="h-8 text-xs"
/>
+ <label class="flex items-center gap-2 text-xs text-muted-foreground">
+ <Checkbox
+ checked={source.complement === true}
+ onCheckedChange={(checked) => {
+ sources[i].complement = checked === true ? true : undefined;
+ }}
+ aria-label="Invert value"
+ />
+ Invert: chart 1 &minus; value (turns CPU idle into CPU busy)
+ </label>
+
{#if source.name && getMetricTagKeys(source.name).length > 0}
<div class="space-y-1">
<span class="text-xs text-muted-foreground">Tag Filters</span>
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index 445ccab1..707aace8 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -93,6 +93,10 @@
let hiddenSeries = new SvelteSet<string>();
const visibleSeries = $derived(series.filter((s) => !hiddenSeries.has(s.key)));
+ function complementValue(value: number, unit: string): number {
+ return unit === '%' ? 100 - value : 1 - value;
+ }
+
function toggleSeries(key: string) {
if (hiddenSeries.has(key)) {
hiddenSeries.delete(key);
@@ -150,6 +154,7 @@
for (const [idx, result] of response.results.entries()) {
if (result.unit) units.add(result.unit);
const baseName = sources[idx]?.label?.trim() || result.name;
+ const complement = sources[idx]?.complement === true;
for (const [key, points] of Object.entries(result.series)) {
const label = Object.keys(result.series).length > 1 ? `${baseName} (${key})` : baseName;
let uniqueKey = label;
@@ -161,7 +166,7 @@
key: uniqueKey,
data: points.map((p) => ({
timestamp: new Date(p.timestamp),
- value: p.value
+ value: complement ? complementValue(p.value, result.unit) : p.value
})),
color: colors[colorIdx % colors.length]
});
diff --git a/frontend/src/lib/components/organization-project-switcher.svelte b/frontend/src/lib/components/organization-project-switcher.svelte
index 705ca29d..d1c330cd 100644
--- a/frontend/src/lib/components/organization-project-switcher.svelte
+++ b/frontend/src/lib/components/organization-project-switcher.svelte
@@ -1,8 +1,8 @@
<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 { organizationContext } from '$lib/state/organization-context.svelte';
import { projectsState, type Project } from '$lib/state/projects.svelte';
import { gotoHref } from '$lib/utils/navigation';
import FrameworkIcon from './framework-icon.svelte';
@@ -14,27 +14,6 @@
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,
@@ -70,7 +49,7 @@
<FrameworkIcon framework={project.framework} class="size-5 shrink-0" />
<span class="truncate">{project.name}</span>
</div>
- {#if !organizationContext && project.id === projectsState.currentProjectId}
+ {#if !organizationContext.active && project.id === projectsState.currentProjectId}
<Check class="size-4 shrink-0" />
{/if}
</DropdownMenu.Item>
@@ -81,9 +60,10 @@
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}
+ {#if organizationContext.active}
<Building2 class="size-5 shrink-0 text-muted-foreground" />
- <span class="truncate">{selectedOrganization?.name || 'Select organization'}</span>
+ <span class="truncate">{organizationContext.organization?.name || 'Select organization'}</span
+ >
{:else}
{#if projectsState.currentProject}
<FrameworkIcon framework={projectsState.currentProject.framework} class="size-6 shrink-0" />
@@ -109,7 +89,7 @@
<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}
+ {#if organizationContext.active && organizationContext.organizationId === group.organization.id}
<Check class="size-4 shrink-0" />
{/if}
</DropdownMenu.Item>
@@ -144,7 +124,7 @@
{/if}
<DropdownMenu.Separator />
- {#if !organizationContext && projectsState.canManageCurrentProject}
+ {#if !organizationContext.active && projectsState.canManageCurrentProject}
<DropdownMenu.Item onclick={onEditProject} class="cursor-pointer">
<Pencil class="size-4" />
Edit Project
diff --git a/frontend/src/lib/state/organization-context.svelte.ts b/frontend/src/lib/state/organization-context.svelte.ts
new file mode 100644
index 00000000..7a180e07
--- /dev/null
+++ b/frontend/src/lib/state/organization-context.svelte.ts
@@ -0,0 +1,62 @@
+import { page } from '$app/state';
+import { api } from '$lib/api';
+import { authState } from './auth.svelte';
+import { isBackendFramework, projectsState, type Project } from './projects.svelte';
+
+export function isOrganizationPath(pathname: string): boolean {
+ return pathname === '/organization' || pathname.startsWith('/organization/');
+}
+
+export function organizationHref(path: string, organizationId: number): string {
+ return `${path}?organizationId=${organizationId}`;
+}
+
+class OrganizationContext {
+ active = $derived(isOrganizationPath(page.url.pathname));
+
+ organizationId = $derived.by(() => {
+ if (!this.active) 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;
+ });
+
+ organization = $derived(
+ authState.organizations.find((organization) => organization.id === this.organizationId) ?? null
+ );
+
+ projects = $derived<Project[]>(
+ this.organizationId === null
+ ? []
+ : projectsState.projects.filter((project) => project.organizationId === this.organizationId)
+ );
+
+ hasBackendProjects = $derived(
+ this.projects.some((project) => isBackendFramework(project.framework))
+ );
+
+ canManage = $derived(
+ this.organizationId !== null && authState.canManageOrganization(this.organizationId)
+ );
+
+ openPagesCount = $state(0);
+ downMonitorsCount = $state(0);
+
+ async refreshCounts(organizationId: number) {
+ try {
+ const response = await api.get(`/organizations/${organizationId}/overview/counts`);
+ if (this.organizationId !== organizationId) return;
+ this.openPagesCount = response.openPagesCount ?? 0;
+ this.downMonitorsCount = response.downMonitorsCount ?? 0;
+ } catch {
+ return;
+ }
+ }
+}
+
+export const organizationContext = new OrganizationContext();
diff --git a/frontend/src/lib/types/dashboard.ts b/frontend/src/lib/types/dashboard.ts
index 5fe0d830..70d1b1eb 100644
--- a/frontend/src/lib/types/dashboard.ts
+++ b/frontend/src/lib/types/dashboard.ts
@@ -99,6 +99,7 @@ export type DashboardWidgetSource = {
tagFilters?: Record<string, string>;
groupBy?: string;
label?: string;
+ complement?: boolean;
};
export type DashboardWidgetConfig = {
diff --git a/frontend/src/lib/utils/metric-format.ts b/frontend/src/lib/utils/metric-format.ts
index d522bbad..0fee1185 100644
--- a/frontend/src/lib/utils/metric-format.ts
+++ b/frontend/src/lib/utils/metric-format.ts
@@ -1,6 +1,11 @@
type FormatResult = { text: string; unit: string };
export function formatMetricValue(value: number, unit: string): FormatResult {
+ if (unit.length > 2 && unit.endsWith('/s')) {
+ const base = formatMetricValue(value, unit.slice(0, -2));
+ return { text: base.text, unit: `${base.unit}/s` };
+ }
+
// OTel canonical unit '1' is a dimensionless ratio (0-1) - render as percent.
if (unit === '1') {
return formatMetricValue(value * 100, '%');
@@ -83,6 +88,11 @@ export function formatMetricLabel(value: number, unit: string): string {
type AxisScale = { divisor: number; unit: string };
export function getMetricAxisScale(maxValue: number, unit: string): AxisScale {
+ if (unit.length > 2 && unit.endsWith('/s')) {
+ const base = getMetricAxisScale(maxValue, unit.slice(0, -2));
+ return { divisor: base.divisor, unit: `${base.unit}/s` };
+ }
+
if (unit === '1') {
return { divisor: 0.01, unit: '%' };
}
diff --git a/frontend/src/lib/utils/time-range-state.svelte.ts b/frontend/src/lib/utils/time-range-state.svelte.ts
new file mode 100644
index 00000000..7ee91a13
--- /dev/null
+++ b/frontend/src/lib/utils/time-range-state.svelte.ts
@@ -0,0 +1,80 @@
+import { CalendarDate } from '@internationalized/date';
+import { getTimezone } from '$lib/state/timezone.svelte';
+import { calendarDateTimeToLuxon, toUTCISO } from './formatters';
+import {
+ dateToCalendarDate,
+ dateToTimeString,
+ getResolvedTimeRange,
+ getTimeRangeFromPreset,
+ parseTimeRangeFromUrl
+} from './url-params';
+
+export class TimeRangeState {
+ preset = $state<string | null>(null);
+ fromDate = $state<CalendarDate>(new CalendarDate(1970, 1, 1));
+ toDate = $state<CalendarDate>(new CalendarDate(1970, 1, 1));
+ fromTime = $state('00:00');
+ toTime = $state('00:00');
+
+ readonly defaultPreset: string;
+
+ constructor(defaultPreset: string) {
+ this.defaultPreset = defaultPreset;
+ this.readUrl();
+ }
+
+ readUrl() {
+ const timezone = getTimezone();
+ const params = parseTimeRangeFromUrl(timezone, this.defaultPreset);
+ const range = getResolvedTimeRange(params, timezone);
+ this.preset = params.preset;
+ this.setRange(range.from, range.to, timezone);
+ }
+
+ resolvePreset() {
+ if (!this.preset) return;
+ const timezone = getTimezone();
+ const range = getTimeRangeFromPreset(this.preset, timezone);
+ this.setRange(range.from, range.to, timezone);
+ }
+
+ apply(
+ from: { date: CalendarDate; time: string },
+ to: { date: CalendarDate; time: string },
+ preset: string | null
+ ) {
+ this.fromDate = from.date;
+ this.toDate = to.date;
+ this.fromTime = from.time;
+ this.toTime = to.time;
+ this.preset = preset;
+ }
+
+ fromUTC(): string {
+ return toUTCISO(this.toLuxon(this.fromDate, this.fromTime));
+ }
+
+ toUTC(): string {
+ return toUTCISO(this.toLuxon(this.toDate, this.toTime).endOf('minute'));
+ }
+
+ urlParams(): Record<string, string | null> {
+ if (this.preset) return { preset: this.preset, from: null, to: null };
+ return { preset: null, from: this.fromUTC(), to: this.toUTC() };
+ }
+
+ private setRange(from: Date, to: Date, timezone: string) {
+ this.fromDate = dateToCalendarDate(from, timezone);
+ this.toDate = dateToCalendarDate(to, timezone);
+ this.fromTime = dateToTimeString(from, timezone);
+ this.toTime = dateToTimeString(to, timezone);
+ }
+
+ private toLuxon(date: CalendarDate, time: string) {
+ const [hour, minute] = time.split(':').map(Number);
+ return calendarDateTimeToLuxon(
+ { year: date.year, month: date.month, day: date.day, hour, minute },
+ getTimezone()
+ );
+ }
+}
diff --git a/frontend/src/lib/utils/url-params.ts b/frontend/src/lib/utils/url-params.ts
index 54db9746..ca0193ba 100644
--- a/frontend/src/lib/utils/url-params.ts
+++ b/frontend/src/lib/utils/url-params.ts
@@ -93,9 +93,10 @@ export function updateUrl(
const { pushToHistory = false } = options;
const urlParams = new URLSearchParams();
- const currentProjectId = new URLSearchParams(window.location.search).get('projectId');
- if (currentProjectId) {
- urlParams.set('projectId', currentProjectId);
+ const current = new URLSearchParams(window.location.search);
+ for (const scope of ['projectId', 'organizationId']) {
+ const value = current.get(scope);
+ if (value) urlParams.set(scope, value);
}
for (const [key, value] of Object.entries(params)) {
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 9f7a76eb..b46ead66 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -13,6 +13,7 @@
import EditProjectModal from '$lib/components/edit-project-modal.svelte';
import DashboardCommand from '$lib/components/dashboard/dashboard-command.svelte';
import OrganizationProjectSwitcher from '$lib/components/organization-project-switcher.svelte';
+ import { isOrganizationPath, organizationContext } from '$lib/state/organization-context.svelte';
import * as Sidebar from '$lib/components/ui/sidebar';
import { Button } from '$lib/components/ui/button';
import { Sun, Moon, LogOut } from '@lucide/svelte';
@@ -54,25 +55,9 @@
let sidebarOpen = $state(localStorage.getItem(SIDEBAR_OPEN_KEY) !== 'false');
let CrossSiteNotificationBanner = $state<Component<{ organizationId: number }> | null>(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
+ organizationContext.active
+ ? organizationContext.organizationId
: (projectsState.currentProject?.organizationId ?? null)
);
const bannerOrganizationId = $derived(contextOrganizationId);
@@ -315,7 +300,7 @@
open={showAddProjectModal}
onOpenChange={(open) => (showAddProjectModal = open)}
onProjectCreated={handleProjectCreated}
- initialOrganizationId={organizationPage ? selectedOrganizationId : null}
+ initialOrganizationId={organizationContext.organizationId}
/>
<EditProjectModal
@@ -346,42 +331,6 @@
</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-[1200px] p-4 sm:p-6">
- {@render contextNotices()}
- {@render children()}
- </main>
- </div>
- {@render authenticatedOverlays()}
{:else if authState.isAuthenticated && !isPublicPath(page.url.pathname)}
<Sidebar.SidebarProvider
bind:open={sidebarOpen}
diff --git a/frontend/src/routes/organization/+layout.svelte b/frontend/src/routes/organization/+layout.svelte
new file mode 100644
index 00000000..d6c70d3b
--- /dev/null
+++ b/frontend/src/routes/organization/+layout.svelte
@@ -0,0 +1,74 @@
+<script lang="ts">
+ import { page } from '$app/state';
+ import { projectsState } from '$lib/state/projects.svelte';
+ import { organizationContext, organizationHref } from '$lib/state/organization-context.svelte';
+ import { gotoHref } from '$lib/utils/navigation';
+ import { LoadingCircle } from '$lib/components/ui/loading-circle';
+ import EmptyState from '$lib/components/traceway/empty-state.svelte';
+
+ let { children } = $props();
+
+ const LEGACY_TABS: Record<string, string> = {
+ overview: '/organization',
+ issues: '/organization/issues',
+ monitors: '/organization/monitors',
+ projects: '/organization/projects'
+ };
+
+ const BACKEND_ONLY_PATHS = new Set(['/organization', '/organization/monitors']);
+
+ const redirectHref = $derived.by(() => {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null || !projectsState.loaded) return null;
+ const projects = organizationContext.projects;
+ if (projects.length === 1) return `/?projectId=${projects[0].id}`;
+ const tab = page.url.searchParams.get('tab');
+ if (tab && LEGACY_TABS[tab]) return organizationHref(LEGACY_TABS[tab], organizationId);
+ if (
+ projects.length > 0 &&
+ !organizationContext.hasBackendProjects &&
+ BACKEND_ONLY_PATHS.has(page.url.pathname)
+ ) {
+ return organizationHref('/organization/issues', organizationId);
+ }
+ return null;
+ });
+
+ $effect(() => {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null || !projectsState.loaded) return;
+ if (redirectHref) {
+ gotoHref(redirectHref, { replaceState: true });
+ return;
+ }
+ const params = page.url.searchParams;
+ if (
+ params.get('organizationId') === String(organizationId) &&
+ !params.has('projectId') &&
+ !params.has('tab')
+ ) {
+ return;
+ }
+ const url = new URL(page.url);
+ url.searchParams.set('organizationId', String(organizationId));
+ url.searchParams.delete('projectId');
+ url.searchParams.delete('tab');
+ gotoHref(url.pathname + url.search, {
+ replaceState: true,
+ noScroll: true,
+ keepFocus: true
+ });
+ });
+</script>
+
+{#if !projectsState.loaded || redirectHref}
+ <div class="flex h-48 items-center justify-center">
+ <LoadingCircle size="xlg" />
+ </div>
+{:else if organizationContext.organizationId === null}
+ <EmptyState message="You are not a member of any organization yet." />
+{:else if organizationContext.projects.length === 0}
+ <EmptyState message="This organization has no projects yet." />
+{:else}
+ {@render children()}
+{/if}
diff --git a/frontend/src/routes/organization/+page.svelte b/frontend/src/routes/organization/+page.svelte
index 4bab7f63..0bf198ab 100644
--- a/frontend/src/routes/organization/+page.svelte
+++ b/frontend/src/routes/organization/+page.svelte
@@ -1,140 +1,660 @@
<script lang="ts">
- import { page } from '$app/state';
- import { authState } from '$lib/state/auth.svelte';
- import { isBackendFramework, projectsState } from '$lib/state/projects.svelte';
- import { setTabParam } from '$lib/utils/url-params';
- import { gotoHref } from '$lib/utils/navigation';
+ import { api } from '$lib/api';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
+ import { getErrorMessage } from '$lib/utils/errors';
+ import { formatRelativeTimeAgo } from '$lib/utils/formatters';
+ import { resolveHref } from '$lib/utils/links';
+ import { getServerColor } from '$lib/utils/server-colors';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import * as Select from '$lib/components/ui/select';
import { LoadingCircle } from '$lib/components/ui/loading-circle';
- 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 ALL_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.'
- };
+ 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 CountPill from './count-pill.svelte';
+ import PartialNotice from './partial-notice.svelte';
+ import {
+ ArrowDown,
+ ArrowRight,
+ ArrowUp,
+ Boxes,
+ Cloud,
+ RefreshCw,
+ Search,
+ Server,
+ TriangleAlert
+ } from '@lucide/svelte';
- const orgs = $derived(authState.organizations);
+ 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;
+ }
- 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;
- });
+ type ServerState = 'critical' | 'warning' | 'stale' | 'healthy';
+ type StateFilter = 'all' | ServerState;
+ type GroupMode = 'project' | 'cluster' | 'none';
+ type RefreshMode = 'initial' | 'background' | 'manual';
- const currentOrganizationName = $derived(
- orgs.find((o) => o.id === currentOrganizationId)?.name ?? ''
- );
+ const GROUP_LABELS: Record<GroupMode, string> = {
+ project: 'Group by project',
+ cluster: 'Group by Kubernetes cluster',
+ none: 'No grouping'
+ };
- const organizationProjects = $derived(
- currentOrganizationId === null
- ? []
- : projectsState.projects.filter((project) => project.organizationId === currentOrganizationId)
- );
+ interface ServerGroup {
+ key: string;
+ label: string;
+ subtitle: string;
+ servers: OrgServerRow[];
+ }
- const redirectHref = $derived.by(() => {
- if (currentOrganizationId === null) return null;
- if (organizationProjects.length === 1) return `/?projectId=${organizationProjects[0].id}`;
- return null;
- });
+ const FRESH_MS = 3 * 60 * 1000;
+ const REFRESH_MS = 60 * 1000;
- const hasBackendProjects = $derived(
- organizationProjects.some((project) => isBackendFramework(project.framework))
- );
+ const STATE_ORDER: ServerState[] = ['critical', 'stale', 'warning', 'healthy'];
+ const STATE_LABELS: Record<ServerState, string> = {
+ critical: 'critical',
+ stale: 'stale',
+ warning: 'warning',
+ healthy: 'healthy'
+ };
+ const STATE_DOT: Record<ServerState, string> = {
+ critical: 'bg-rose-500',
+ stale: 'bg-muted-foreground/50',
+ warning: 'bg-amber-500',
+ healthy: 'bg-emerald-500'
+ };
+ const STATE_BADGE: Record<ServerState, string> = {
+ critical: 'bg-rose-500/10 text-rose-600 ring-rose-500/20 dark:text-rose-400',
+ stale: 'bg-muted text-muted-foreground ring-border',
+ warning: 'bg-amber-500/10 text-amber-700 ring-amber-500/20 dark:text-amber-400',
+ healthy: 'bg-emerald-500/10 text-emerald-700 ring-emerald-500/20 dark:text-emerald-400'
+ };
- const tabs = $derived(
- hasBackendProjects ? ALL_TABS : ALL_TABS.filter((tab) => tab.value !== 'monitors')
- );
+ let servers = $state<OrgServerRow[]>([]);
+ let loading = $state(true);
+ let error = $state('');
+ let partial = $state(false);
+ let refreshedAt = $state<string | null>(null);
+ let refreshing = $state(false);
- const activeTab = $derived.by(() => {
- const tab = page.url.searchParams.get('tab') || 'overview';
- return tabs.some((t) => t.value === tab) ? tab : 'overview';
- });
+ let searchQuery = $state('');
+ let stateFilter = $state<StateFilter>('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(organizationId: number, mode: RefreshMode) {
+ const generation = ++loadGeneration;
+ if (mode === 'initial') loading = true;
+ if (mode === 'manual') refreshing = true;
+ error = '';
+ try {
+ const response = await api.get(`/organizations/${organizationId}/overview/servers`);
+ if (generation !== loadGeneration) return;
+ servers = response.servers || [];
+ partial = response.partial === true;
+ now = Date.now();
+ refreshedAt = new Date(now).toISOString();
+ } catch (e) {
+ if (generation !== loadGeneration) return;
+ error = getErrorMessage(e) || 'Failed to load servers';
+ } finally {
+ if (generation === loadGeneration) {
+ loading = false;
+ refreshing = false;
+ }
+ }
+ }
- function setTab(tab: string) {
- setTabParam(tab);
+ function refresh(mode: RefreshMode) {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId !== null) void loadServers(organizationId, mode);
}
$effect(() => {
- if (!projectsState.loaded) return;
- const tab = page.url.searchParams.get('tab');
- if (tab && !tabs.some((t) => t.value === tab)) {
- setTabParam('overview');
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null) return;
+ if (activeOrganizationId !== organizationId) {
+ activeOrganizationId = organizationId;
+ servers = [];
+ partial = false;
+ refreshedAt = null;
+ searchQuery = '';
+ stateFilter = 'all';
+ projectFilter = 'all';
+ groupMode = 'project';
+ groupPreferenceInitializedFor = null;
}
+ void loadServers(organizationId, 'initial');
+ const timer = window.setInterval(
+ () => void loadServers(organizationId, 'background'),
+ REFRESH_MS
+ );
+ return () => window.clearInterval(timer);
});
- $effect(() => {
- const organizationId = currentOrganizationId;
- if (organizationId === null) return;
- if (projectsState.loaded && redirectHref) {
- gotoHref(redirectHref, { replaceState: true });
- return;
+ 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 serverState(server: OrgServerRow): ServerState {
+ if (!isFresh(server)) return 'stale';
+ if (
+ atLeast(server.cpuPct, 95) ||
+ atLeast(server.memoryPct, 95) ||
+ atLeast(server.diskPct, 90)
+ ) {
+ return 'critical';
}
if (
- page.url.searchParams.get('organizationId') === String(organizationId) &&
- !page.url.searchParams.has('projectId')
+ atLeast(server.cpuPct, 80) ||
+ atLeast(server.memoryPct, 85) ||
+ atLeast(server.diskPct, 80)
) {
- return;
+ return 'warning';
+ }
+ return 'healthy';
+ }
+
+ function stateRank(state: ServerState): number {
+ return STATE_ORDER.indexOf(state);
+ }
+
+ const stateCounts = $derived.by(() => {
+ const counts: Record<ServerState, number> = { critical: 0, stale: 0, warning: 0, healthy: 0 };
+ for (const server of servers) counts[serverState(server)]++;
+ return counts;
+ });
+ const attentionCount = $derived(servers.length - stateCounts.healthy);
+ const allServerNames = $derived(servers.map((server) => server.serverName));
+ const hasKubernetesMetadata = $derived(servers.some((server) => !!server.k8sClusterName));
+ const projectOptions = $derived.by(() => {
+ const byProject = new Map(
+ servers.map((server) => [
+ server.projectId,
+ { id: server.projectId, name: server.projectName }
+ ])
+ );
+ return [...byProject.values()].sort((a, b) => a.name.localeCompare(b.name));
+ });
+
+ $effect(() => {
+ if (loading || groupPreferenceInitializedFor === organizationContext.organizationId) return;
+ groupMode = hasKubernetesMetadata ? 'cluster' : 'project';
+ groupPreferenceInitializedFor = organizationContext.organizationId;
+ });
+
+ const visibleServers = $derived.by(() => {
+ const query = searchQuery.trim().toLowerCase();
+ return servers
+ .filter((server) => {
+ const state = serverState(server);
+ if (projectFilter !== 'all' && server.projectId !== projectFilter) return false;
+ if (stateFilter !== 'all' && state !== stateFilter) 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(serverState(a)) - stateRank(serverState(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 servers', subtitle: '', servers: visibleServers }];
}
- 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
+
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
+ 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);
});
});
+
+ const filtersActive = $derived(
+ searchQuery.trim() !== '' || stateFilter !== 'all' || projectFilter !== 'all'
+ );
+
+ const headline = $derived.by(() => {
+ if (attentionCount === 0) {
+ return servers.length === 1 ? 'The only server is healthy' : 'All servers are healthy';
+ }
+ const verb = attentionCount === 1 ? 'needs' : 'need';
+ return `${attentionCount} of ${servers.length} servers ${verb} attention`;
+ });
+
+ function toggleStateFilter(state: ServerState) {
+ stateFilter = stateFilter === state ? 'all' : state;
+ }
+
+ function clearFilters() {
+ searchQuery = '';
+ stateFilter = 'all';
+ projectFilter = 'all';
+ }
+
+ const projectFilterLabel = $derived(
+ projectOptions.find((project) => project.id === projectFilter)?.name ?? 'All projects'
+ );
+
+ 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 serverHref(server: OrgServerRow): string {
+ const params = new URLSearchParams({
+ projectId: server.projectId,
+ server: server.serverName,
+ preset: '30m',
+ ...(server.dashboardId ? { dashboard: String(server.dashboardId) } : {})
+ });
+ return `/dashboards?${params.toString()}`;
+ }
+
+ function osLabel(server: OrgServerRow): string {
+ const type = server.osType.trim();
+ if (!type) return '';
+ return type.charAt(0).toUpperCase() + type.slice(1);
+ }
</script>
-{#if !projectsState.loaded || redirectHref}
- <div class="flex h-48 items-center justify-center">
- <LoadingCircle size="xlg" />
- </div>
-{:else}
- <div class="space-y-4">
- <PageHeader
- title={currentOrganizationName || 'Organization'}
- description={hasBackendProjects
- ? 'Live instance health, active response, and telemetry across every project.'
- : 'Issues and active response across every project.'}
+<div class="space-y-5">
+ <PageHeader
+ title="Servers"
+ description="CPU, memory, disk, and network for every server that reported in the last 30 minutes, across all projects."
+ >
+ {#snippet trailing()}
+ {#if !loading}
+ <CountPill count={servers.length} />
+ {/if}
+ {/snippet}
+ {#snippet actions()}
+ <div class="flex items-center gap-3">
+ {#if refreshedAt}
+ <span class="text-xs text-muted-foreground">
+ Updated {formatRelativeTimeAgo(refreshedAt)}
+ </span>
+ {/if}
+ <Button variant="outline" size="sm" disabled={refreshing} onclick={() => refresh('manual')}>
+ <RefreshCw class="size-4 {refreshing ? 'animate-spin' : ''}" />
+ Refresh
+ </Button>
+ </div>
+ {/snippet}
+ </PageHeader>
+
+ {#if servers.length > 0}
+ <section aria-label="Fleet health" class="space-y-2.5">
+ <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <p class="flex items-center gap-2 text-sm font-medium">
+ <span
+ class="size-2 shrink-0 rounded-full {attentionCount > 0
+ ? 'bg-amber-500'
+ : 'bg-emerald-500'}"
+ ></span>
+ {headline}
+ </p>
+ <div
+ class="flex flex-wrap gap-1.5"
+ role="group"
+ aria-label="Filter servers by health state"
+ >
+ {#each STATE_ORDER as state (state)}
+ {@const count = stateCounts[state]}
+ <button
+ type="button"
+ aria-pressed={stateFilter === state}
+ disabled={count === 0 && stateFilter !== state}
+ onclick={() => toggleStateFilter(state)}
+ class="inline-flex items-center gap-1.5 rounded-full border bg-background px-2.5 py-1 text-xs font-medium tabular-nums transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:opacity-40 disabled:hover:bg-background aria-pressed:border-foreground aria-pressed:bg-foreground aria-pressed:text-background aria-pressed:hover:bg-foreground"
+ >
+ <span class="size-2 rounded-full {STATE_DOT[state]}"></span>
+ {count}
+ {STATE_LABELS[state]}
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="flex h-2 w-full gap-0.5 overflow-hidden rounded-full bg-muted" aria-hidden="true">
+ {#each STATE_ORDER as state (state)}
+ {#if stateCounts[state] > 0}
+ <div
+ class="h-full transition-[flex] duration-300 motion-reduce:transition-none {STATE_DOT[
+ state
+ ]}"
+ style="flex: {stateCounts[state]} 1 0%"
+ ></div>
+ {/if}
+ {/each}
+ </div>
+ </section>
+
+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <div class="relative min-w-0 sm:w-64">
+ <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 a server" class="h-9 pl-9" />
+ </div>
+ {#if projectOptions.length > 1}
+ <Select.Root type="single" bind:value={projectFilter}>
+ <Select.Trigger class="h-9 w-full sm:w-48" aria-label="Filter servers by project">
+ <span class="truncate">{projectFilterLabel}</span>
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="all" label="All projects">All projects</Select.Item>
+ {#each projectOptions as project (project.id)}
+ <Select.Item value={project.id} label={project.name}>{project.name}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {/if}
+ <Select.Root
+ type="single"
+ value={groupMode}
+ onValueChange={(value) => (groupMode = value as GroupMode)}
+ >
+ <Select.Trigger class="h-9 w-full sm:w-auto" aria-label="Group servers">
+ {GROUP_LABELS[groupMode]}
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="project" label={GROUP_LABELS.project}
+ >{GROUP_LABELS.project}</Select.Item
+ >
+ {#if hasKubernetesMetadata}
+ <Select.Item value="cluster" label={GROUP_LABELS.cluster}
+ >{GROUP_LABELS.cluster}</Select.Item
+ >
+ {/if}
+ <Select.Item value="none" label={GROUP_LABELS.none}>{GROUP_LABELS.none}</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ {#if filtersActive}
+ <span class="text-sm text-muted-foreground tabular-nums sm:ml-auto">
+ Showing {visibleServers.length} of {servers.length}
+ </span>
+ {/if}
+ </div>
+ {/if}
+
+ {#if partial || (error && servers.length > 0)}
+ <PartialNotice
+ message={partial
+ ? 'Some projects could not be read. The servers shown are still current.'
+ : 'The last refresh failed. Showing the most recent snapshot.'}
/>
+ {/if}
+
+ {#if loading && servers.length === 0}
+ <div class="flex h-48 items-center justify-center rounded-xl border">
+ <LoadingCircle size="lg" />
+ </div>
+ {:else if error && 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">Servers could not be loaded</p>
+ <p class="mt-1 text-sm text-muted-foreground">{error}</p>
+ </div>
+ <Button variant="outline" size="sm" onclick={() => refresh('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 servers reported 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 servers match these filters</p>
+ <button class="mt-2 text-sm font-medium text-primary hover:underline" onclick={clearFilters}>
+ 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>Server</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 = serverState(server)}
+ <a
+ {...{ href: resolveHref(serverHref(server)) }}
+ class="group/server 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_DOT[
+ state
+ ]}"
+ ></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 capitalize ring-1 ring-inset {STATE_BADGE[
+ state
+ ]}">{STATE_LABELS[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)}{server.hostArch ? ` · ${server.hostArch}` : ''}</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>
- <PageTabs {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 organizationProjects.length === 0}
- <EmptyState message="This organization has no projects yet." />
- {:else if activeTab === 'overview'}
- <OverviewTab organizationId={currentOrganizationId} {hasBackendProjects} />
- {:else if activeTab === 'issues'}
- <IssuesTab organizationId={currentOrganizationId} />
- {:else if activeTab === 'monitors'}
- <MonitorsTab organizationId={currentOrganizationId} />
- {:else if activeTab === 'projects'}
- <ProjectsTab organizationId={currentOrganizationId} />
- {/if}
- </div>
-{/if}
+ <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/server:translate-x-0.5 group-hover/server:text-foreground lg:block"
+ />
+ </a>
+ {/each}
+ {/each}
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/routes/organization/count-pill.svelte b/frontend/src/routes/organization/count-pill.svelte
new file mode 100644
index 00000000..e348cea0
--- /dev/null
+++ b/frontend/src/routes/organization/count-pill.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ interface Props {
+ count: number;
+ label?: string;
+ tone?: 'default' | 'danger';
+ }
+
+ let { count, label = '', tone = 'default' }: Props = $props();
+</script>
+
+<span
+ class="mt-1 rounded-full px-2 py-0.5 font-mono text-xs tabular-nums {tone === 'danger'
+ ? 'bg-rose-500/10 font-semibold text-rose-600 dark:text-rose-400'
+ : 'bg-muted text-muted-foreground'}"
+>
+ {count.toLocaleString()}{label ? ` ${label}` : ''}
+</span>
diff --git a/frontend/src/routes/organization/issues-tab.svelte b/frontend/src/routes/organization/issues-tab.svelte
deleted file mode 100644
index 09375317..00000000
--- a/frontend/src/routes/organization/issues-tab.svelte
+++ /dev/null
@@ -1,143 +0,0 @@
-<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 PartialNotice from './partial-notice.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 partial = $state(false);
- let loading = $state(true);
- let error = $state('');
- let loadGeneration = 0;
-
- function loadIssues(orgId: number) {
- const generation = ++loadGeneration;
- loading = true;
- error = '';
- partial = false;
- api
- .get(`/organizations/${orgId}/overview/issues`)
- .then((response) => {
- if (generation !== loadGeneration) return;
- issues = response.issues || [];
- totalGroups = response.totalGroups || 0;
- partial = response.partial === true;
- })
- .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 partial}
- <PartialNotice />
- {/if}
-
- {#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/issues/+page.svelte b/frontend/src/routes/organization/issues/+page.svelte
new file mode 100644
index 00000000..638cfdcf
--- /dev/null
+++ b/frontend/src/routes/organization/issues/+page.svelte
@@ -0,0 +1,337 @@
+<script lang="ts">
+ import { onDestroy, onMount, untrack } from 'svelte';
+ import { browser } from '$app/environment';
+ import { api } from '$lib/api';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
+ import { getTimezone } from '$lib/state/timezone.svelte';
+ import * as Table from '$lib/components/ui/table';
+ import { SearchBar } from '$lib/components/ui/search-bar';
+ import { LoadingCircle } from '$lib/components/ui/loading-circle';
+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';
+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';
+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';
+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
+ import IssueTrendChart from '$lib/components/issue-trend-chart.svelte';
+ import PageHeader from '$lib/components/traceway/page-header.svelte';
+ import TableContainer from '$lib/components/traceway/table-container.svelte';
+ import CountPill from '../count-pill.svelte';
+ import PartialNotice from '../partial-notice.svelte';
+ import { getErrorMessage } from '$lib/utils/errors';
+ import { formatDateTime } from '$lib/utils/formatters';
+ import { createRowClickHandler } from '$lib/utils/navigation';
+ import { TimeRangeState } from '$lib/utils/time-range-state.svelte';
+ import { updateUrl } from '$lib/utils/url-params';
+ import {
+ getSortState,
+ setSortState,
+ handleSortClick,
+ type SortDirection
+ } from '$lib/utils/sort-storage';
+
+ interface OrgIssueRow {
+ exceptionHash: string;
+ stackTrace: string;
+ lastSeen: string;
+ firstSeen: string;
+ count: number;
+ hourlyTrend: { timestamp: string; count: number }[];
+ projectId: string;
+ projectName: string;
+ }
+
+ const timezone = $derived(getTimezone());
+ const range = new TimeRangeState('24h');
+
+ const SORT_STORAGE_KEY = 'org-issues';
+ const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'last_seen', direction: 'desc' });
+ let sortField = $state(initialSort.field);
+ let sortDirection = $state<SortDirection>(initialSort.direction);
+
+ const searchTypeOptions = [
+ { value: 'all', label: 'All' },
+ { value: 'issues', label: 'Issues' },
+ { value: 'messages', label: 'Messages' }
+ ];
+
+ function readSearchParams() {
+ if (!browser) return { search: '', searchType: 'all' };
+ const params = new URLSearchParams(window.location.search);
+ return {
+ search: params.get('search') || '',
+ searchType: params.get('searchType') || 'all'
+ };
+ }
+
+ const initialSearch = readSearchParams();
+ let searchQuery = $state(initialSearch.search);
+ let searchType = $state(initialSearch.searchType);
+
+ let issues = $state<OrgIssueRow[]>([]);
+ let loading = $state(true);
+ let error = $state('');
+ let partial = $state(false);
+ let page = $state(1);
+ let pageSize = $state(20);
+ let total = $state(0);
+ let totalPages = $state(0);
+ let loadGeneration = 0;
+ let activeOrganizationId: number | null = null;
+
+ function syncUrl(pushToHistory: boolean) {
+ updateUrl(
+ {
+ ...range.urlParams(),
+ search: searchQuery.trim() || null,
+ searchType: searchType !== 'all' ? searchType : null
+ },
+ { pushToHistory }
+ );
+ }
+
+ async function loadData(pushToHistory = true) {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null) return;
+ const generation = ++loadGeneration;
+ loading = true;
+ error = '';
+ range.resolvePreset();
+ syncUrl(pushToHistory);
+ try {
+ const orderBy = sortDirection === 'asc' ? `${sortField}_asc` : sortField;
+ const response = await api.post(`/organizations/${organizationId}/overview/issues`, {
+ fromDate: range.fromUTC(),
+ toDate: range.toUTC(),
+ orderBy,
+ pagination: { page, pageSize },
+ search: searchQuery.trim(),
+ searchType
+ });
+ if (generation !== loadGeneration) return;
+ issues = response.data || [];
+ total = response.pagination?.total || 0;
+ totalPages = response.pagination?.totalPages || 0;
+ partial = response.partial === true;
+ } catch (e) {
+ if (generation !== loadGeneration) return;
+ error = getErrorMessage(e) || 'Failed to load issues';
+ } finally {
+ if (generation === loadGeneration) loading = false;
+ }
+ }
+
+ function handlePageChange(newPage: number) {
+ if (newPage >= 1 && newPage <= totalPages) {
+ page = newPage;
+ loadData(true);
+ }
+ }
+
+ function handlePageSizeChange(newPageSize: number) {
+ pageSize = newPageSize;
+ page = 1;
+ loadData(true);
+ }
+
+ function handleTimeRangeChange(
+ from: Parameters<TimeRangeState['apply']>[0],
+ to: Parameters<TimeRangeState['apply']>[1],
+ preset: string | null
+ ) {
+ range.apply(from, to, preset);
+ page = 1;
+ loadData(true);
+ }
+
+ function handleSearch() {
+ page = 1;
+ loadData(true);
+ }
+
+ function handleSort(field: string) {
+ const newSort = handleSortClick(field, sortField, sortDirection);
+ sortField = newSort.field;
+ sortDirection = newSort.direction;
+ setSortState(SORT_STORAGE_KEY, newSort);
+ page = 1;
+ loadData(true);
+ }
+
+ function handlePopState() {
+ range.readUrl();
+ const params = readSearchParams();
+ searchQuery = params.search;
+ searchType = params.searchType;
+ page = 1;
+ loadData(false);
+ }
+
+ $effect(() => {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null || organizationId === activeOrganizationId) return;
+ activeOrganizationId = organizationId;
+ untrack(() => {
+ page = 1;
+ loadData(false);
+ });
+ });
+
+ onMount(() => {
+ window.addEventListener('popstate', handlePopState);
+ });
+
+ onDestroy(() => {
+ if (typeof window !== 'undefined') {
+ window.removeEventListener('popstate', handlePopState);
+ }
+ });
+
+ 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>
+
+<div class="space-y-4">
+ <PageHeader
+ title="Issues"
+ description="Issues from every project in the selected range, with the project each belongs to."
+ >
+ {#snippet trailing()}
+ {#if !loading && !error}
+ <CountPill count={total} />
+ {/if}
+ {/snippet}
+ {#snippet actions()}
+ <TimeRangePicker
+ bind:fromDate={range.fromDate}
+ bind:toDate={range.toDate}
+ bind:fromTime={range.fromTime}
+ bind:toTime={range.toTime}
+ bind:preset={range.preset}
+ onApply={handleTimeRangeChange}
+ />
+ {/snippet}
+ </PageHeader>
+
+ <SearchBar
+ placeholder="Search issues..."
+ bind:value={searchQuery}
+ bind:typeValue={searchType}
+ typeOptions={searchTypeOptions}
+ onSearch={handleSearch}
+ disabled={loading}
+ />
+
+ {#if partial}
+ <PartialNotice />
+ {/if}
+
+ <TableContainer minWidth="880px">
+ <Table.Root>
+ {#if loading}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={5} class="h-48">
+ <div class="flex h-full items-center justify-center">
+ <LoadingCircle size="xlg" />
+ </div>
+ </Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if error}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={5} class="h-24 text-center text-red-500">{error}</Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if issues.length === 0}
+ <Table.Body>
+ <TableEmptyState colspan={5} message="No issues found in the selected range." />
+ </Table.Body>
+ {:else}
+ <Table.Header>
+ <Table.Row>
+ <TracewayTableHeader
+ label="Issue"
+ tooltip="The error message or exception that occurred"
+ />
+ <TracewayTableHeader label="Project" class="w-[180px]" />
+ <TracewayTableHeader
+ label="Trend"
+ tooltip="Hourly occurrence pattern over the last 24h"
+ class="w-[190px]"
+ />
+ <TracewayTableHeader
+ label="Events"
+ tooltip="Total number of times this issue occurred in the selected range"
+ align="right"
+ class="w-[90px]"
+ sortField="count"
+ currentSortField={sortField}
+ {sortDirection}
+ onSort={handleSort}
+ />
+ <TracewayTableHeader
+ label="Last seen"
+ tooltip="When this issue last occurred"
+ class="w-[180px]"
+ sortField="last_seen"
+ currentSortField={sortField}
+ {sortDirection}
+ onSort={handleSort}
+ />
+ </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>
+ <IssueTrendChart trend={issue.hourlyTrend || []} />
+ </Table.Cell>
+ <Table.Cell class="text-right text-[15px] font-semibold tabular-nums">
+ {issue.count.toLocaleString()}
+ </Table.Cell>
+ <Table.Cell class="text-muted-foreground tabular-nums">
+ {formatDateTime(issue.lastSeen, { timezone })}
+ </Table.Cell>
+ </Table.Row>
+ {/each}
+ </Table.Body>
+ {/if}
+ </Table.Root>
+ </TableContainer>
+
+ <PaginationFooter
+ currentPage={page}
+ {totalPages}
+ {pageSize}
+ totalItems={total}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ {loading}
+ itemLabel="issue"
+ />
+</div>
diff --git a/frontend/src/routes/organization/monitors-tab.svelte b/frontend/src/routes/organization/monitors/+page.svelte
similarity index 53%
rename from frontend/src/routes/organization/monitors-tab.svelte
rename to frontend/src/routes/organization/monitors/+page.svelte
index 24f05fc5..5bcbb53c 100644
--- a/frontend/src/routes/organization/monitors-tab.svelte
+++ b/frontend/src/routes/organization/monitors/+page.svelte
@@ -1,19 +1,29 @@
<script lang="ts">
- import { SvelteMap } from 'svelte/reactivity';
+ import { onDestroy, onMount, untrack } from 'svelte';
+ import { browser } from '$app/environment';
import { api } from '$lib/api';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
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 { TimeRangeState } from '$lib/utils/time-range-state.svelte';
+ import { updateUrl } from '$lib/utils/url-params';
import * as Table from '$lib/components/ui/table';
+ import { Badge } from '$lib/components/ui/badge';
import { LoadingCircle } from '$lib/components/ui/loading-circle';
+ import { SearchBar } from '$lib/components/ui/search-bar';
import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';
- import { Badge } from '$lib/components/ui/badge';
+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';
+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';
+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
+ import PageHeader from '$lib/components/traceway/page-header.svelte';
import TableContainer from '$lib/components/traceway/table-container.svelte';
import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';
- import PartialNotice from './partial-notice.svelte';
import CheckStatusBadge from '$lib/components/synthetics/check-status-badge.svelte';
import MonitorTypeBadge from '$lib/components/synthetics/monitor-type-badge.svelte';
+ import CountPill from '../count-pill.svelte';
+ import PartialNotice from '../partial-notice.svelte';
import {
incidentDisplayTitle,
type CheckOverview,
@@ -30,9 +40,30 @@
projectName: string;
}
- type SortField = 'name' | 'project' | 'status' | 'uptime' | 'latency';
+ type SortField = 'name' | 'project' | 'status' | 'uptime' | 'latency' | 'last_run';
+
+ const typeOptions = [
+ { value: '', label: 'All types' },
+ { value: 'http', label: 'HTTP' },
+ { value: 'tcp', label: 'TCP' },
+ { value: 'browser', label: 'Browser' }
+ ];
+
+ function readParams() {
+ if (!browser) return { search: '', incidentSearch: '' };
+ const params = new URLSearchParams(window.location.search);
+ return {
+ search: params.get('search') || '',
+ incidentSearch: params.get('incidentSearch') || ''
+ };
+ }
- let { organizationId }: { organizationId: number } = $props();
+ const initialParams = readParams();
+ let searchQuery = $state(initialParams.search);
+ let typeFilter = $state('');
+ let incidentSearch = $state(initialParams.incidentSearch);
+
+ const range = new TimeRangeState('3M');
let checks = $state<OrgMonitorRow[]>([]);
let checksLoading = $state(true);
@@ -43,6 +74,10 @@
let incidents = $state<OrgIncident[]>([]);
let incidentsLoading = $state(true);
let incidentsError = $state('');
+ let incidentsPage = $state(1);
+ let incidentsPageSize = $state(20);
+ let incidentsTotal = $state(0);
+ let incidentsTotalPages = $state(0);
let incidentsGeneration = 0;
let activeOrganizationId: number | null = null;
@@ -51,12 +86,24 @@
let orderBy = $state<SortField>(initialSort.field as SortField);
let sortDirection = $state<SortDirection>(initialSort.direction);
- async function loadChecks(orgId: number, generation: number) {
+ function syncUrl(pushToHistory: boolean) {
+ updateUrl(
+ {
+ ...range.urlParams(),
+ search: searchQuery.trim() || null,
+ incidentSearch: incidentSearch.trim() || null
+ },
+ { pushToHistory }
+ );
+ }
+
+ async function loadChecks(organizationId: number) {
+ const generation = ++checksGeneration;
checksLoading = true;
checksError = '';
checksPartial = false;
try {
- const response = await api.get(`/organizations/${orgId}/overview/monitors`);
+ const response = await api.get(`/organizations/${organizationId}/overview/monitors`);
if (generation !== checksGeneration) return;
checks = response.checks || [];
checksPartial = response.partial === true;
@@ -68,13 +115,23 @@
}
}
- async function loadIncidents(orgId: number, generation: number) {
+ async function loadIncidents(organizationId: number, pushToHistory: boolean) {
+ const generation = ++incidentsGeneration;
incidentsLoading = true;
incidentsError = '';
+ range.resolvePreset();
+ syncUrl(pushToHistory);
try {
- const response = await api.get(`/organizations/${orgId}/incidents`);
+ const response = await api.post(`/organizations/${organizationId}/overview/incidents`, {
+ search: incidentSearch.trim(),
+ fromDate: range.fromUTC(),
+ toDate: range.toUTC(),
+ pagination: { page: incidentsPage, pageSize: incidentsPageSize }
+ });
if (generation !== incidentsGeneration) return;
- incidents = response.incidents || [];
+ incidents = response.data || [];
+ incidentsTotal = response.pagination?.total || 0;
+ incidentsTotalPages = response.pagination?.totalPages || 0;
} catch (e) {
if (generation !== incidentsGeneration) return;
incidentsError = getErrorMessage(e) || 'Failed to load incidents';
@@ -83,27 +140,78 @@
}
}
- $effect(() => {
- const orgId = organizationId;
- if (activeOrganizationId !== orgId) {
- activeOrganizationId = orgId;
- checks = [];
- checksError = '';
- incidents = [];
- incidentsError = '';
- }
- loadChecks(orgId, ++checksGeneration);
- loadIncidents(orgId, ++incidentsGeneration);
- });
+ function reloadIncidents(pushToHistory: boolean) {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId !== null) void loadIncidents(organizationId, pushToHistory);
+ }
function retryChecks() {
- loadChecks(organizationId, ++checksGeneration);
+ const organizationId = organizationContext.organizationId;
+ if (organizationId !== null) void loadChecks(organizationId);
+ }
+
+ function handleSearch() {
+ syncUrl(true);
+ }
+
+ function handleIncidentSearch() {
+ incidentsPage = 1;
+ reloadIncidents(true);
+ }
+
+ function handleTimeRangeChange(
+ from: Parameters<TimeRangeState['apply']>[0],
+ to: Parameters<TimeRangeState['apply']>[1],
+ preset: string | null
+ ) {
+ range.apply(from, to, preset);
+ incidentsPage = 1;
+ reloadIncidents(true);
}
- function retryIncidents() {
- loadIncidents(organizationId, ++incidentsGeneration);
+ function handleIncidentsPageChange(newPage: number) {
+ if (newPage >= 1 && newPage <= incidentsTotalPages) {
+ incidentsPage = newPage;
+ reloadIncidents(true);
+ }
+ }
+
+ function handleIncidentsPageSizeChange(newSize: number) {
+ incidentsPageSize = newSize;
+ incidentsPage = 1;
+ reloadIncidents(true);
+ }
+
+ function handlePopState() {
+ range.readUrl();
+ const params = readParams();
+ searchQuery = params.search;
+ incidentSearch = params.incidentSearch;
+ incidentsPage = 1;
+ reloadIncidents(false);
}
+ $effect(() => {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null || organizationId === activeOrganizationId) return;
+ activeOrganizationId = organizationId;
+ untrack(() => {
+ incidentsPage = 1;
+ void loadChecks(organizationId);
+ void loadIncidents(organizationId, false);
+ });
+ });
+
+ onMount(() => {
+ window.addEventListener('popstate', handlePopState);
+ });
+
+ onDestroy(() => {
+ if (typeof window !== 'undefined') {
+ window.removeEventListener('popstate', handlePopState);
+ }
+ });
+
function handleSort(field: SortField) {
const newSort = handleSortClick(field, orderBy, sortDirection);
orderBy = newSort.field as SortField;
@@ -119,23 +227,29 @@
return (agg.up / measured) * 100;
}
+ function target(check: OrgMonitorRow): string {
+ if (check.checkType === 'http')
+ return `${check.config?.method || 'GET'} ${check.config?.url ?? ''}`;
+ if (check.checkType === 'tcp') return `${check.config?.host ?? ''}:${check.config?.port ?? ''}`;
+ return 'Playwright script';
+ }
+
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 downCount = $derived(
+ checks.filter((check) => check.enabled && check.currentStatus === 'down').length
+ );
- const sortedChecks = $derived.by(() => {
+ const visibleChecks = $derived.by(() => {
+ const query = searchQuery.trim().toLowerCase();
+ let filtered = typeFilter ? checks.filter((c) => c.checkType === typeFilter) : checks;
+ if (query) {
+ filtered = filtered.filter((c) =>
+ [c.name, c.projectName, c.checkType, target(c)].join(' ').toLowerCase().includes(query)
+ );
+ }
const direction = sortDirection === 'asc' ? 1 : -1;
- return [...checks].sort((a, b) => {
+ return [...filtered].sort((a, b) => {
switch (orderBy) {
case 'project':
return direction * a.projectName.localeCompare(b.projectName);
@@ -150,6 +264,11 @@
return (
direction * ((a.aggregates?.avgLatencyMs ?? -1) - (b.aggregates?.avgLatencyMs ?? -1))
);
+ case 'last_run': {
+ const timeA = a.lastRunAt ? new Date(a.lastRunAt).getTime() : 0;
+ const timeB = b.lastRunAt ? new Date(b.lastRunAt).getTime() : 0;
+ return direction * (timeA - timeB);
+ }
default:
return direction * a.name.localeCompare(b.name);
}
@@ -157,8 +276,31 @@
});
</script>
-<div class="space-y-6">
- <section class="space-y-3">
+<div class="space-y-8">
+ <section class="space-y-4">
+ <PageHeader
+ title="Monitors"
+ description="Every monitor in the organization with its current status, 30-day uptime, and average latency."
+ >
+ {#snippet trailing()}
+ {#if !checksLoading && !checksError}
+ <CountPill count={checks.length} />
+ {#if downCount > 0}
+ <CountPill count={downCount} label="down" tone="danger" />
+ {/if}
+ {/if}
+ {/snippet}
+ </PageHeader>
+
+ <SearchBar
+ placeholder="Search monitors..."
+ bind:value={searchQuery}
+ bind:typeValue={typeFilter}
+ {typeOptions}
+ onSearch={handleSearch}
+ disabled={checksLoading}
+ />
+
{#if checksPartial}
<PartialNotice />
{/if}
@@ -172,6 +314,10 @@
<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 if visibleChecks.length === 0}
+ <div class="rounded-md border py-16 text-center text-sm text-muted-foreground">
+ No monitors match the search.
+ </div>
{:else}
<TableContainer minWidth="920px">
<Table.Root>
@@ -220,13 +366,20 @@
onSort={(field) => handleSort(field as SortField)}
class="w-[120px]"
/>
- <TracewayTableHeader label="Last incident" class="w-[160px]" align="right" />
+ <TracewayTableHeader
+ label="Last run"
+ sortField="last_run"
+ currentSortField={orderBy}
+ {sortDirection}
+ onSort={(field) => handleSort(field as SortField)}
+ class="w-[130px]"
+ align="right"
+ />
</Table.Row>
</Table.Header>
<Table.Body>
- {#each sortedChecks as check (check.id)}
+ {#each visibleChecks as check (check.id)}
{@const uptime = uptimePct(check)}
- {@const lastIncident = lastIncidentByCheck.get(check.id)}
<Table.Row
class="cursor-pointer"
onclick={createRowClickHandler(
@@ -238,14 +391,7 @@
<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}
+ {target(check)}
</div>
</Table.Cell>
<Table.Cell>
@@ -284,15 +430,7 @@
: '—'}
</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}
+ {check.lastRunAt ? formatRelativeTimeAgo(check.lastRunAt) : 'never'}
</Table.Cell>
</Table.Row>
{/each}
@@ -302,21 +440,67 @@
{/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" />
+ <section class="space-y-4">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
+ <div>
+ <div class="flex items-center gap-2">
+ <h2 class="text-lg font-semibold">Incidents</h2>
+ {#if !incidentsLoading && !incidentsError}
+ <CountPill count={incidentsTotal} />
+ {/if}
+ </div>
+ <p class="mt-0.5 text-sm text-muted-foreground">
+ Across monitors and status pages, for incidents open at any point in the selected range.
+ </p>
</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>
+ <TimeRangePicker
+ bind:fromDate={range.fromDate}
+ bind:toDate={range.toDate}
+ bind:fromTime={range.fromTime}
+ bind:toTime={range.toTime}
+ bind:preset={range.preset}
+ onApply={handleTimeRangeChange}
+ />
+ </div>
+
+ <SearchBar
+ placeholder="Search incidents by title, monitor, or status page..."
+ bind:value={incidentSearch}
+ onSearch={handleIncidentSearch}
+ disabled={incidentsLoading}
+ />
+
+ <TableContainer minWidth="720px">
+ <Table.Root>
+ {#if incidentsLoading}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={4} class="h-32">
+ <div class="flex h-full items-center justify-center">
+ <LoadingCircle size="lg" />
+ </div>
+ </Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if incidentsError}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={4} class="h-32">
+ <div class="flex h-full flex-col items-center justify-center gap-3">
+ <p class="text-sm text-destructive">{incidentsError}</p>
+ <button
+ class="text-sm font-medium text-primary hover:underline"
+ onclick={() => reloadIncidents(false)}>Retry</button
+ >
+ </div>
+ </Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if incidents.length === 0}
+ <Table.Body>
+ <TableEmptyState colspan={4} message="No incidents in the selected range." />
+ </Table.Body>
+ {:else}
<Table.Header>
<Table.Row>
<TracewayTableHeader label="Incident" />
@@ -365,8 +549,19 @@
</Table.Row>
{/each}
</Table.Body>
- </Table.Root>
- </TableContainer>
- {/if}
+ {/if}
+ </Table.Root>
+ </TableContainer>
+
+ <PaginationFooter
+ currentPage={incidentsPage}
+ totalPages={incidentsTotalPages}
+ pageSize={incidentsPageSize}
+ totalItems={incidentsTotal}
+ onPageChange={handleIncidentsPageChange}
+ onPageSizeChange={handleIncidentsPageSizeChange}
+ loading={incidentsLoading}
+ itemLabel="incident"
+ />
</section>
</div>
diff --git a/frontend/src/routes/organization/on-call/+page.svelte b/frontend/src/routes/organization/on-call/+page.svelte
new file mode 100644
index 00000000..8ad2cffc
--- /dev/null
+++ b/frontend/src/routes/organization/on-call/+page.svelte
@@ -0,0 +1,317 @@
+<script lang="ts">
+ import { onDestroy, onMount, untrack } from 'svelte';
+ import { browser } from '$app/environment';
+ import { api } from '$lib/api';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
+ import type { OncallPage } from '$lib/state/oncall.svelte';
+ import { getErrorMessage } from '$lib/utils/errors';
+ import { formatDateTime, formatRelativeTimeAgo } from '$lib/utils/formatters';
+ import { createRowClickHandler } from '$lib/utils/navigation';
+ import { TimeRangeState } from '$lib/utils/time-range-state.svelte';
+ import { updateUrl } from '$lib/utils/url-params';
+ import * as Table from '$lib/components/ui/table';
+ import { Button } from '$lib/components/ui/button';
+ import { SearchBar } from '$lib/components/ui/search-bar';
+ import { LoadingCircle } from '$lib/components/ui/loading-circle';
+ import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';
+ import { TableEmptyState } from '$lib/components/ui/table-empty-state';
+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';
+ import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
+ import PageHeader from '$lib/components/traceway/page-header.svelte';
+ import TableContainer from '$lib/components/traceway/table-container.svelte';
+ import PageBadges from '$lib/components/traceway/page-badges.svelte';
+ import CountPill from '../count-pill.svelte';
+
+ interface OrgPageRow extends OncallPage {
+ projectName: string;
+ }
+
+ const REFRESH_MS = 60 * 1000;
+
+ const statusFilters = [
+ { value: 'active', label: 'All active' },
+ { value: 'open', label: 'Open' },
+ { value: 'acknowledged', label: 'Acknowledged' },
+ { value: 'resolved', label: 'Resolved' }
+ ];
+ const statusValues = new Set(statusFilters.map((filter) => filter.value));
+
+ const emptyMessages: Record<string, string> = {
+ active: 'No active pages opened in the selected range. All quiet.',
+ open: 'No open pages in the selected range.',
+ acknowledged: 'No acknowledged pages in the selected range.',
+ resolved: 'No resolved pages in the selected range.'
+ };
+
+ const range = new TimeRangeState('1M');
+
+ function readParams() {
+ if (!browser) return { status: 'active', search: '' };
+ const params = new URLSearchParams(window.location.search);
+ const status = params.get('status') || 'active';
+ return {
+ status: statusValues.has(status) ? status : 'active',
+ search: params.get('search') || ''
+ };
+ }
+
+ const initialParams = readParams();
+ let statusFilter = $state(initialParams.status);
+ let searchQuery = $state(initialParams.search);
+
+ let pages = $state<OrgPageRow[]>([]);
+ let openPagesCount = $state(0);
+ let loading = $state(true);
+ let error = $state('');
+ let currentPage = $state(1);
+ let pageSize = $state(25);
+ let total = $state(0);
+ let totalPages = $state(0);
+ let loadGeneration = 0;
+ let activeOrganizationId: number | null = null;
+
+ function syncUrl(pushToHistory: boolean) {
+ updateUrl(
+ {
+ ...range.urlParams(),
+ status: statusFilter !== 'active' ? statusFilter : null,
+ search: searchQuery.trim() || null
+ },
+ { pushToHistory }
+ );
+ }
+
+ async function loadPages(pushToHistory: boolean, background = false) {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null) return;
+ const generation = ++loadGeneration;
+ if (!background) loading = true;
+ error = '';
+ range.resolvePreset();
+ syncUrl(pushToHistory);
+ try {
+ const response = await api.post(`/organizations/${organizationId}/overview/pages`, {
+ status: statusFilter,
+ search: searchQuery.trim(),
+ fromDate: range.fromUTC(),
+ toDate: range.toUTC(),
+ pagination: { page: currentPage, pageSize }
+ });
+ if (generation !== loadGeneration) return;
+ pages = response.data || [];
+ total = response.pagination?.total || 0;
+ totalPages = response.pagination?.totalPages || 0;
+ openPagesCount = response.openPagesCount || 0;
+ } catch (e) {
+ if (generation !== loadGeneration) return;
+ error = getErrorMessage(e) || 'Failed to load on-call pages';
+ } finally {
+ if (generation === loadGeneration) loading = false;
+ }
+ }
+
+ function setFilter(value: string) {
+ statusFilter = value;
+ currentPage = 1;
+ loadPages(true);
+ }
+
+ function handleSearch() {
+ currentPage = 1;
+ loadPages(true);
+ }
+
+ function handleTimeRangeChange(
+ from: Parameters<TimeRangeState['apply']>[0],
+ to: Parameters<TimeRangeState['apply']>[1],
+ preset: string | null
+ ) {
+ range.apply(from, to, preset);
+ currentPage = 1;
+ loadPages(true);
+ }
+
+ function handlePageChange(newPage: number) {
+ if (newPage >= 1 && newPage <= totalPages) {
+ currentPage = newPage;
+ loadPages(true);
+ }
+ }
+
+ function handlePageSizeChange(newSize: number) {
+ pageSize = newSize;
+ currentPage = 1;
+ loadPages(true);
+ }
+
+ function handlePopState() {
+ range.readUrl();
+ const params = readParams();
+ statusFilter = params.status;
+ searchQuery = params.search;
+ currentPage = 1;
+ loadPages(false);
+ }
+
+ $effect(() => {
+ const organizationId = organizationContext.organizationId;
+ if (organizationId === null) return;
+ if (organizationId !== activeOrganizationId) {
+ activeOrganizationId = organizationId;
+ untrack(() => {
+ currentPage = 1;
+ loadPages(false);
+ });
+ }
+ const timer = window.setInterval(() => void loadPages(false, true), REFRESH_MS);
+ return () => window.clearInterval(timer);
+ });
+
+ onMount(() => {
+ window.addEventListener('popstate', handlePopState);
+ });
+
+ onDestroy(() => {
+ if (typeof window !== 'undefined') {
+ window.removeEventListener('popstate', handlePopState);
+ }
+ });
+</script>
+
+<div class="space-y-4">
+ <PageHeader
+ title="On-Call"
+ description="Pages from every project, filtered by when they were opened. Acknowledged pages stay active until they are resolved."
+ >
+ {#snippet trailing()}
+ {#if !loading && !error}
+ <CountPill count={total} />
+ {#if openPagesCount > 0}
+ <CountPill count={openPagesCount} label="open" tone="danger" />
+ {/if}
+ {/if}
+ {/snippet}
+ {#snippet actions()}
+ <TimeRangePicker
+ bind:fromDate={range.fromDate}
+ bind:toDate={range.toDate}
+ bind:fromTime={range.fromTime}
+ bind:toTime={range.toTime}
+ bind:preset={range.preset}
+ onApply={handleTimeRangeChange}
+ />
+ {/snippet}
+ </PageHeader>
+
+ <SearchBar
+ placeholder="Search pages by subject or rule..."
+ bind:value={searchQuery}
+ onSearch={handleSearch}
+ disabled={loading}
+ />
+
+ <div class="flex flex-wrap items-center gap-2">
+ {#each statusFilters as filter (filter.value)}
+ <Button
+ size="sm"
+ variant={statusFilter === filter.value ? 'default' : 'outline'}
+ class="rounded-full"
+ onclick={() => setFilter(filter.value)}
+ >
+ {filter.label}
+ </Button>
+ {/each}
+ </div>
+
+ <TableContainer minWidth="820px">
+ <Table.Root>
+ {#if loading}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={5} class="h-48">
+ <div class="flex h-full items-center justify-center">
+ <LoadingCircle size="xlg" />
+ </div>
+ </Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if error}
+ <Table.Body>
+ <Table.Row>
+ <Table.Cell colspan={5} class="h-48">
+ <div class="flex h-full flex-col items-center justify-center gap-3">
+ <p class="text-sm text-destructive">{error}</p>
+ <Button variant="outline" size="sm" onclick={() => loadPages(false)}>Retry</Button>
+ </div>
+ </Table.Cell>
+ </Table.Row>
+ </Table.Body>
+ {:else if pages.length === 0}
+ <Table.Body>
+ <TableEmptyState colspan={5} message={emptyMessages[statusFilter]} />
+ </Table.Body>
+ {:else}
+ <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-[170px]" 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"
+ title={formatDateTime(oncallPage.createdAt)}
+ >
+ {formatRelativeTimeAgo(oncallPage.createdAt)}
+ </Table.Cell>
+ </Table.Row>
+ {/each}
+ </Table.Body>
+ {/if}
+ </Table.Root>
+ </TableContainer>
+
+ <PaginationFooter
+ {currentPage}
+ {totalPages}
+ {pageSize}
+ totalItems={total}
+ onPageChange={handlePageChange}
+ onPageSizeChange={handlePageSizeChange}
+ {loading}
+ itemLabel="page"
+ />
+</div>
diff --git a/frontend/src/routes/organization/overview-tab.svelte b/frontend/src/routes/organization/overview-tab.svelte
deleted file mode 100644
index eed5ddee..00000000
--- a/frontend/src/routes/organization/overview-tab.svelte
+++ /dev/null
@@ -1,944 +0,0 @@
-<script lang="ts">
- import { resolveHref } from '$lib/utils/links';
- 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 PartialNotice from './partial-notice.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,
- hasBackendProjects
- }: { organizationId: number; hasBackendProjects: boolean } = $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
- ): Promise<boolean> {
- if (!background) serversLoading = true;
- serversError = '';
- try {
- const response = await api.get(`/organizations/${orgId}/overview/servers`);
- if (generation !== loadGeneration) return false;
- servers = response.servers || [];
- serversPartial = response.partial === true;
- now = Date.now();
- return true;
- } catch (e) {
- if (generation !== loadGeneration) return false;
- serversError = getErrorMessage(e) || 'Failed to load instance health';
- return false;
- } finally {
- if (generation === loadGeneration) serversLoading = false;
- }
- }
-
- async function loadIssues(
- orgId: number,
- generation: number,
- background: boolean
- ): Promise<boolean> {
- if (!background) issuesLoading = true;
- issuesError = '';
- try {
- const response = await api.get(`/organizations/${orgId}/overview/issues`);
- if (generation !== loadGeneration) return false;
- totalGroups = response.totalGroups || 0;
- return true;
- } catch (e) {
- if (generation !== loadGeneration) return false;
- issuesError = getErrorMessage(e) || 'Failed to load issues';
- return false;
- } finally {
- if (generation === loadGeneration) issuesLoading = false;
- }
- }
-
- async function loadPages(
- orgId: number,
- generation: number,
- background: boolean
- ): Promise<boolean> {
- if (!background) pagesLoading = true;
- pagesError = '';
- try {
- const response = await api.get(`/organizations/${orgId}/overview/pages`);
- if (generation !== loadGeneration) return false;
- pages = response.pages || [];
- openPagesCount = response.openPagesCount || 0;
- downMonitorsCount = response.downMonitorsCount || 0;
- return true;
- } catch (e) {
- if (generation !== loadGeneration) return false;
- pagesError = getErrorMessage(e) || 'Failed to load on-call pages';
- return false;
- } finally {
- if (generation === loadGeneration) pagesLoading = false;
- }
- }
-
- type RefreshMode = 'initial' | 'background' | 'manual';
-
- async function refreshOverview(orgId: number, mode: RefreshMode, includeServers: boolean) {
- const generation = ++loadGeneration;
- const background = mode !== 'initial';
- if (mode === 'manual') refreshing = true;
- const loads = [
- loadIssues(orgId, generation, background),
- loadPages(orgId, generation, background)
- ];
- if (includeServers) {
- loads.push(loadServers(orgId, generation, background));
- } else {
- servers = [];
- serversLoading = false;
- }
- const succeeded = await Promise.all(loads);
- if (generation !== loadGeneration) return;
- refreshing = false;
- if (succeeded.some(Boolean)) refreshedAt = new Date().toISOString();
- }
-
- $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;
- }
- const includeServers = hasBackendProjects;
- void refreshOverview(orgId, 'initial', includeServers);
- const timer = window.setInterval(
- () => void refreshOverview(orgId, 'background', includeServers),
- 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 byProject = new Map(
- servers.map((server) => [
- server.projectId,
- { id: server.projectId, name: server.projectName }
- ])
- );
- return [...byProject.values()].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 }];
- }
-
- // Scratch map: never escapes this derived, only the sorted array of its values is returned.
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
- 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',
- ...(server.dashboardId ? { dashboard: String(server.dashboardId) } : {})
- });
- return `/dashboards?${params.toString()}`;
- }
-
- function organizationTabHref(tab: string): string {
- return `/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 pulseAttention = $derived(hasBackendProjects ? attentionCount > 0 : openPagesCount > 0);
-
- const pulseHeadline = $derived.by(() => {
- if (!hasBackendProjects) {
- if (pagesLoading && pages.length === 0) return 'Checking active response';
- if (pagesError && pages.length === 0) return 'Response signal unavailable';
- if (openPagesCount > 0) {
- return `${openPagesCount} ${openPagesCount === 1 ? 'page needs' : 'pages need'} a response`;
- }
- return 'Nobody is being paged';
- }
- 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 {pulseAttention
- ? 'bg-amber-500/10 text-amber-600 dark:text-amber-400'
- : 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'}"
- >
- {#if pulseAttention}
- <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">
- {pulseHeadline}
- </h2>
- <p class="mt-1 text-sm text-muted-foreground">
- {#if refreshedAt}
- Updated {formatRelativeTimeAgo(refreshedAt)} · refreshes every minute
- {:else if hasBackendProjects}
- Live resource health across every project
- {:else}
- Issues and on-call response across every project
- {/if}
- </p>
- </div>
- </div>
- <Button
- variant="outline"
- size="sm"
- disabled={refreshing}
- onclick={() => void refreshOverview(organizationId, 'manual', hasBackendProjects)}
- >
- <RefreshCw class="size-4 {refreshing ? 'animate-spin' : ''}" />
- Refresh
- </Button>
- </div>
-
- <div
- class="grid grid-cols-2 border-t {hasBackendProjects ? 'sm:grid-cols-3 xl:grid-cols-6' : ''}"
- >
- {#if hasBackendProjects}
- <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>
- {/if}
- <a
- {...{ href: resolveHref(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>
- {#if hasBackendProjects}
- <a
- {...{ href: resolveHref(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>
- {:else}
- <a
- href="#pages-heading"
- 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 > 0
- ? 'text-rose-600 dark:text-rose-400'
- : ''}"
- >
- {pagesLoading || pagesError ? '—' : openPagesCount}
- </div>
- </a>
- {/if}
- </div>
- </section>
-
- {#if hasBackendProjects}
- <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)}
- <PartialNotice
- message={serversPartial
- ? 'Some projects could not be read. The instances shown are still current.'
- : 'The last refresh failed. Showing the most recent snapshot.'}
- />
- {/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', hasBackendProjects)}
- >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: resolveHref(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>
- {/if}
-
- <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/+page.svelte
similarity index 77%
rename from frontend/src/routes/organization/projects-tab.svelte
rename to frontend/src/routes/organization/projects/+page.svelte
index 034fd621..26dc5beb 100644
--- a/frontend/src/routes/organization/projects-tab.svelte
+++ b/frontend/src/routes/organization/projects/+page.svelte
@@ -4,20 +4,24 @@
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 PageHeader from '$lib/components/traceway/page-header.svelte';
import TableContainer from '$lib/components/traceway/table-container.svelte';
+ import CountPill from '../count-pill.svelte';
import { authState } from '$lib/state/auth.svelte';
- import { getFrameworkLabel, projectsState, type Project } from '$lib/state/projects.svelte';
+ import { organizationContext } from '$lib/state/organization-context.svelte';
+ import { getFrameworkLabel, 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)
- );
+ const projects = $derived(organizationContext.projects);
function projectRole(project: Project): string {
- return project.role || authState.getRoleForOrganization(organizationId) || 'user';
+ const organizationId = organizationContext.organizationId;
+ return (
+ project.role ||
+ (organizationId === null ? null : authState.getRoleForOrganization(organizationId)) ||
+ 'user'
+ );
}
function roleLabel(role: string): string {
@@ -34,14 +38,15 @@
}
</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>
+<div class="space-y-4">
+ <PageHeader
+ title="Projects"
+ description="Every project in the organization, with its framework and your effective access level."
+ >
+ {#snippet trailing()}
+ <CountPill count={projects.length} />
+ {/snippet}
+ </PageHeader>
{#if projects.length === 0}
<div class="rounded-md border py-16 text-center text-sm text-muted-foreground">
@@ -93,4 +98,4 @@
</Table.Root>
</TableContainer>
{/if}
-</section>
+</div>