Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(dashboard): add 1d range to workspace Usage tab (#2837)
Jiayuan Zhang8d30d76300ad
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex 6c81fe316c..65eefc62b7 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -58,11 +58,17 @@ import {// Period selector — mirrors the runtime detail page so users see the same// option set across both dashboards. `dims` declares which dimensions each-// range is allowed in: 7d at the weekly grain is one bar, 180d at the daily-// grain is 180 unreadable bars, so each end of the range belongs to a single-// dimension. Switching dimensions resets `days` if the current value isn't-// in the new dimension's allowed set (see `handleDimChange` below).+// range is allowed in: 1d / 7d at the weekly grain collapse to a single bar,+// 180d at the daily grain is 180 unreadable bars, so each end of the range+// belongs to a single dimension. Switching dimensions resets `days` if the+// current value isn't in the new dimension's allowed set (see+// `handleDimChange` below).+//+// 1d semantic: "today" (the natural calendar day from 00:00 in UTC, matching+// the rollup's bucket_date axis), not "the last 24 hours". The client-side+// `dailyCutoffIso` filter below enforces this even at the midnight edge.const TIME_RANGES = [+ { label: "1d", days: 1, dims: ["daily"] as const },{ label: "7d", days: 7, dims: ["daily"] as const },{ label: "30d", days: 30, dims: ["daily", "weekly"] as const },{ label: "90d", days: 90, dims: ["daily", "weekly"] as const },@@ -209,24 +215,20 @@ export function DashboardPage() {// trend chart) re-scope to the user-selected `days` even when we// over-fetched for the weekly chart. UTC matches the bucket_date the// backend filters on, so the cutoff lands on the same calendar boundary- // the rollup used.+ // the rollup used. Applied in both dims so 1d strictly means "today" even+ // at the midnight UTC edge where the server's wall-clock cutoff would+ // otherwise include yesterday.const dailyCutoffIso = useMemo(() => addDaysIso(todayIso(WEEK_TZ), -(days - 1)),[days],);const dailyUsageInWindow = useMemo(- () =>- dim === "weekly"- ? dailyUsage.filter((u) => u.date >= dailyCutoffIso)- : dailyUsage,- [dailyUsage, dim, dailyCutoffIso],+ () => dailyUsage.filter((u) => u.date >= dailyCutoffIso),+ [dailyUsage, dailyCutoffIso],);const runTimeDailyInWindow = useMemo(- () =>- dim === "weekly"- ? runTimeDailyRows.filter((r) => r.date >= dailyCutoffIso)- : runTimeDailyRows,- [runTimeDailyRows, dim, dailyCutoffIso],+ () => runTimeDailyRows.filter((r) => r.date >= dailyCutoffIso),+ [runTimeDailyRows, dailyCutoffIso],);const isLoading =diff --git a/server/internal/handler/parse_since_param_test.go b/server/internal/handler/parse_since_param_test.gonew file mode 100644index 0000000000..0015de38fa--- /dev/null+++ b/server/internal/handler/parse_since_param_test.go@@ -0,0 +1,48 @@+package handler++import (+ "net/http/httptest"+ "testing"+ "time"+)++// TestParseSinceParam locks in the natural-calendar-day semantic that the+// workspace dashboard's `1d` / `7d` / `30d` / `90d` selectors depend on:+//+// - `days=N` returns UTC start-of-today minus (N-1) full days, so the+// window covers N calendar days (today + N-1 prior).+// - `days=1` therefore means "today only" — not the trailing 24h that the+// previous wall-clock implementation produced (which leaked yesterday+// into the pre-aggregated `byAgent` / `runTime` endpoints).+func TestParseSinceParam(t *testing.T) {+ now := time.Now().UTC()+ startOfToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)++ cases := []struct {+ name string+ path string+ want time.Time+ }{+ {name: "default (no days)", path: "/x", want: startOfToday.AddDate(0, 0, -29)}, // defaultDays=30+ {name: "1d = today only", path: "/x?days=1", want: startOfToday}, // critical: PR 2837 fix+ {name: "7d", path: "/x?days=7", want: startOfToday.AddDate(0, 0, -6)},+ {name: "30d", path: "/x?days=30", want: startOfToday.AddDate(0, 0, -29)},+ {name: "90d", path: "/x?days=90", want: startOfToday.AddDate(0, 0, -89)},+ {name: "invalid falls back to default", path: "/x?days=abc", want: startOfToday.AddDate(0, 0, -29)},+ {name: "zero falls back to default", path: "/x?days=0", want: startOfToday.AddDate(0, 0, -29)},+ {name: "over cap falls back to default", path: "/x?days=400", want: startOfToday.AddDate(0, 0, -29)},+ }+ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest("GET", tc.path, nil)+ got := parseSinceParam(req, 30)+ if !got.Valid {+ t.Fatalf("expected Valid timestamptz, got invalid")+ }+ if !got.Time.Equal(tc.want) {+ t.Errorf("days param in %q: got %s, want %s", tc.path, got.Time.Format(time.RFC3339), tc.want.Format(time.RFC3339))+ }+ })+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex ae2a68f161..3f358c7543 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -398,10 +398,16 @@ func (h *Handler) GetWorkspaceUsageSummary(w http.ResponseWriter, r *http.RequeswriteJSON(w, http.StatusOK, resp)}-// parseSinceParam parses the "days" query parameter and returns a timestamptz.-// Wall-clock window relative to UTC. Use parseSinceParamInTZ when the cutoff-// must align with a per-runtime calendar boundary (so `days=N` returns N-// full local days under the runtime's tz instead of N×24h sliding window).+// parseSinceParam parses the "days" query parameter and returns a timestamptz+// anchored to UTC start-of-today, so `days=N` represents N natural calendar+// days under UTC (today plus N-1 prior full days). `days=1` therefore means+// "today only" — matching the workspace dashboard's `dailyCutoffIso` axis —+// rather than the trailing 24-hour window the wall-clock cutoff used to+// return. The downstream SQL all applies `DATE_TRUNC('day', @since)` so the+// pre-truncated value below lands on the same boundary regardless.+//+// Use parseSinceParamInTZ when the cutoff must align with a per-runtime+// timezone instead of UTC (runtime-detail pages).func parseSinceParam(r *http.Request, defaultDays int) pgtype.Timestamptz {days := defaultDaysif d := r.URL.Query().Get("days"); d != "" {@@ -409,8 +415,10 @@ func parseSinceParam(r *http.Request, defaultDays int) pgtype.Timestamptz {days = parsed}}- t := time.Now().AddDate(0, 0, -days)- return pgtype.Timestamptz{Time: t, Valid: true}+ now := time.Now().UTC()+ startOfToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)+ cutoff := startOfToday.AddDate(0, 0, -(days - 1))+ return pgtype.Timestamptz{Time: cutoff, Valid: true}}// parseSinceParamInTZ is the timezone-aware variant of parseSinceParam.diff --git a/server/internal/handler/usage_test.go b/server/internal/handler/usage_test.goindex caa10b4185..6b96f96cd6 100644--- a/server/internal/handler/usage_test.go+++ b/server/internal/handler/usage_test.go@@ -12,8 +12,9 @@ import (// TestWorkspaceUsage_BucketsByUsageTime mirrors the runtime usage test for// the workspace-level aggregations: a task that queues one calendar day and// reports usage the next must attribute to the day tokens were produced, and-// `?days=N` must cover the full earliest day, not a rolling window starting-// at "now minus N days".+// `?days=N` must cover N full calendar days anchored at UTC start-of-today+// (so `days=2` covers today + yesterday), not a rolling window starting at+// "now minus N days".func TestWorkspaceUsage_BucketsByUsageTime(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -73,9 +74,12 @@ func TestWorkspaceUsage_BucketsByUsageTime(t *testing.T) {insertTaskWithUsage(yesterdayLate, todayEarly, 1000) // cross-midnightinsertTaskWithUsage(yesterdayMorning, yesterdayMorning, 2000) // full-day yesterday- // /api/usage/daily — daily breakdown.+ // /api/usage/daily — daily breakdown. `days=2` covers today + yesterday+ // (the two buckets we just populated). Under the old rolling-window+ // semantics this would have been `days=1` and still incidentally included+ // both buckets via DATE_TRUNC; that was the bug Emacs flagged on PR 2837.w := httptest.NewRecorder()- req := newRequest("GET", "/api/usage/daily?days=1", nil)+ req := newRequest("GET", "/api/usage/daily?days=2", nil)testHandler.GetWorkspaceUsageByDay(w, req)if w.Code != http.StatusOK {t.Fatalf("GetWorkspaceUsageByDay: expected 200, got %d: %s", w.Code, w.Body.String())@@ -107,7 +111,7 @@ func TestWorkspaceUsage_BucketsByUsageTime(t *testing.T) {// be included; if the cutoff were a rolling window, yesterday morning's// 2000 would be missing depending on time of day.w = httptest.NewRecorder()- req = newRequest("GET", "/api/usage/summary?days=1", nil)+ req = newRequest("GET", "/api/usage/summary?days=2", nil)testHandler.GetWorkspaceUsageSummary(w, req)if w.Code != http.StatusOK {t.Fatalf("GetWorkspaceUsageSummary: expected 200, got %d: %s", w.Code, w.Body.String())