Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(runtime): per-runtime timezone for token-usage aggregation (MUL-1950) (#2394)

Multica Eved6349c16eca7
diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.ts
index 62369c67a3..83730042d5 100644
--- a/packages/core/agents/derive-presence.test.ts
+++ b/packages/core/agents/derive-presence.test.ts
@@ -49,6 +49,7 @@ function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
device_info: "",
metadata: {},
owner_id: null,
+ timezone: "UTC",
last_seen_at: "2026-04-27T11:59:50Z",
created_at: "2026-04-01T00:00:00Z",
updated_at: "2026-04-01T00:00:00Z",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0119152165..52bb43cbae 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -657,6 +657,16 @@ export class ApiClient {
await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });
}
+ async updateRuntime(
+ runtimeId: string,
+ patch: { timezone?: string },
+ ): Promise<AgentRuntime> {
+ return this.fetch(`/api/runtimes/${runtimeId}`, {
+ method: "PATCH",
+ body: JSON.stringify(patch),
+ });
+ }
+
async getRuntimeUsage(runtimeId: string, params?: { days?: number }): Promise<RuntimeUsage[]> {
const search = new URLSearchParams();
if (params?.days) search.set("days", String(params.days));
diff --git a/packages/core/permissions/rules.test.ts b/packages/core/permissions/rules.test.ts
index 54262ec171..b512ba57a7 100644
--- a/packages/core/permissions/rules.test.ts
+++ b/packages/core/permissions/rules.test.ts
@@ -93,6 +93,7 @@ function makeRuntime(ownerId: string | null): RuntimeDevice {
device_info: "",
metadata: {},
owner_id: ownerId,
+ timezone: "UTC",
last_seen_at: null,
created_at: "2026-04-01T00:00:00Z",
updated_at: "2026-04-01T00:00:00Z",
diff --git a/packages/core/runtimes/derive-health.test.ts b/packages/core/runtimes/derive-health.test.ts
index 9e8f0d0e90..fcf1763b25 100644
--- a/packages/core/runtimes/derive-health.test.ts
+++ b/packages/core/runtimes/derive-health.test.ts
@@ -17,6 +17,7 @@ function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
device_info: "",
metadata: {},
owner_id: null,
+ timezone: "UTC",
last_seen_at: new Date(FIXED_NOW - 10_000).toISOString(),
created_at: "2026-04-01T00:00:00Z",
updated_at: "2026-04-01T00:00:00Z",
diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.ts
index 741bd8efba..25283953f5 100644
--- a/packages/core/runtimes/mutations.ts
+++ b/packages/core/runtimes/mutations.ts
@@ -11,3 +11,37 @@ export function useDeleteRuntime(wsId: string) {
},
});
}
+
+// useUpdateRuntime patches editable fields on a runtime (currently the
+// reporting timezone). Invalidates the runtime list AND any keys downstream
+// of the updated runtime — usage queries are bucketed by tz on the server,
+// so a tz change must blow away cached usage rows or the chart would lie
+// for one polling cycle.
+export function useUpdateRuntime(wsId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ runtimeId,
+ patch,
+ }: {
+ runtimeId: string;
+ patch: { timezone?: string };
+ }) => api.updateRuntime(runtimeId, patch),
+ onSettled: (_data, _err, vars) => {
+ qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ if (vars) {
+ // Usage query keys are not workspace-scoped; invalidate only this
+ // runtime's daily/by-agent/by-hour usage rows under the new tz buckets.
+ qc.invalidateQueries({
+ queryKey: ["runtimes", "usage", vars.runtimeId],
+ });
+ qc.invalidateQueries({
+ queryKey: ["runtimes", "usage", "by-agent", vars.runtimeId],
+ });
+ qc.invalidateQueries({
+ queryKey: ["runtimes", "usage", "by-hour", vars.runtimeId],
+ });
+ }
+ },
+ });
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index eb7c33cfb3..ff123f48f0 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -16,6 +16,7 @@ export interface RuntimeDevice {
device_info: string;
metadata: Record<string, unknown>;
owner_id: string | null;
+ timezone: string;
last_seen_at: string | null;
created_at: string;
updated_at: string;
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 3dada8ecda..72b265ace1 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -64,6 +64,11 @@
"no_agents": "No agents are bound to this runtime yet.",
"diagnostics_title": "Diagnostics",
"diagnostics_cli": "CLI",
+ "diagnostics_timezone": "Timezone",
+ "timezone_browser_suffix": " (browser)",
+ "timezone_hint": "Token-usage charts on this runtime bucket dates by this timezone.",
+ "timezone_toast_updated": "Timezone updated to {{tz}}",
+ "timezone_toast_failed": "Failed to update timezone",
"delete_dialog": {
"title": "Delete Runtime",
"description": "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 79659dde0d..4ca0180f87 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -63,6 +63,11 @@
"no_agents": "还没有智能体绑定到这个运行时。",
"diagnostics_title": "诊断",
"diagnostics_cli": "CLI",
+ "diagnostics_timezone": "时区",
+ "timezone_browser_suffix": "(浏览器)",
+ "timezone_hint": "该 Runtime 的 Token 用量图表会按此时区进行日期分桶。",
+ "timezone_toast_updated": "时区已更新为 {{tz}}",
+ "timezone_toast_failed": "更新时区失败",
"delete_dialog": {
"title": "删除运行时",
"description": "确定要删除\"{{name}}\"吗?此操作不可撤销。",
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 76deb77f84..8e96dad673 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -14,7 +14,7 @@ import type { AgentRuntime, Agent, MemberWithUser } from "@multica/core/types";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
-import { useDeleteRuntime } from "@multica/core/runtimes/mutations";
+import { useDeleteRuntime, useUpdateRuntime } from "@multica/core/runtimes/mutations";
import { deriveRuntimeHealth } from "@multica/core/runtimes";
import {
type AgentPresenceDetail,
@@ -37,6 +37,13 @@ import {
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
import { ActorAvatar } from "../../common/actor-avatar";
import { AppLink } from "../../navigation";
import { availabilityConfig, workloadConfig } from "../../agents/presence";
@@ -505,8 +512,18 @@ function DiagnosticsCard({
<span className="text-xs font-semibold">{t(($) => $.detail.diagnostics_title)}</span>
</div>
<div className="space-y-3 p-4">
+ <div>
+ <div className="mb-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
+ {t(($) => $.detail.diagnostics_timezone)}
+ </div>
+ {canDelete ? (
+ <TimezoneEditor runtime={runtime} />
+ ) : (
+ <TimezoneReadout runtime={runtime} />
+ )}
+ </div>
{isLocal && (
- <div>
+ <div className="border-t pt-3">
<div className="mb-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
{t(($) => $.detail.diagnostics_cli)}
</div>
@@ -519,7 +536,7 @@ function DiagnosticsCard({
</div>
)}
{canDelete && (
- <div className={isLocal ? "border-t pt-3" : ""}>
+ <div className="border-t pt-3">
<Button
variant="ghost"
size="sm"
@@ -535,3 +552,122 @@ function DiagnosticsCard({
</div>
);
}
+
+// Common IANA zones offered as quick picks when Intl.supportedValuesOf is not
+// available, and promoted near the top otherwise.
+const COMMON_TIMEZONES = [
+ "UTC",
+ "America/Los_Angeles",
+ "America/Denver",
+ "America/Chicago",
+ "America/New_York",
+ "America/Sao_Paulo",
+ "Europe/London",
+ "Europe/Berlin",
+ "Europe/Paris",
+ "Europe/Moscow",
+ "Africa/Cairo",
+ "Asia/Dubai",
+ "Asia/Kolkata",
+ "Asia/Bangkok",
+ "Asia/Shanghai",
+ "Asia/Singapore",
+ "Asia/Tokyo",
+ "Australia/Sydney",
+ "Pacific/Auckland",
+];
+
+function browserTimezone(): string {
+ try {
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ return tz || "UTC";
+ } catch {
+ return "UTC";
+ }
+}
+
+type IntlWithSupportedValues = typeof Intl & {
+ supportedValuesOf?: (key: "timeZone") => string[];
+};
+
+function supportedTimezones(): string[] {
+ try {
+ const supported = (Intl as IntlWithSupportedValues).supportedValuesOf?.(
+ "timeZone",
+ );
+ return supported && supported.length > 0 ? supported : COMMON_TIMEZONES;
+ } catch {
+ return COMMON_TIMEZONES;
+ }
+}
+
+function TimezoneReadout({ runtime }: { runtime: AgentRuntime }) {
+ const { t } = useT("runtimes");
+ return (
+ <div className="space-y-1.5">
+ <div className="rounded-md border bg-muted/30 px-2 py-1.5 font-mono text-xs">
+ {runtime.timezone || "UTC"}
+ </div>
+ <p className="text-[11px] leading-snug text-muted-foreground">
+ {t(($) => $.detail.timezone_hint)}
+ </p>
+ </div>
+ );
+}
+
+// TimezoneEditor renders the current runtime tz, a dropdown of supported IANA
+// zones (plus the runtime's current value if it is unusual), and commits the
+// change via PATCH /api/runtimes/:id. We deliberately don't gate this behind a
+// separate "edit" mode because the change is reversible.
+function TimezoneEditor({ runtime }: { runtime: AgentRuntime }) {
+ const { t } = useT("runtimes");
+ const wsId = useWorkspaceId();
+ const updateRuntime = useUpdateRuntime(wsId);
+ const current = runtime.timezone || "UTC";
+ const browser = browserTimezone();
+ const browserSuffix = t(($) => $.detail.timezone_browser_suffix);
+
+ const options = Array.from(
+ new Set([current, browser, ...COMMON_TIMEZONES, ...supportedTimezones()]),
+ ).filter(Boolean);
+ const handleTimezoneChange = (next: string) => {
+ if (next === current) return;
+ updateRuntime.mutate(
+ { runtimeId: runtime.id, patch: { timezone: next } },
+ {
+ onSuccess: () =>
+ toast.success(t(($) => $.detail.timezone_toast_updated, { tz: next })),
+ onError: () =>
+ toast.error(t(($) => $.detail.timezone_toast_failed)),
+ },
+ );
+ };
+
+ return (
+ <div className="space-y-1.5">
+ <Select
+ value={current}
+ disabled={updateRuntime.isPending}
+ onValueChange={(next) => {
+ if (next) handleTimezoneChange(next);
+ }}
+ >
+ <SelectTrigger size="sm" className="w-full rounded-md font-mono text-xs">
+ <SelectValue>
+ {current === browser ? `${current}${browserSuffix}` : current}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent align="start" className="max-h-72">
+ {options.map((tz) => (
+ <SelectItem key={tz} value={tz} className="font-mono text-xs">
+ {tz === browser ? `${tz}${browserSuffix}` : tz}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-[11px] leading-snug text-muted-foreground">
+ {t(($) => $.detail.timezone_hint)}
+ </p>
+ </div>
+ );
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index ce754c5cde..2f1add2de2 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -457,6 +457,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/api/runtimes", func(r chi.Router) {
r.Get("/", h.ListAgentRuntimes)
r.Route("/{runtimeId}", func(r chi.Router) {
+ r.Patch("/", h.UpdateAgentRuntime)
r.Get("/usage", h.GetRuntimeUsage)
r.Get("/usage/by-agent", h.GetRuntimeUsageByAgent)
r.Get("/usage/by-hour", h.GetRuntimeUsageByHour)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 0aa613db9f..06bf651fa5 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -370,6 +370,7 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s
"device_name": d.cfg.DeviceName,
"cli_version": d.cfg.CLIVersion,
"launched_by": d.cfg.LaunchedBy,
+ "timezone": detectLocalTimezone(),
"runtimes": runtimes,
}
@@ -383,6 +384,41 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s
return resp, nil
}
+// detectLocalTimezone returns an IANA zone name for the daemon host, used as
+// the initial value of agent_runtime.timezone on first registration. The
+// server treats any unparseable value as "UTC", but we still try harder here
+// because we'd rather a real "Asia/Shanghai" than a silent UTC fallback.
+// Short abbreviations like "EST" are intentionally ignored: they lose DST
+// rules and are a poor reporting timezone.
+func detectLocalTimezone() string {
+ if tz, ok := canonicalTimezoneName(os.Getenv("TZ")); ok {
+ return tz
+ }
+ if data, err := os.ReadFile("/etc/timezone"); err == nil {
+ if tz, ok := canonicalTimezoneName(string(data)); ok {
+ return tz
+ }
+ }
+ if tz, ok := canonicalTimezoneName(time.Local.String()); ok {
+ return tz
+ }
+ return "UTC"
+}
+
+func canonicalTimezoneName(raw string) (string, bool) {
+ tz := strings.TrimSpace(raw)
+ if tz == "" || tz == "Local" {
+ return "", false
+ }
+ if tz != "UTC" && !strings.Contains(tz, "/") {
+ return "", false
+ }
+ if _, err := time.LoadLocation(tz); err != nil {
+ return "", false
+ }
+ return tz, true
+}
+
func newWorkspaceState(workspaceID string, runtimeIDs []string, reposVersion string, repos []RepoData, settings json.RawMessage) *workspaceState {
return &workspaceState{
workspaceID: workspaceID,
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 85d4bc1b49..0ddf1faf81 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -134,7 +134,16 @@ type DaemonRegisterRequest struct {
DeviceName string `json:"device_name"`
CLIVersion string `json:"cli_version"` // multica CLI version
LaunchedBy string `json:"launched_by"` // "desktop" when spawned by the Electron app
- Runtimes []struct {
+ // Timezone is the daemon host's IANA timezone (e.g. "Asia/Shanghai"),
+ // detected client-side from time.Local. The server stores it on each
+ // agent_runtime row created for this daemon so token-usage rollups
+ // bucket by the operator's local calendar day instead of UTC. Empty
+ // or invalid values fall back to "UTC". The value is set ONLY on
+ // first-time registration; once a user overrides the tz via the web
+ // UI, the upsert query preserves that override on subsequent
+ // daemon reconnects (see UpsertAgentRuntime in runtime.sql).
+ Timezone string `json:"timezone"`
+ Runtimes []struct {
Name string `json:"name"`
Type string `json:"type"`
Version string `json:"version"` // agent CLI version (claude/codex)
@@ -148,6 +157,24 @@ type daemonWorkspaceReposResponse struct {
ReposVersion string `json:"repos_version"`
}
+// normalizeRuntimeTimezone validates and normalizes the IANA timezone string
+// reported by a daemon during registration. The stored column is NOT NULL with
+// a 'UTC' default so any unparseable, blank, or trivially-invalid value is
+// quietly downgraded to "UTC" rather than rejected: a misconfigured daemon
+// host shouldn't take down registration just because its tz string is junk.
+// Real validation happens on the user-driven PATCH path where we surface the
+// error.
+func normalizeRuntimeTimezone(tz string) string {
+ tz = strings.TrimSpace(tz)
+ if tz == "" {
+ return "UTC"
+ }
+ if _, err := time.LoadLocation(tz); err != nil {
+ return "UTC"
+ }
+ return tz
+}
+
func normalizeWorkspaceRepos(repos []RepoData) []RepoData {
if len(repos) == 0 {
return []RepoData{}
@@ -296,6 +323,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
DeviceInfo: deviceInfo,
Metadata: metadata,
OwnerID: ownerID,
+ Timezone: normalizeRuntimeTimezone(req.Timezone),
})
if err != nil {
h.Analytics.Capture(analytics.RuntimeFailed(
@@ -326,6 +354,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
UpdatedAt: row.UpdatedAt,
OwnerID: row.OwnerID,
LegacyDaemonID: row.LegacyDaemonID,
+ Timezone: row.Timezone,
}
// Inserted is false for normal daemon reconnects/upserts, so
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 37a4b6abf3..fd98962cdc 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -27,6 +27,7 @@ type AgentRuntimeResponse struct {
DeviceInfo string `json:"device_info"`
Metadata any `json:"metadata"`
OwnerID *string `json:"owner_id"`
+ Timezone string `json:"timezone"`
LastSeenAt *string `json:"last_seen_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
@@ -53,6 +54,7 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {
DeviceInfo: rt.DeviceInfo,
Metadata: metadata,
OwnerID: uuidToPtr(rt.OwnerID),
+ Timezone: rt.Timezone,
LastSeenAt: timestampToPtr(rt.LastSeenAt),
CreatedAt: timestampToString(rt.CreatedAt),
UpdatedAt: timestampToString(rt.UpdatedAt),
@@ -95,9 +97,9 @@ func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {
return
}
- since := parseSinceParam(r, 90)
+ since := parseSinceParamInTZ(r, 90, rt.Timezone)
- resp, err := h.listRuntimeUsage(r.Context(), rt.ID, since)
+ resp, err := h.listRuntimeUsage(r.Context(), rt.ID, rt.Timezone, since)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list usage")
return
@@ -110,12 +112,13 @@ func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {
// task_usage_daily rollup based on the UseDailyRollupForRuntimeUsage
// feature flag. Both code paths return rows in the same shape, so the
// handler doesn't care which one ran.
-func (h *Handler) listRuntimeUsage(ctx context.Context, runtimeID pgtype.UUID, since pgtype.Timestamptz) ([]RuntimeUsageResponse, error) {
+func (h *Handler) listRuntimeUsage(ctx context.Context, runtimeID pgtype.UUID, tz string, since pgtype.Timestamptz) ([]RuntimeUsageResponse, error) {
resolvedRuntimeID := uuidToString(runtimeID)
if h.cfg.UseDailyRollupForRuntimeUsage {
rows, err := h.Queries.ListRuntimeUsageDaily(ctx, db.ListRuntimeUsageDailyParams{
RuntimeID: runtimeID,
Since: since,
+ Tz: tz,
})
if err != nil {
return nil, err
@@ -139,6 +142,7 @@ func (h *Handler) listRuntimeUsage(ctx context.Context, runtimeID pgtype.UUID, s
rows, err := h.Queries.ListRuntimeUsage(ctx, db.ListRuntimeUsageParams{
RuntimeID: runtimeID,
Since: since,
+ Tz: tz,
})
if err != nil {
return nil, err
@@ -177,7 +181,10 @@ func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request)
return
}
- rows, err := h.Queries.GetRuntimeTaskHourlyActivity(r.Context(), rt.ID)
+ rows, err := h.Queries.GetRuntimeTaskHourlyActivity(r.Context(), db.GetRuntimeTaskHourlyActivityParams{
+ RuntimeID: rt.ID,
+ Tz: rt.Timezone,
+ })
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to get task activity")
return
@@ -225,7 +232,7 @@ func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request)
return
}
- since := parseSinceParam(r, 30)
+ since := parseSinceParamInTZ(r, 30, rt.Timezone)
rows, err := h.Queries.ListRuntimeUsageByAgent(r.Context(), db.ListRuntimeUsageByAgentParams{
RuntimeID: parseUUID(runtimeID),
@@ -280,11 +287,12 @@ func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request)
return
}
- since := parseSinceParam(r, 30)
+ since := parseSinceParamInTZ(r, 30, rt.Timezone)
rows, err := h.Queries.GetRuntimeUsageByHour(r.Context(), db.GetRuntimeUsageByHourParams{
RuntimeID: parseUUID(runtimeID),
Since: since,
+ Tz: rt.Timezone,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to get usage by hour")
@@ -386,6 +394,9 @@ func (h *Handler) GetWorkspaceUsageSummary(w http.ResponseWriter, r *http.Reques
}
// 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).
func parseSinceParam(r *http.Request, defaultDays int) pgtype.Timestamptz {
days := defaultDays
if d := r.URL.Query().Get("days"); d != "" {
@@ -397,6 +408,140 @@ func parseSinceParam(r *http.Request, defaultDays int) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: t, Valid: true}
}
+// parseSinceParamInTZ is the timezone-aware variant of parseSinceParam.
+// Anchors the cutoff to start-of-day-(N) in the supplied IANA zone so that
+// `days=N` returns full N+1 calendar buckets in that zone (today's partial
+// bucket + N prior full days). If tzName is empty or unparseable, falls back
+// to UTC — never returns an error so handlers stay simple.
+func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {
+ days := defaultDays
+ if d := r.URL.Query().Get("days"); d != "" {
+ if parsed, err := strconv.Atoi(d); err == nil && parsed > 0 && parsed <= 365 {
+ days = parsed
+ }
+ }
+ loc, err := time.LoadLocation(tzName)
+ if err != nil || loc == nil {
+ loc = time.UTC
+ }
+ now := time.Now().In(loc)
+ startOfToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
+ cutoff := startOfToday.AddDate(0, 0, -days)
+ return pgtype.Timestamptz{Time: cutoff, Valid: true}
+}
+
+// UpdateAgentRuntimeRequest is the JSON body accepted by PATCH /api/runtimes/:id.
+// Only fields users may legitimately edit are listed; other runtime metadata
+// (provider, daemon_id, status…) flows in from the daemon and is read-only here.
+type UpdateAgentRuntimeRequest struct {
+ // Timezone is an IANA zone name (e.g. "Asia/Shanghai", "America/New_York").
+ // Validated server-side via time.LoadLocation; "UTC" or empty resets to UTC.
+ Timezone *string `json:"timezone,omitempty"`
+}
+
+// UpdateAgentRuntime handles PATCH /api/runtimes/:id. Currently only the
+// reporting timezone is editable, but the request shape is open-ended so
+// future fields (display name, description) can be added without a route
+// change. Workspace-membership-checked; no admin-only restriction since the
+// runtime owner traditionally edits their own runtime.
+func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
+ if !ok {
+ return
+ }
+
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
+ if err != nil {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return
+ }
+
+ member, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found")
+ if !ok {
+ return
+ }
+ if !canEditRuntime(member, rt) {
+ writeError(w, http.StatusForbidden, "you can only edit your own runtimes")
+ return
+ }
+
+ var req UpdateAgentRuntimeRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid JSON body")
+ return
+ }
+
+ if req.Timezone != nil {
+ tz := *req.Timezone
+ if tz == "" {
+ tz = "UTC"
+ }
+ if _, err := time.LoadLocation(tz); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid IANA timezone")
+ return
+ }
+
+ if tz == rt.Timezone {
+ writeJSON(w, http.StatusOK, runtimeToResponse(rt))
+ return
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update runtime")
+ return
+ }
+ defer tx.Rollback(r.Context())
+
+ qtx := h.Queries.WithTx(tx)
+ if err := qtx.LockTaskUsageDailyRollup(r.Context()); err != nil {
+ slog.Error("LockTaskUsageDailyRollup failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to update runtime")
+ return
+ }
+ updated, err := qtx.UpdateAgentRuntimeTimezone(r.Context(), db.UpdateAgentRuntimeTimezoneParams{
+ ID: runtimeUUID,
+ Timezone: tz,
+ })
+ if err != nil {
+ slog.Error("UpdateAgentRuntimeTimezone failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to update runtime")
+ return
+ }
+ if _, err := qtx.DeleteTaskUsageDailyForRuntime(r.Context(), runtimeUUID); err != nil {
+ slog.Error("DeleteTaskUsageDailyForRuntime failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to rebuild runtime usage")
+ return
+ }
+ if _, err := qtx.DeleteTaskUsageDailyDirtyForRuntime(r.Context(), runtimeUUID); err != nil {
+ slog.Error("DeleteTaskUsageDailyDirtyForRuntime failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to rebuild runtime usage")
+ return
+ }
+ if _, err := qtx.InsertTaskUsageDailyForRuntime(r.Context(), runtimeUUID); err != nil {
+ slog.Error("InsertTaskUsageDailyForRuntime failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to rebuild runtime usage")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Error("runtime timezone transaction commit failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to update runtime")
+ return
+ }
+ rt = updated
+ }
+
+ writeJSON(w, http.StatusOK, runtimeToResponse(rt))
+}
+
+func canEditRuntime(member db.Member, rt db.AgentRuntime) bool {
+ if roleAllowed(member.Role, "owner", "admin") {
+ return true
+ }
+ return rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID)
+}
+
func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
@@ -450,13 +595,11 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
// Permission: owner/admin can delete any runtime; members can only delete their own.
- userID := uuidToString(member.UserID)
- isAdmin := roleAllowed(member.Role, "owner", "admin")
- isOwner := rt.OwnerID.Valid && uuidToString(rt.OwnerID) == userID
- if !isAdmin && !isOwner {
+ if !canEditRuntime(member, rt) {
writeError(w, http.StatusForbidden, "you can only delete your own runtimes")
return
}
+ userID := uuidToString(member.UserID)
// Check if any active (non-archived) agents are bound to this runtime.
activeCount, err := h.Queries.CountActiveAgentsByRuntime(r.Context(), rt.ID)
diff --git a/server/internal/handler/runtime_rollup_test.go b/server/internal/handler/runtime_rollup_test.go
index c94bdeb513..040324c472 100644
--- a/server/internal/handler/runtime_rollup_test.go
+++ b/server/internal/handler/runtime_rollup_test.go
@@ -172,6 +172,84 @@ func TestRollupTaskUsageDaily_AggregatesAndIsIdempotent(t *testing.T) {
}
}
+func TestRollupTaskUsageDaily_UsesRuntimeTimezone(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, timezone, last_seen_at
+ )
+ VALUES ($1, NULL, 'runtime-tz-rollup', 'cloud', 'runtime-tz-rollup', 'online', '{}'::jsonb, '{}'::jsonb, 'Asia/Shanghai', now())
+ RETURNING id
+ `, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("fetch agent: %v", err)
+ }
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type)
+ VALUES ($1, 'runtime tz rollup test', $2, 'member')
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+
+ usageAt := time.Date(2020, 6, 15, 18, 0, 0, 0, time.UTC) // 2020-06-16 02:00 Asia/Shanghai
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)
+ VALUES ($1, $2, $3, 'completed', $4)
+ RETURNING id
+ `, agentID, issueID, runtimeID, usageAt).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at, updated_at)
+ VALUES ($1, 'claude', 'claude-3-5-sonnet', 321, 0, $2, $2)
+ `, taskID, usageAt); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE runtime_id = $1`, runtimeID)
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
+ testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_daily_window($1::timestamptz, $2::timestamptz)
+ `, usageAt.Add(-time.Minute), usageAt.Add(time.Minute)); err != nil {
+ t.Fatalf("rollup_task_usage_daily_window: %v", err)
+ }
+
+ var bucketDate string
+ var inputTokens int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT bucket_date::text, input_tokens
+ FROM task_usage_daily
+ WHERE runtime_id = $1 AND provider = 'claude' AND model = 'claude-3-5-sonnet'
+ `, runtimeID).Scan(&bucketDate, &inputTokens); err != nil {
+ t.Fatalf("read rolled up row: %v", err)
+ }
+ if bucketDate != "2020-06-16" {
+ t.Fatalf("expected Asia/Shanghai bucket date 2020-06-16, got %s", bucketDate)
+ }
+ if inputTokens != 321 {
+ t.Fatalf("expected rolled up input tokens 321, got %d", inputTokens)
+ }
+}
+
// TestRollupTaskUsageDaily_WatermarkAdvances verifies the cron entry
// point: rollup_task_usage_daily() consults task_usage_rollup_state to
// decide its window, performs the upsert, and bumps the watermark.
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index 7408847e2d..787a30d2df 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -7,6 +7,9 @@ import (
"net/http/httptest"
"testing"
"time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {
@@ -194,3 +197,199 @@ func TestGetRuntimeUsage_BucketsByUsageTime(t *testing.T) {
t.Errorf("yesterday morning task: yesterday bucket expected 2000 input tokens, got %d (full map: %v)", byDate[yesterdayKey], byDate)
}
}
+
+func TestGetRuntimeUsageDailyRollupCutoffUsesRuntimeTimezone(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := handlerTestRuntimeID(t)
+
+ loc, err := time.LoadLocation("Asia/Shanghai")
+ if err != nil {
+ t.Fatalf("load location: %v", err)
+ }
+ cutoff := time.Date(2026, 5, 4, 0, 0, 0, 0, loc)
+ cutoffDate := cutoff.Format("2006-01-02")
+ extraDate := cutoff.AddDate(0, 0, -1).Format("2006-01-02")
+
+ var originalTZ string
+ if err := testPool.QueryRow(ctx, `SELECT timezone FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&originalTZ); err != nil {
+ t.Fatalf("read runtime timezone: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `UPDATE agent_runtime SET timezone = $1 WHERE id = $2`, originalTZ, runtimeID)
+ testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE runtime_id = $1 AND provider = 'cutoff-test'`, runtimeID)
+ })
+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET timezone = 'Asia/Shanghai' WHERE id = $1`, runtimeID); err != nil {
+ t.Fatalf("set runtime timezone: %v", err)
+ }
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage_daily (
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, event_count
+ )
+ VALUES
+ ($1::date, $3, $4, 'cutoff-test', 'old-day', 111, 0, 0, 0, 1),
+ ($2::date, $3, $4, 'cutoff-test', 'cutoff-day', 222, 0, 0, 0, 1)
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ event_count = EXCLUDED.event_count
+ `, extraDate, cutoffDate, testWorkspaceID, runtimeID); err != nil {
+ t.Fatalf("seed rollup rows: %v", err)
+ }
+
+ origRollup := testHandler.cfg.UseDailyRollupForRuntimeUsage
+ testHandler.cfg.UseDailyRollupForRuntimeUsage = true
+ t.Cleanup(func() { testHandler.cfg.UseDailyRollupForRuntimeUsage = origRollup })
+
+ resp, err := testHandler.listRuntimeUsage(ctx, parseUUID(runtimeID), "Asia/Shanghai", pgtype.Timestamptz{
+ Time: cutoff,
+ Valid: true,
+ })
+ if err != nil {
+ t.Fatalf("listRuntimeUsage: %v", err)
+ }
+ byDate := make(map[string]int64)
+ for _, row := range resp {
+ if row.Provider == "cutoff-test" {
+ byDate[row.Date] += row.InputTokens
+ }
+ }
+ if byDate[cutoffDate] != 222 {
+ t.Fatalf("expected cutoff date %s to be included with 222 tokens, got map %v", cutoffDate, byDate)
+ }
+ if byDate[extraDate] != 0 {
+ t.Fatalf("expected extra date %s to be excluded, got map %v", extraDate, byDate)
+ }
+}
+
+func TestUpdateAgentRuntimeTimezoneValidatesPermissionAndValue(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := handlerTestRuntimeID(t)
+
+ var originalTZ string
+ if err := testPool.QueryRow(ctx, `SELECT timezone FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&originalTZ); err != nil {
+ t.Fatalf("read runtime timezone: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `UPDATE agent_runtime SET timezone = $1 WHERE id = $2`, originalTZ, runtimeID)
+ testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE runtime_id = $1 AND provider = 'patch-tz-test'`, runtimeID)
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/runtimes/"+runtimeID, map[string]string{"timezone": "Asia/Shanghai"})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UpdateAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("valid timezone: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp AgentRuntimeResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Timezone != "Asia/Shanghai" {
+ t.Fatalf("expected timezone Asia/Shanghai, got %q", resp.Timezone)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/runtimes/"+runtimeID, map[string]string{"timezone": "Mars/Olympus"})
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UpdateAgentRuntime(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("invalid timezone: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var otherUserID string
+ testPool.Exec(ctx, `DELETE FROM "user" WHERE email = '[email protected]'`)
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO "user" (name, email)
+ VALUES ('Runtime TZ Member', '[email protected]')
+ RETURNING id
+ `).Scan(&otherUserID); err != nil {
+ t.Fatalf("create member user: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, otherUserID) })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role)
+ VALUES ($1, $2, 'member')
+ `, testWorkspaceID, otherUserID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/runtimes/"+runtimeID, map[string]string{"timezone": "Asia/Tokyo"})
+ req.Header.Set("X-User-ID", otherUserID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UpdateAgentRuntime(w, req)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("non-owner member: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestUpsertAgentRuntimePreservesTimezoneOverride(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ testPool.Exec(ctx, `
+ DELETE FROM agent_runtime
+ WHERE workspace_id = $1 AND daemon_id = 'tz-upsert-daemon' AND provider = 'tz-upsert-provider'
+ `, testWorkspaceID)
+ row, err := testHandler.Queries.UpsertAgentRuntime(ctx, db.UpsertAgentRuntimeParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ DaemonID: strToText("tz-upsert-daemon"),
+ Name: "Timezone Upsert Runtime",
+ RuntimeMode: "local",
+ Provider: "tz-upsert-provider",
+ Status: "online",
+ DeviceInfo: "tz-upsert-device",
+ Metadata: []byte(`{}`),
+ OwnerID: parseUUID(testUserID),
+ Timezone: "Asia/Shanghai",
+ })
+ if err != nil {
+ t.Fatalf("initial upsert: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, row.ID)
+ })
+
+ updated, err := testHandler.Queries.UpdateAgentRuntimeTimezone(ctx, db.UpdateAgentRuntimeTimezoneParams{
+ ID: row.ID,
+ Timezone: "America/New_York",
+ })
+ if err != nil {
+ t.Fatalf("set override: %v", err)
+ }
+ if updated.Timezone != "America/New_York" {
+ t.Fatalf("expected override to be set, got %q", updated.Timezone)
+ }
+
+ row, err = testHandler.Queries.UpsertAgentRuntime(ctx, db.UpsertAgentRuntimeParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ DaemonID: strToText("tz-upsert-daemon"),
+ Name: "Timezone Upsert Runtime",
+ RuntimeMode: "local",
+ Provider: "tz-upsert-provider",
+ Status: "online",
+ DeviceInfo: "tz-upsert-device reconnect",
+ Metadata: []byte(`{}`),
+ OwnerID: pgtype.UUID{},
+ Timezone: "Asia/Tokyo",
+ })
+ if err != nil {
+ t.Fatalf("reconnect upsert: %v", err)
+ }
+ if row.Timezone != "America/New_York" {
+ t.Fatalf("daemon reconnect should preserve user override, got %q", row.Timezone)
+ }
+}
diff --git a/server/migrations/081_runtime_timezone.down.sql b/server/migrations/081_runtime_timezone.down.sql
new file mode 100644
index 0000000000..f9e1d3afb2
--- /dev/null
+++ b/server/migrations/081_runtime_timezone.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_runtime DROP COLUMN IF EXISTS timezone;
diff --git a/server/migrations/081_runtime_timezone.up.sql b/server/migrations/081_runtime_timezone.up.sql
new file mode 100644
index 0000000000..dc0c82a73a
--- /dev/null
+++ b/server/migrations/081_runtime_timezone.up.sql
@@ -0,0 +1,19 @@
+-- Per-runtime IANA timezone, used as the bucket boundary for daily and
+-- hourly token-usage aggregation (see runtime_usage.sql + the rollup
+-- function in 082_rollup_runtime_timezone.up.sql).
+--
+-- Defaults to 'UTC' so the migration is non-disruptive: pre-existing
+-- runtimes keep their current UTC-bucketed semantics until an operator
+-- (web UI) or a daemon (system zoneinfo on registration) overrides it.
+-- All historical task_usage_daily rows stay UTC-cut; only buckets that
+-- get re-touched by new task_usage events after this migration ships
+-- get rebuilt under the runtime's tz. This is intentional — the product
+-- decision was "guarantee future correctness, do not backfill history".
+ALTER TABLE agent_runtime
+ ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC';
+
+COMMENT ON COLUMN agent_runtime.timezone IS
+ 'IANA timezone (e.g. ''Asia/Shanghai''). Bucket boundary for per-day '
+ 'and per-hour token usage aggregation. Defaults to UTC for runtimes '
+ 'that existed before MUL-1950; the daemon registration / web UI '
+ 'overwrites this with an operator-detected value going forward.';
diff --git a/server/migrations/082_rollup_runtime_timezone.down.sql b/server/migrations/082_rollup_runtime_timezone.down.sql
new file mode 100644
index 0000000000..dff4286b2b
--- /dev/null
+++ b/server/migrations/082_rollup_runtime_timezone.down.sql
@@ -0,0 +1,174 @@
+-- Restore the pre-082 function bodies (UTC-bucketed via bare DATE()).
+-- Mirrors the definitions installed by migration 077.
+
+CREATE OR REPLACE FUNCTION enqueue_task_usage_daily_dirty_for_atq()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ IF OLD.runtime_id IS DISTINCT FROM NEW.runtime_id THEN
+ IF OLD.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT DATE(tu.created_at), a.workspace_id, OLD.runtime_id, tu.provider, tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ IF NEW.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT DATE(tu.created_at), a.workspace_id, NEW.runtime_id, tu.provider, tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = NEW.agent_id
+ WHERE tu.task_id = NEW.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ END IF;
+ RETURN NEW;
+ ELSIF TG_OP = 'DELETE' THEN
+ IF OLD.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT DATE(tu.created_at), a.workspace_id, OLD.runtime_id, tu.provider, tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ RETURN OLD;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION enqueue_task_usage_daily_dirty_for_tu()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DATE(OLD.created_at), a.workspace_id, atq.runtime_id, OLD.provider, OLD.model
+ FROM agent_task_queue atq
+ JOIN agent a ON a.id = atq.agent_id
+ WHERE atq.id = OLD.task_id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ RETURN OLD;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION rollup_task_usage_daily_window(
+ p_from TIMESTAMPTZ,
+ p_to TIMESTAMPTZ
+)
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_rows BIGINT;
+BEGIN
+ IF p_from >= p_to THEN
+ RETURN 0;
+ END IF;
+
+ WITH
+ dirty_from_updates AS (
+ SELECT DISTINCT
+ DATE(tu.created_at) AS bucket_date,
+ a.workspace_id AS workspace_id,
+ atq.runtime_id AS runtime_id,
+ tu.provider AS provider,
+ tu.model AS model
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ WHERE atq.runtime_id IS NOT NULL
+ AND (
+ (tu.updated_at >= p_from AND tu.updated_at < p_to)
+ OR (tu.updated_at IS NULL
+ AND tu.created_at >= p_from
+ AND tu.created_at < p_to)
+ )
+ ),
+ dirty_from_queue AS (
+ SELECT bucket_date, workspace_id, runtime_id, provider, model
+ FROM task_usage_daily_dirty
+ WHERE enqueued_at < p_to
+ ),
+ dirty_keys AS (
+ SELECT * FROM dirty_from_updates
+ UNION
+ SELECT * FROM dirty_from_queue
+ ),
+ recomputed AS (
+ SELECT
+ dk.bucket_date,
+ dk.workspace_id,
+ dk.runtime_id,
+ dk.provider,
+ dk.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(*)::bigint AS event_count
+ FROM dirty_keys dk
+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id
+ JOIN agent a ON a.id = atq.agent_id
+ AND a.workspace_id = dk.workspace_id
+ JOIN task_usage tu ON tu.task_id = atq.id
+ AND tu.provider = dk.provider
+ AND tu.model = dk.model
+ AND DATE(tu.created_at) = dk.bucket_date
+ GROUP BY 1, 2, 3, 4, 5
+ ),
+ upserted AS (
+ INSERT INTO task_usage_daily AS d (
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+ )
+ SELECT
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+ FROM recomputed
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+ RETURNING 1
+ ),
+ deleted_empty AS (
+ DELETE FROM task_usage_daily d
+ USING dirty_keys dk
+ WHERE d.bucket_date = dk.bucket_date
+ AND d.workspace_id = dk.workspace_id
+ AND d.runtime_id = dk.runtime_id
+ AND d.provider = dk.provider
+ AND d.model = dk.model
+ AND NOT EXISTS (
+ SELECT 1 FROM recomputed r
+ WHERE r.bucket_date = dk.bucket_date
+ AND r.workspace_id = dk.workspace_id
+ AND r.runtime_id = dk.runtime_id
+ AND r.provider = dk.provider
+ AND r.model = dk.model
+ )
+ RETURNING 1
+ )
+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)
+ INTO v_rows;
+
+ DELETE FROM task_usage_daily_dirty WHERE enqueued_at < p_to;
+
+ RETURN v_rows;
+END;
+$$;
diff --git a/server/migrations/082_rollup_runtime_timezone.up.sql b/server/migrations/082_rollup_runtime_timezone.up.sql
new file mode 100644
index 0000000000..482ffaf100
--- /dev/null
+++ b/server/migrations/082_rollup_runtime_timezone.up.sql
@@ -0,0 +1,243 @@
+-- Re-bucket the rollup pipeline by the owning runtime's IANA timezone
+-- (added in 081), instead of the Postgres session timezone (which is
+-- effectively UTC in production).
+--
+-- This affects three places that all derive a bucket_date from
+-- `task_usage.created_at`:
+--
+-- 1. enqueue_task_usage_daily_dirty_for_atq() — trigger that enqueues
+-- dirty buckets when a task_usage's atq row changes runtime or
+-- gets deleted.
+-- 2. enqueue_task_usage_daily_dirty_for_tu() — trigger that enqueues
+-- dirty buckets when a task_usage row is deleted directly.
+-- 3. rollup_task_usage_daily_window() — the cron-driven window
+-- function that drains dirty keys and recomputes their buckets.
+--
+-- All three previously called bare `DATE(tu.created_at)`. They now call
+-- `DATE(tu.created_at AT TIME ZONE rt.timezone)`, joining `agent_runtime
+-- rt` along the existing path to atq.runtime_id. Skipping any one of
+-- them would split the bucket key between writers (triggers / window)
+-- and the rollup table itself.
+--
+-- *** NO HISTORICAL BACKFILL ***
+-- This migration changes only the function bodies, not any data. Rows
+-- already present in `task_usage_daily` keep their previously computed
+-- (UTC) `bucket_date` values. From the moment this migration ships,
+-- *future* writes / re-touches of any bucket recompute the date under
+-- the runtime's tz. For runtimes that stay on `'UTC'` (the column
+-- default) this is a no-op; for runtimes whose operators set a non-UTC
+-- tz, dates only converge as their underlying raw rows get re-touched
+-- by new events. The product decision (MUL-1950) was "guarantee future
+-- correctness, do not backfill history".
+
+CREATE OR REPLACE FUNCTION enqueue_task_usage_daily_dirty_for_atq()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ IF OLD.runtime_id IS DISTINCT FROM NEW.runtime_id THEN
+ IF OLD.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT
+ DATE(tu.created_at AT TIME ZONE rt.timezone),
+ a.workspace_id,
+ OLD.runtime_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ JOIN agent_runtime rt ON rt.id = OLD.runtime_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ IF NEW.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT
+ DATE(tu.created_at AT TIME ZONE rt.timezone),
+ a.workspace_id,
+ NEW.runtime_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = NEW.agent_id
+ JOIN agent_runtime rt ON rt.id = NEW.runtime_id
+ WHERE tu.task_id = NEW.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ END IF;
+ RETURN NEW;
+ ELSIF TG_OP = 'DELETE' THEN
+ IF OLD.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DISTINCT
+ DATE(tu.created_at AT TIME ZONE rt.timezone),
+ a.workspace_id,
+ OLD.runtime_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ JOIN agent_runtime rt ON rt.id = OLD.runtime_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ RETURN OLD;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION enqueue_task_usage_daily_dirty_for_tu()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO task_usage_daily_dirty (bucket_date, workspace_id, runtime_id, provider, model)
+ SELECT DATE(OLD.created_at AT TIME ZONE rt.timezone),
+ a.workspace_id,
+ atq.runtime_id,
+ OLD.provider,
+ OLD.model
+ FROM agent_task_queue atq
+ JOIN agent a ON a.id = atq.agent_id
+ JOIN agent_runtime rt ON rt.id = atq.runtime_id
+ WHERE atq.id = OLD.task_id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_daily_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ RETURN OLD;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION rollup_task_usage_daily_window(
+ p_from TIMESTAMPTZ,
+ p_to TIMESTAMPTZ
+)
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_rows BIGINT;
+BEGIN
+ IF p_from >= p_to THEN
+ RETURN 0;
+ END IF;
+
+ WITH
+ -- Source 1: rows with updated_at in this window (steady state) plus
+ -- the legacy-row OR branch for NULL updated_at (covered by partial
+ -- index idx_task_usage_created_at_legacy from migration 078).
+ --
+ -- bucket_date is now derived under each runtime's IANA timezone via
+ -- AT TIME ZONE rt.timezone. agent_runtime joins through atq.runtime_id
+ -- which is already required NOT NULL in the same WHERE clause.
+ dirty_from_updates AS (
+ SELECT DISTINCT
+ DATE(tu.created_at AT TIME ZONE rt.timezone) AS bucket_date,
+ a.workspace_id AS workspace_id,
+ atq.runtime_id AS runtime_id,
+ tu.provider AS provider,
+ tu.model AS model
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ JOIN agent_runtime rt ON rt.id = atq.runtime_id
+ WHERE atq.runtime_id IS NOT NULL
+ AND (
+ (tu.updated_at >= p_from AND tu.updated_at < p_to)
+ OR (tu.updated_at IS NULL
+ AND tu.created_at >= p_from
+ AND tu.created_at < p_to)
+ )
+ ),
+ -- Source 2: explicit invalidation queue (deletes + reassignments).
+ -- The queue rows already carry bucket_date computed under each
+ -- runtime's tz at trigger time, so we don't translate again here.
+ dirty_from_queue AS (
+ SELECT bucket_date, workspace_id, runtime_id, provider, model
+ FROM task_usage_daily_dirty
+ WHERE enqueued_at < p_to
+ ),
+ dirty_keys AS (
+ SELECT * FROM dirty_from_updates
+ UNION
+ SELECT * FROM dirty_from_queue
+ ),
+ -- Recompute each dirty bucket from ground truth. The bucket_date
+ -- predicate uses the runtime's tz so it matches dirty_from_updates
+ -- and the trigger functions byte-for-byte.
+ recomputed AS (
+ SELECT
+ dk.bucket_date,
+ dk.workspace_id,
+ dk.runtime_id,
+ dk.provider,
+ dk.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(*)::bigint AS event_count
+ FROM dirty_keys dk
+ JOIN agent_runtime rt ON rt.id = dk.runtime_id
+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id
+ JOIN agent a ON a.id = atq.agent_id
+ AND a.workspace_id = dk.workspace_id
+ JOIN task_usage tu ON tu.task_id = atq.id
+ AND tu.provider = dk.provider
+ AND tu.model = dk.model
+ AND DATE(tu.created_at AT TIME ZONE rt.timezone) = dk.bucket_date
+ GROUP BY 1, 2, 3, 4, 5
+ ),
+ -- REPLACE present buckets.
+ upserted AS (
+ INSERT INTO task_usage_daily AS d (
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+ )
+ SELECT
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+ FROM recomputed
+ ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+ RETURNING 1
+ ),
+ -- DELETE buckets that are dirty but have no source rows anymore.
+ deleted_empty AS (
+ DELETE FROM task_usage_daily d
+ USING dirty_keys dk
+ WHERE d.bucket_date = dk.bucket_date
+ AND d.workspace_id = dk.workspace_id
+ AND d.runtime_id = dk.runtime_id
+ AND d.provider = dk.provider
+ AND d.model = dk.model
+ AND NOT EXISTS (
+ SELECT 1 FROM recomputed r
+ WHERE r.bucket_date = dk.bucket_date
+ AND r.workspace_id = dk.workspace_id
+ AND r.runtime_id = dk.runtime_id
+ AND r.provider = dk.provider
+ AND r.model = dk.model
+ )
+ RETURNING 1
+ )
+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)
+ INTO v_rows;
+
+ DELETE FROM task_usage_daily_dirty WHERE enqueued_at < p_to;
+
+ RETURN v_rows;
+END;
+$$;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index f4a1e15a9b..541f246a28 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -58,6 +58,8 @@ type AgentRuntime struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
OwnerID pgtype.UUID `json:"owner_id"`
LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ // IANA timezone (e.g. 'Asia/Shanghai'). Bucket boundary for per-day and per-hour token usage aggregation. Defaults to UTC for runtimes that existed before MUL-1950; the daemon registration / web UI overwrites this with an operator-detected value going forward.
+ Timezone string `json:"timezone"`
}
type AgentSkill struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index a2f8f07630..ed6350f4f8 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -76,6 +76,36 @@ func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds f
return items, nil
}
+const deleteTaskUsageDailyDirtyForRuntime = `-- name: DeleteTaskUsageDailyDirtyForRuntime :execrows
+DELETE FROM task_usage_daily_dirty
+WHERE runtime_id = $1
+`
+
+// Drop queued dirty keys computed under the old timezone; the ordered rebuild
+// in the same transaction will write the current aggregate instead.
+func (q *Queries) DeleteTaskUsageDailyDirtyForRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteTaskUsageDailyDirtyForRuntime, runtimeID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const deleteTaskUsageDailyForRuntime = `-- name: DeleteTaskUsageDailyForRuntime :execrows
+DELETE FROM task_usage_daily
+WHERE runtime_id = $1
+`
+
+// First step of an explicit user timezone edit rebuild. Delete old materialized
+// rows before re-inserting under the runtime's new timezone.
+func (q *Queries) DeleteTaskUsageDailyForRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteTaskUsageDailyForRuntime, runtimeID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :many
UPDATE agent_task_queue
SET status = 'failed', completed_at = now(), error = 'runtime went offline',
@@ -135,7 +165,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
}
const findLegacyRuntimesByDaemonID = `-- name: FindLegacyRuntimesByDaemonID :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone FROM agent_runtime
WHERE workspace_id = $1
AND provider = $2
AND LOWER(daemon_id) = LOWER($3)
@@ -186,6 +216,7 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
); err != nil {
return nil, err
}
@@ -198,7 +229,7 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega
}
const getAgentRuntime = `-- name: GetAgentRuntime :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone FROM agent_runtime
WHERE id = $1
`
@@ -220,12 +251,13 @@ func (q *Queries) GetAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRun
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
)
return i, err
}
const getAgentRuntimeForWorkspace = `-- name: GetAgentRuntimeForWorkspace :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone FROM agent_runtime
WHERE id = $1 AND workspace_id = $2
`
@@ -252,12 +284,58 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
)
return i, err
}
+const insertTaskUsageDailyForRuntime = `-- name: InsertTaskUsageDailyForRuntime :execrows
+INSERT INTO task_usage_daily AS d (
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+)
+SELECT
+ DATE(tu.created_at AT TIME ZONE rt.timezone) AS bucket_date,
+ a.workspace_id,
+ atq.runtime_id,
+ tu.provider,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(*)::bigint AS event_count
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ JOIN agent_runtime rt ON rt.id = atq.runtime_id
+ WHERE atq.runtime_id = $1
+ GROUP BY 1, 2, 3, 4, 5
+ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+`
+
+// Final step of an explicit user timezone edit rebuild. This is intentionally
+// called only for user edits, not by the migration itself: deploys do not
+// backfill history, but a user-driven change must not leave old UTC rows next
+// to newly computed local rows. This scans all history for the edited runtime;
+// timezone edits are owner/admin operations and are expected to be rare.
+func (q *Queries) InsertTaskUsageDailyForRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, insertTaskUsageDailyForRuntime, runtimeID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const listAgentRuntimes = `-- name: ListAgentRuntimes :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone FROM agent_runtime
WHERE workspace_id = $1
ORDER BY created_at ASC
`
@@ -286,6 +364,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
); err != nil {
return nil, err
}
@@ -298,7 +377,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID
}
const listAgentRuntimesByOwner = `-- name: ListAgentRuntimesByOwner :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone FROM agent_runtime
WHERE workspace_id = $1 AND owner_id = $2
ORDER BY created_at ASC
`
@@ -332,6 +411,7 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
); err != nil {
return nil, err
}
@@ -343,11 +423,23 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
return items, nil
}
+const lockTaskUsageDailyRollup = `-- name: LockTaskUsageDailyRollup :exec
+SELECT pg_advisory_xact_lock(4242)
+`
+
+// Serialize explicit timezone rebuilds with rollup_task_usage_daily(), which
+// uses the same advisory key in migration 073. This prevents cron from
+// writing old-timezone buckets while PATCH is deleting/rebuilding rows.
+func (q *Queries) LockTaskUsageDailyRollup(ctx context.Context) error {
+ _, err := q.db.Exec(ctx, lockTaskUsageDailyRollup)
+ return err
+}
+
const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :one
UPDATE agent_runtime
SET status = 'online', last_seen_at = now(), updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone
`
// Used on the offline→online transition (and on first heartbeat after
@@ -371,6 +463,7 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (A
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
)
return i, err
}
@@ -600,6 +693,42 @@ func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgt
return result.RowsAffected(), nil
}
+const updateAgentRuntimeTimezone = `-- name: UpdateAgentRuntimeTimezone :one
+UPDATE agent_runtime
+SET timezone = $1, updated_at = now()
+WHERE id = $2
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone
+`
+
+type UpdateAgentRuntimeTimezoneParams struct {
+ Timezone string `json:"timezone"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Operator-driven override of the runtime's reporting timezone (MUL-1950).
+func (q *Queries) UpdateAgentRuntimeTimezone(ctx context.Context, arg UpdateAgentRuntimeTimezoneParams) (AgentRuntime, error) {
+ row := q.db.QueryRow(ctx, updateAgentRuntimeTimezone, arg.Timezone, arg.ID)
+ var i AgentRuntime
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DaemonID,
+ &i.Name,
+ &i.RuntimeMode,
+ &i.Provider,
+ &i.Status,
+ &i.DeviceInfo,
+ &i.Metadata,
+ &i.LastSeenAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OwnerID,
+ &i.LegacyDaemonID,
+ &i.Timezone,
+ )
+ return i, err
+}
+
const upsertAgentRuntime = `-- name: UpsertAgentRuntime :one
INSERT INTO agent_runtime (
workspace_id,
@@ -611,8 +740,9 @@ INSERT INTO agent_runtime (
device_info,
metadata,
owner_id,
+ timezone,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
ON CONFLICT (workspace_id, daemon_id, provider)
DO UPDATE SET
name = EXCLUDED.name,
@@ -623,7 +753,7 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, (xmax = 0) AS inserted
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, timezone, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeParams struct {
@@ -636,6 +766,7 @@ type UpsertAgentRuntimeParams struct {
DeviceInfo string `json:"device_info"`
Metadata []byte `json:"metadata"`
OwnerID pgtype.UUID `json:"owner_id"`
+ Timezone string `json:"timezone"`
}
type UpsertAgentRuntimeRow struct {
@@ -653,12 +784,19 @@ type UpsertAgentRuntimeRow struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
OwnerID pgtype.UUID `json:"owner_id"`
LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ Timezone string `json:"timezone"`
Inserted bool `json:"inserted"`
}
// (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
// that updated an existing row (false). Analytics reads this to fire
// runtime_registered/runtime_ready only on first-time registration.
+//
+// @timezone is set on INSERT only. On conflict we deliberately KEEP the
+// existing agent_runtime.timezone — once an operator overrides the tz via
+// the web UI we don't want a daemon reconnect (which sends its own system
+// tz) to silently revert it. Daemons can still set the initial value when
+// they're the first to register a brand-new runtime row.
func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntimeParams) (UpsertAgentRuntimeRow, error) {
row := q.db.QueryRow(ctx, upsertAgentRuntime,
arg.WorkspaceID,
@@ -670,6 +808,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
arg.DeviceInfo,
arg.Metadata,
arg.OwnerID,
+ arg.Timezone,
)
var i UpsertAgentRuntimeRow
err := row.Scan(
@@ -687,6 +826,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Timezone,
&i.Inserted,
)
return i, err
diff --git a/server/pkg/db/generated/runtime_usage.sql.go b/server/pkg/db/generated/runtime_usage.sql.go
index f532b606cb..483a73cc39 100644
--- a/server/pkg/db/generated/runtime_usage.sql.go
+++ b/server/pkg/db/generated/runtime_usage.sql.go
@@ -12,20 +12,29 @@ import (
)
const getRuntimeTaskHourlyActivity = `-- name: GetRuntimeTaskHourlyActivity :many
-SELECT EXTRACT(HOUR FROM started_at)::int AS hour, COUNT(*)::int AS count
+SELECT EXTRACT(HOUR FROM started_at AT TIME ZONE $2::text)::int AS hour,
+ COUNT(*)::int AS count
FROM agent_task_queue
WHERE runtime_id = $1 AND started_at IS NOT NULL
GROUP BY hour
ORDER BY hour
`
+type GetRuntimeTaskHourlyActivityParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Tz string `json:"tz"`
+}
+
type GetRuntimeTaskHourlyActivityRow struct {
Hour int32 `json:"hour"`
Count int32 `json:"count"`
}
-func (q *Queries) GetRuntimeTaskHourlyActivity(ctx context.Context, runtimeID pgtype.UUID) ([]GetRuntimeTaskHourlyActivityRow, error) {
- rows, err := q.db.Query(ctx, getRuntimeTaskHourlyActivity, runtimeID)
+// Hour-of-day distribution for queue starts. Bucketed in the runtime's
+// local tz so "this runtime is busy in the afternoon" actually means
+// the operator's afternoon, not UTC's.
+func (q *Queries) GetRuntimeTaskHourlyActivity(ctx context.Context, arg GetRuntimeTaskHourlyActivityParams) ([]GetRuntimeTaskHourlyActivityRow, error) {
+ rows, err := q.db.Query(ctx, getRuntimeTaskHourlyActivity, arg.RuntimeID, arg.Tz)
if err != nil {
return nil, err
}
@@ -46,7 +55,7 @@ func (q *Queries) GetRuntimeTaskHourlyActivity(ctx context.Context, runtimeID pg
const getRuntimeUsageByHour = `-- name: GetRuntimeUsageByHour :many
SELECT
- EXTRACT(HOUR FROM tu.created_at)::int AS hour,
+ EXTRACT(HOUR FROM tu.created_at AT TIME ZONE $2::text)::int AS hour,
tu.model,
SUM(tu.input_tokens)::bigint AS input_tokens,
SUM(tu.output_tokens)::bigint AS output_tokens,
@@ -56,13 +65,14 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
-GROUP BY EXTRACT(HOUR FROM tu.created_at), tu.model
+ AND tu.created_at >= $3::timestamptz
+GROUP BY EXTRACT(HOUR FROM tu.created_at AT TIME ZONE $2::text), tu.model
ORDER BY hour, tu.model
`
type GetRuntimeUsageByHourParams struct {
RuntimeID pgtype.UUID `json:"runtime_id"`
+ Tz string `json:"tz"`
Since pgtype.Timestamptz `json:"since"`
}
@@ -81,8 +91,11 @@ type GetRuntimeUsageByHourRow struct {
// doing real work, with model preserved for client-side cost calculation
// (same reason as ListRuntimeUsageByAgent above). Hours with zero activity
// are omitted; the client fills the 24-bucket axis.
+//
+// Hours are extracted in the runtime's local tz via @tz so afternoon
+// work bucketed at UTC 06:00 lands in 14:00 for a UTC+8 runtime.
func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsageByHourParams) ([]GetRuntimeUsageByHourRow, error) {
- rows, err := q.db.Query(ctx, getRuntimeUsageByHour, arg.RuntimeID, arg.Since)
+ rows, err := q.db.Query(ctx, getRuntimeUsageByHour, arg.RuntimeID, arg.Tz, arg.Since)
if err != nil {
return nil, err
}
@@ -111,7 +124,7 @@ func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsage
const listRuntimeUsage = `-- name: ListRuntimeUsage :many
SELECT
- DATE(tu.created_at) AS date,
+ DATE(tu.created_at AT TIME ZONE $2::text) AS date,
tu.provider,
tu.model,
SUM(tu.input_tokens)::bigint AS input_tokens,
@@ -121,13 +134,14 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
-GROUP BY DATE(tu.created_at), tu.provider, tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.provider, tu.model
+ AND tu.created_at >= $3::timestamptz
+GROUP BY DATE(tu.created_at AT TIME ZONE $2::text), tu.provider, tu.model
+ORDER BY DATE(tu.created_at AT TIME ZONE $2::text) DESC, tu.provider, tu.model
`
type ListRuntimeUsageParams struct {
RuntimeID pgtype.UUID `json:"runtime_id"`
+ Tz string `json:"tz"`
Since pgtype.Timestamptz `json:"since"`
}
@@ -141,13 +155,15 @@ type ListRuntimeUsageRow struct {
CacheWriteTokens int64 `json:"cache_write_tokens"`
}
-// Reads from raw `task_usage`, bucketed by DATE(tu.created_at) — usage
-// report time, ~= task completion time. Since cutoff is truncated to
-// start-of-day so `days=N` yields full calendar days. This is the
-// always-correct fallback path; used when USAGE_DAILY_ROLLUP_ENABLED
-// is false (or the rollup hasn't been deployed yet).
+// Reads from raw `task_usage`, bucketed by the runtime's local calendar
+// date via @tz (IANA name, e.g. 'Asia/Shanghai'). The Go layer resolves
+// @tz from agent_runtime.timezone and computes @since as start-of-day-N
+// already in that zone, so the cutoff can stay as a plain timestamptz.
+// This is the always-correct fallback path; used when
+// USAGE_DAILY_ROLLUP_ENABLED is false (or the rollup hasn't been
+// deployed yet).
func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsageParams) ([]ListRuntimeUsageRow, error) {
- rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Since)
+ rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Tz, arg.Since)
if err != nil {
return nil, err
}
@@ -186,7 +202,7 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
+ AND tu.created_at >= $2::timestamptz
GROUP BY atq.agent_id, tu.model
ORDER BY atq.agent_id, tu.model
`
@@ -212,6 +228,9 @@ type ListRuntimeUsageByAgentRow struct {
// purpose: cost is computed client-side from a per-model pricing table, so
// collapsing models server-side would erase the information needed to do
// that arithmetic. The client groups by agent_id and sums cost per agent.
+//
+// This view doesn't bucket by date, so it doesn't need @tz; only the
+// @since cutoff is provided in runtime-local terms (computed in Go).
func (q *Queries) ListRuntimeUsageByAgent(ctx context.Context, arg ListRuntimeUsageByAgentParams) ([]ListRuntimeUsageByAgentRow, error) {
rows, err := q.db.Query(ctx, listRuntimeUsageByAgent, arg.RuntimeID, arg.Since)
if err != nil {
@@ -251,13 +270,14 @@ SELECT
SUM(cache_write_tokens)::bigint AS cache_write_tokens
FROM task_usage_daily
WHERE runtime_id = $1
- AND bucket_date >= DATE(DATE_TRUNC('day', $2::timestamptz))
+ AND bucket_date >= (($3::timestamptz AT TIME ZONE $2::text)::date)
GROUP BY bucket_date, provider, model
ORDER BY bucket_date DESC, provider, model
`
type ListRuntimeUsageDailyParams struct {
RuntimeID pgtype.UUID `json:"runtime_id"`
+ Tz string `json:"tz"`
Since pgtype.Timestamptz `json:"since"`
}
@@ -281,12 +301,17 @@ type ListRuntimeUsageDailyRow struct {
// verified that the rollup is fresh (see task_usage_rollup_lag_seconds
// helper from migration 076).
//
+// bucket_date is already materialized in the runtime's tz (migration
+// 082). The cutoff still needs @tz because DATE(timestamptz) would cast in
+// the Postgres session timezone; positive-offset runtimes would otherwise
+// include one extra UTC day.
+//
// The PK on task_usage_daily already collapses to one row per
// (bucket_date, runtime_id, provider, model), but SUM/GROUP BY is kept
// so future schema changes (extra dimensions promoted into the table)
// don't silently change query semantics.
func (q *Queries) ListRuntimeUsageDaily(ctx context.Context, arg ListRuntimeUsageDailyParams) ([]ListRuntimeUsageDailyRow, error) {
- rows, err := q.db.Query(ctx, listRuntimeUsageDaily, arg.RuntimeID, arg.Since)
+ rows, err := q.db.Query(ctx, listRuntimeUsageDaily, arg.RuntimeID, arg.Tz, arg.Since)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index f9e34ab4c2..5172bb2d90 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -15,6 +15,12 @@ WHERE id = $1 AND workspace_id = $2;
-- (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
-- that updated an existing row (false). Analytics reads this to fire
-- runtime_registered/runtime_ready only on first-time registration.
+--
+-- @timezone is set on INSERT only. On conflict we deliberately KEEP the
+-- existing agent_runtime.timezone — once an operator overrides the tz via
+-- the web UI we don't want a daemon reconnect (which sends its own system
+-- tz) to silently revert it. Daemons can still set the initial value when
+-- they're the first to register a brand-new runtime row.
INSERT INTO agent_runtime (
workspace_id,
daemon_id,
@@ -25,8 +31,9 @@ INSERT INTO agent_runtime (
device_info,
metadata,
owner_id,
+ timezone,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, @timezone, now())
ON CONFLICT (workspace_id, daemon_id, provider)
DO UPDATE SET
name = EXCLUDED.name,
@@ -39,6 +46,67 @@ DO UPDATE SET
updated_at = now()
RETURNING *, (xmax = 0) AS inserted;
+-- name: LockTaskUsageDailyRollup :exec
+-- Serialize explicit timezone rebuilds with rollup_task_usage_daily(), which
+-- uses the same advisory key in migration 073. This prevents cron from
+-- writing old-timezone buckets while PATCH is deleting/rebuilding rows.
+SELECT pg_advisory_xact_lock(4242);
+
+-- name: UpdateAgentRuntimeTimezone :one
+-- Operator-driven override of the runtime's reporting timezone (MUL-1950).
+UPDATE agent_runtime
+SET timezone = @timezone, updated_at = now()
+WHERE id = @id
+RETURNING *;
+
+-- name: DeleteTaskUsageDailyForRuntime :execrows
+-- First step of an explicit user timezone edit rebuild. Delete old materialized
+-- rows before re-inserting under the runtime's new timezone.
+DELETE FROM task_usage_daily
+WHERE runtime_id = $1;
+
+-- name: DeleteTaskUsageDailyDirtyForRuntime :execrows
+-- Drop queued dirty keys computed under the old timezone; the ordered rebuild
+-- in the same transaction will write the current aggregate instead.
+DELETE FROM task_usage_daily_dirty
+WHERE runtime_id = $1;
+
+-- name: InsertTaskUsageDailyForRuntime :execrows
+-- Final step of an explicit user timezone edit rebuild. This is intentionally
+-- called only for user edits, not by the migration itself: deploys do not
+-- backfill history, but a user-driven change must not leave old UTC rows next
+-- to newly computed local rows. This scans all history for the edited runtime;
+-- timezone edits are owner/admin operations and are expected to be rare.
+INSERT INTO task_usage_daily AS d (
+ bucket_date, workspace_id, runtime_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ event_count
+)
+SELECT
+ DATE(tu.created_at AT TIME ZONE rt.timezone) AS bucket_date,
+ a.workspace_id,
+ atq.runtime_id,
+ tu.provider,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(*)::bigint AS event_count
+ FROM task_usage tu
+ JOIN agent_task_queue atq ON atq.id = tu.task_id
+ JOIN agent a ON a.id = atq.agent_id
+ JOIN agent_runtime rt ON rt.id = atq.runtime_id
+ WHERE atq.runtime_id = $1
+ GROUP BY 1, 2, 3, 4, 5
+ON CONFLICT (bucket_date, workspace_id, runtime_id, provider, model) DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens,
+ output_tokens = EXCLUDED.output_tokens,
+ cache_read_tokens = EXCLUDED.cache_read_tokens,
+ cache_write_tokens = EXCLUDED.cache_write_tokens,
+ event_count = EXCLUDED.event_count,
+ updated_at = now();
+
-- name: TouchAgentRuntimeLastSeen :execrows
-- Bumps last_seen_at on an already-online runtime. Deliberately does NOT
-- touch status or updated_at: status is unchanged on the hot heartbeat path,
diff --git a/server/pkg/db/queries/runtime_usage.sql b/server/pkg/db/queries/runtime_usage.sql
index 48267328f2..95437602d8 100644
--- a/server/pkg/db/queries/runtime_usage.sql
+++ b/server/pkg/db/queries/runtime_usage.sql
@@ -1,11 +1,13 @@
-- name: ListRuntimeUsage :many
--- Reads from raw `task_usage`, bucketed by DATE(tu.created_at) — usage
--- report time, ~= task completion time. Since cutoff is truncated to
--- start-of-day so `days=N` yields full calendar days. This is the
--- always-correct fallback path; used when USAGE_DAILY_ROLLUP_ENABLED
--- is false (or the rollup hasn't been deployed yet).
+-- Reads from raw `task_usage`, bucketed by the runtime's local calendar
+-- date via @tz (IANA name, e.g. 'Asia/Shanghai'). The Go layer resolves
+-- @tz from agent_runtime.timezone and computes @since as start-of-day-N
+-- already in that zone, so the cutoff can stay as a plain timestamptz.
+-- This is the always-correct fallback path; used when
+-- USAGE_DAILY_ROLLUP_ENABLED is false (or the rollup hasn't been
+-- deployed yet).
SELECT
- DATE(tu.created_at) AS date,
+ DATE(tu.created_at AT TIME ZONE @tz::text) AS date,
tu.provider,
tu.model,
SUM(tu.input_tokens)::bigint AS input_tokens,
@@ -15,9 +17,9 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
-GROUP BY DATE(tu.created_at), tu.provider, tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.provider, tu.model;
+ AND tu.created_at >= @since::timestamptz
+GROUP BY DATE(tu.created_at AT TIME ZONE @tz::text), tu.provider, tu.model
+ORDER BY DATE(tu.created_at AT TIME ZONE @tz::text) DESC, tu.provider, tu.model;
-- name: ListRuntimeUsageDaily :many
-- Reads from the `task_usage_daily` rollup table maintained by
@@ -30,6 +32,11 @@ ORDER BY DATE(tu.created_at) DESC, tu.provider, tu.model;
-- verified that the rollup is fresh (see task_usage_rollup_lag_seconds
-- helper from migration 076).
--
+-- bucket_date is already materialized in the runtime's tz (migration
+-- 082). The cutoff still needs @tz because DATE(timestamptz) would cast in
+-- the Postgres session timezone; positive-offset runtimes would otherwise
+-- include one extra UTC day.
+--
-- The PK on task_usage_daily already collapses to one row per
-- (bucket_date, runtime_id, provider, model), but SUM/GROUP BY is kept
-- so future schema changes (extra dimensions promoted into the table)
@@ -44,12 +51,16 @@ SELECT
SUM(cache_write_tokens)::bigint AS cache_write_tokens
FROM task_usage_daily
WHERE runtime_id = $1
- AND bucket_date >= DATE(DATE_TRUNC('day', @since::timestamptz))
+ AND bucket_date >= ((sqlc.arg('since')::timestamptz AT TIME ZONE sqlc.arg('tz')::text)::date)
GROUP BY bucket_date, provider, model
ORDER BY bucket_date DESC, provider, model;
-- name: GetRuntimeTaskHourlyActivity :many
-SELECT EXTRACT(HOUR FROM started_at)::int AS hour, COUNT(*)::int AS count
+-- Hour-of-day distribution for queue starts. Bucketed in the runtime's
+-- local tz so "this runtime is busy in the afternoon" actually means
+-- the operator's afternoon, not UTC's.
+SELECT EXTRACT(HOUR FROM started_at AT TIME ZONE @tz::text)::int AS hour,
+ COUNT(*)::int AS count
FROM agent_task_queue
WHERE runtime_id = $1 AND started_at IS NOT NULL
GROUP BY hour
@@ -62,6 +73,9 @@ ORDER BY hour;
-- purpose: cost is computed client-side from a per-model pricing table, so
-- collapsing models server-side would erase the information needed to do
-- that arithmetic. The client groups by agent_id and sums cost per agent.
+--
+-- This view doesn't bucket by date, so it doesn't need @tz; only the
+-- @since cutoff is provided in runtime-local terms (computed in Go).
SELECT
atq.agent_id,
tu.model,
@@ -73,7 +87,7 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
+ AND tu.created_at >= @since::timestamptz
GROUP BY atq.agent_id, tu.model
ORDER BY atq.agent_id, tu.model;
@@ -83,8 +97,11 @@ ORDER BY atq.agent_id, tu.model;
-- doing real work, with model preserved for client-side cost calculation
-- (same reason as ListRuntimeUsageByAgent above). Hours with zero activity
-- are omitted; the client fills the 24-bucket axis.
+--
+-- Hours are extracted in the runtime's local tz via @tz so afternoon
+-- work bucketed at UTC 06:00 lands in 14:00 for a UTC+8 runtime.
SELECT
- EXTRACT(HOUR FROM tu.created_at)::int AS hour,
+ EXTRACT(HOUR FROM tu.created_at AT TIME ZONE @tz::text)::int AS hour,
tu.model,
SUM(tu.input_tokens)::bigint AS input_tokens,
SUM(tu.output_tokens)::bigint AS output_tokens,
@@ -94,6 +111,6 @@ SELECT
FROM task_usage tu
JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.runtime_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
-GROUP BY EXTRACT(HOUR FROM tu.created_at), tu.model
+ AND tu.created_at >= @since::timestamptz
+GROUP BY EXTRACT(HOUR FROM tu.created_at AT TIME ZONE @tz::text), tu.model
ORDER BY hour, tu.model;