Skip to content

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

Go

MUL-2488 feat(timezone): Scheduling / Viewing two-layer timezone architecture (#2968)

YYClaw614dfae884ba
diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsx
index 854175886c..2a5d9c0689 100644
--- a/apps/web/test/helpers.tsx
+++ b/apps/web/test/helpers.tsx
@@ -15,6 +15,7 @@ export const mockUser: User = {
// field shipped — migration 054 backfills 'skipped_legacy'.
starter_content_state: "skipped_legacy",
language: null,
+ timezone: null,
profile_description: "",
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
diff --git a/docs/timezone-architecture-rfc.md b/docs/timezone-architecture-rfc.md
new file mode 100644
index 0000000000..544cfc9904
--- /dev/null
+++ b/docs/timezone-architecture-rfc.md
@@ -0,0 +1,374 @@
+# Timezone 架构重构 — Scheduling / Viewing 两层模型
+
+> Status: Implemented
+> Last updated: 2026-05-20
+
+## TL;DR
+
+- **问题**:当前代码里 timezone 被三种语义混用,导致 workspace usage 页 picker 在 #2822 review 中被移除(前后端 tz 不一致会把跨 UTC 午夜的行算到错的 calendar week),同时 runtime detail 页的 timezone editor 又承担了"既是物理 tz 又是报表 tz"的双重职责。
+- **方案**:把 timezone 收敛成两个独立的 product 概念——**Scheduling**(trigger 规则里写的"9 点"是哪个 9 点,由 `autopilot_trigger.timezone` 承载)和 **Viewing**(用户报表 tz,由新字段 `user.timezone` 承载)。原先混在 `runtime.timezone` 上的"物理位置"语义(Operational)经盘查无真实消费者,整列移除。
+- **数据层**:把 `task_usage_daily` (per-runtime, 物化在 runtime tz) 和 `task_usage_dashboard_daily` (workspace 级, 物化在 UTC) **合并成一张 `task_usage_hourly` (UTC, hourly grain)**,所有报表查询按调用方 tz 在查询时切日界。
+- **新增字段**:`user.timezone`(默认 = browser detected,可在 Preferences 覆盖)。
+- **不引入** `workspace.timezone`——viewing tz 是查看者属性,不是 workspace 属性。
+- **性能**:hourly rollup 在密集工况(16 active hours/day)下单 ws 90d 窗口 ~15k 行、~15ms,和现有 daily rollup 同档。
+- **副产品**:Migration 082 的"改 runtime tz → 重灌整张 rollup"逻辑可以删除;跨 region 团队自动支持各看各的"今天";未来要做 hourly heatmap / 时段分析无需再动 schema。
+
+---
+
+## 1. 背景
+
+### 1.1 现状盘点
+
+代码里"timezone"出现在四个地方:
+
+| # | 位置 | 字段 | 实际语义 |
+|---|---|---|---|
+| 1 | `agent_runtime.timezone` | TEXT, daemon 探测或 UI 覆盖 | 报表 + 物理位置(混淆) |
+| 2 | `autopilot_trigger.timezone` | TEXT, 用户写规则时选 | Scheduling(正确) |
+| 3 | Workspace Usage 页面 | 无字段,曾在前端用 `useState(browserTimezone())` | Viewing(被 #2822 删除) |
+| 4 | 各种 list / log 时间戳显示 | 浏览器 tz | Viewing(隐式) |
+
+### 1.2 问题
+
+**问题 A — Runtime tz 同时承担两个不同的角色:**
+
+`runtime.timezone` 在 migration 082 之后决定了 `task_usage_daily.bucket_date` 的物化口径,等于"报表 tz";同时 daemon 启动时 `detectLocalTimezone()` 写入这个字段,又当成"机器物理 tz"用。结果:
+
+- 改这个字段会触发整张 rollup 重新物化(migration 082 backfill 逻辑),代价不小。
+- 一个 SF 的 dev 把 daemon 跑在 PST 的机器上,但 PM 在上海希望按 CST 出报表——这一个字段没法同时满足两个需求。
+- daemon 自动探测的"客观真值"和用户手动想换的"我想看的报表 tz"被同一个 PATCH 接口覆盖,互相打架。
+
+**问题 B — Workspace usage 页面没有正确的"报表 tz"概念:**
+
+PR #2822 删除了 workspace usage 页的 TimezonePicker,原因是:
+
+> 后端 dashboard rollup 把数据按 UTC `bucket_date` 聚合,但前端却驱动 Weekly 边界用用户在 picker 里选的 tz。靠近 UTC 午夜的行会被放进错的 calendar week。Lock workspace Weekly to UTC and remove the timezone picker。
+
+这个修复是对的——前后端 tz 不一致就是 bug。但它**没解决根本问题**:用户确实需要按自己的 tz 看 workspace 报表,只是当前数据层没法支持。
+
+**问题 C — Viewing tz 没有持久化:**
+
+即使 picker 还在,它也只是 `useState(browserTimezone())`——刷新页面、换设备、跨 session 都会丢。用户每次都得手动切。
+
+**问题 D — 没有"跨 region 团队"的支持位:**
+
+把"报表 tz"放在 workspace 上是常见的诱惑,但 workspace 里两个成员一个在 SF 一个在 Beijing,他们想看到的"今天"本来就不同。任何"workspace 级 tz 设置"都强制其中一个人看错位的报表。
+
+### 1.3 目标
+
+1. **架构上清晰**:每个 timezone 字段只回答一个问题。
+2. **性能上不退步**:所有现有报表查询保持 <15ms 量级。
+3. **正确性优先**:前后端 tz 物化口径必须一致,没有"前端切了但后端没跟"的 UI 谎言。
+4. **跨 region 友好**:同一 workspace 不同成员可以各看各的"今天"。
+
+---
+
+## 2. 两个 timezone 概念
+
+| 概念 | 在回答什么 | 谁是真值 | 承载字段 |
+|---|---|---|---|
+| **Scheduling** | "9 点跑"的 9 点是哪个 9 点 | 用户写规则那一刻的意图 | `autopilot_trigger.timezone` |
+| **Viewing** | 我想看的"今天"是哪个日历日 | 当前查看者的偏好 | `user.timezone`(新增) |
+
+**关键论断**:之前代码把"物理位置"和"报表口径"混在 `runtime.timezone` 一个字段上。重构后:
+
+- Scheduling 不动,`autopilot_trigger.timezone` 已经正确。
+- Viewing 由新字段 `user.timezone` 承载。
+- 数据层不再按任何固定 tz 物化 bucket,而是以 UTC 为唯一存储口径,所有报表查询在 read time 按调用方传入的 tz 切日界。
+- `runtime.timezone` 整列删除——见 §2.1。
+
+### 2.1 为什么不要 Operational 层
+
+最初设计有第三个概念 **Operational**(机器物理在哪)。落地盘查后砍掉,两条理由:
+
+**理由一 —— 就算需要 operational tz,`runtime` 也是错的层级。** Operational tz 是**物理机器**的属性,不是 runtime 的属性。同一台机器可以跑多个 runtime,它们共用同一个 OS 时钟,operational tz 必然相同。把 tz 放在 `agent_runtime` 上,等于把一个 machine 级事实复制到同机每一行 runtime——天然的冗余与 drift 风险(同机两个 runtime 的 tz 被改得不一致是无意义的非法状态)。要建模 operational tz,正确归属是 machine 层;而当前 schema 里根本没有 machine 实体,强行放 runtime 层只是把错误固化。
+
+**理由二 —— 它的消费者都不需要 operational 语义。** `runtime.timezone` 今天承担"既是物理 tz 又是报表 tz"的双重职责,但盘查后没有一个读取者真正要"机器物理 tz":
+
+- runtime detail 页的 Daily / Weekly 趋势图、KPI 卡片,通过 `task_usage_daily` 的物化口径间接吃这个 tz——这是**报表口径**语义,不是 operational。而且这些成本/token 数字要和 workspace dashboard 跨页对账,dashboard 下挂多 runtime、多时区,根本不存在"workspace 的 operational tz",可对账量只能统一走 Viewing tz。
+- hour-of-day heatmap(`GetRuntimeUsageByHour` / `GetRuntimeTaskActivity`)看似要"机器作息"属性,但若只让它一个图表走 operational,用户在同一张卡里切 "Daily" ↔ "Heatmap" 会看到同一个"昨天"两个数。它也只能跟 Viewing tz。
+
+autopilot 调度走 `trigger.timezone` 不碰它,daemon 要时钟直接读 OS clock,`TimezoneEditor` 只是编辑它自己。换句话说,凡是真读它的地方都应当是 Viewing tz——operational 语义在整个系统里没有一个真实需求点。
+
+结论:Operational 作为服务端持久化、用户可编辑的字段没有立足点。机器有物理时钟这个**事实**永远存在,但那是 daemon 进程内部的事,不必上 server。`runtime.timezone` 整列由 migration 104 删除。
+
+代价已知且接受:跨 region 团队看一台 SF runtime 的 hour-of-day heatmap 时,按查看者自己的 tz(如 Asia/Shanghai)显示活跃时段,而非机器本地的 9-to-5。对单 region 团队零影响。
+
+---
+
+## 3. 字段定义与 UI 文案
+
+### 3.1 `runtime.timezone` — 已移除
+
+由 migration `104_drop_runtime_timezone` 删除整列。daemon 注册不再上报 host tz(`detectLocalTimezone()` 删除),`PATCH /api/runtimes/:id` 不再接受 `timezone`(只剩 `visibility`),Runtime Detail 页的 timezone editor 删除。理由见 §2.1。
+
+### 3.2 `autopilot_trigger.timezone` — 不动
+
+已经正确。
+
+### 3.3 `user.timezone` — 新增 Viewing 字段
+
+实现见 migration `100_user_timezone`。表名是 `"user"`(单数、保留字需加引号):
+
+```sql
+ALTER TABLE "user"
+ ADD COLUMN timezone TEXT NULL;
+
+COMMENT ON COLUMN "user".timezone IS
+ 'User-preferred IANA timezone for report rendering (Viewing tz). '
+ 'NULL means "use the browser-detected tz at render time". Affects '
+ 'dashboards, charts, and any "today" label shown to this user. Does '
+ 'not affect data materialisation — all rollups remain in UTC.';
+```
+
+`NULL` 是默认值——前端在 NULL 时 fallback 到 `browserTimezone()`。这样新用户零配置就有合理行为。
+
+UI:
+- **Settings → Preferences → Timezone**:dropdown,可选 `(browser)` 或具体 IANA name。
+- Hint:`"Used for dashboards, charts, and any 'today' label shown to you. Other users in your workspaces will see their own timezone."`
+
+### 3.4 不引入 `workspace.timezone`
+
+理由见 §1.2 问题 D。如果未来真有"workspace 默认报表 tz"的需求(例如新成员加入时给一个建议默认值),可以在那时再加,与本 RFC 兼容——`user.timezone` 可作为 `workspace.timezone` 的 override。
+
+### 3.5 Viewing tz 如何到达后端
+
+报表 handler 通过 `Handler.resolveViewingTZ(r)` 解析当前请求该用哪个 tz 渲染,优先级:
+
+1. `?tz=` query param —— 浏览器端 `useViewingTimezone()` 解析后随每个报表请求显式带上。
+2. 已认证用户的 `user.timezone`(query param 缺失时的 cold fallback,会多查一次 `GetUser`)。
+3. `"UTC"` —— 兜底。
+
+非法 IANA 名直接跳过该级、不报错(tz 是显示问题)。浏览器走 (1) 显式 query param 这条热路径,旧客户端 / API client 漏传时由 (2) 服务端读 `user.timezone` 兜底。Handler 拿到 tz 后用 `parseSinceParamInTZ` 把 `days=N` 折算成"查看者本地第 N 天零点"对应的 UTC 瞬间,再连同 `@tz` 一起传给 SQL。
+
+---
+
+## 4. 数据层设计
+
+### 4.1 新表 `task_usage_hourly`
+
+实现见 migration `101_task_usage_hourly_schema`(建表):
+
+```sql
+CREATE TABLE task_usage_hourly (
+ bucket_hour TIMESTAMPTZ NOT NULL, -- UTC, truncated to hour boundary
+ workspace_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ project_id UUID, -- nullable
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ input_tokens BIGINT NOT NULL DEFAULT 0,
+ output_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,
+ task_count BIGINT NOT NULL DEFAULT 0, -- COUNT(DISTINCT task_id)
+ event_count BIGINT NOT NULL DEFAULT 0, -- COUNT(*) of task_usage rows
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_task_usage_hourly_key
+ UNIQUE NULLS NOT DISTINCT
+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
+);
+
+CREATE INDEX idx_task_usage_hourly_workspace_time
+ ON task_usage_hourly (workspace_id, bucket_hour DESC);
+CREATE INDEX idx_task_usage_hourly_runtime_time
+ ON task_usage_hourly (runtime_id, bucket_hour DESC);
+CREATE INDEX idx_task_usage_hourly_workspace_agent_time
+ ON task_usage_hourly (workspace_id, agent_id, bucket_hour DESC);
+CREATE INDEX idx_task_usage_hourly_workspace_project_time
+ ON task_usage_hourly (workspace_id, project_id, bucket_hour DESC)
+ WHERE project_id IS NOT NULL;
+```
+
+**关于字段的几个落地决定**:
+
+- **没有 `cost_micros` 列**。成本不在数据层物化——`task_usage_hourly` 只存 token 计数,PK 里带 `provider`+`model`,客户端按 per-model 定价表算成本。这样定价表更新无需重灌 rollup。
+- **`task_count` 与 `event_count` 两个计数**:`task_count` 是 `COUNT(DISTINCT task_id)`,`event_count` 是 `COUNT(*)`(同一 task 多次 usage 事件)。注意 task 跨多个 hour bucket 时 `task_count` 会按小时重复计——面向用户的"任务数"列优先用 `agent_task_queue` 派生的查询(见 §4.2),hourly 表的 `task_count` 仅作信息参考。
+- **`runtime_id` 为 `NOT NULL`**:`agent_task_queue.runtime_id` 本身带 `NOT NULL` 约束(migration 004),所有建队列的写入路径(含 quick-create)都会带上 runtime,所以 rollup 永远不会产生 no-runtime 的 bucket。`project_id` 可空是因为任务确实可以不挂 project。
+
+migration 101 同时建了两张配套表:
+
+- `task_usage_hourly_rollup_state` —— 单行 watermark 状态表(与 073/084 的 rollup_state 同形)。
+- `task_usage_hourly_dirty` —— 失效队列,承载 `updated_at` watermark 看不到的失效(`task_usage` 的 DELETE、级联 DELETE、`issue.project_id` / `agent_task_queue.runtime_id` 改动导致的重新归属)。**必须配 TTL**,见 §4.4。
+
+**这一张表替换两张现有表**:
+- `task_usage_daily` (migration 073, 082) — 含 runtime_id,物化在 runtime tz
+- `task_usage_dashboard_daily` (migration 084) — 含 agent_id/project_id,物化在 UTC
+
+合并后 PK 同时包含 runtime / agent / project 三个维度,可以从同一张表派生出所有现有视图。
+
+### 4.2 查询模式
+
+Token 类报表查询从 `task_usage_hourly` 派生,按调用方传入的 `@tz` 在查询时折算日界。**成本不在 SQL 里算**——查询只 `SUM` token 列并保留 `model` 维度,成本由客户端按 per-model 定价表折算(所以按日期分组的查询会保留 `model`,按 agent 分组的也是)。
+
+```sql
+-- Workspace dashboard 趋势图 ListDashboardUsageDaily(按 viewer tz 切日,保留 model)
+SELECT DATE(bucket_hour AT TIME ZONE @tz::text) AS date,
+ model,
+ SUM(input_tokens)::bigint AS input_tokens,
+ SUM(output_tokens)::bigint AS output_tokens,
+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(cache_write_tokens)::bigint AS cache_write_tokens,
+ SUM(task_count)::int AS task_count
+FROM task_usage_hourly
+WHERE workspace_id = $1
+ AND bucket_hour >= @since::timestamptz
+ AND (@project_id::uuid IS NULL OR project_id = @project_id)
+GROUP BY DATE(bucket_hour AT TIME ZONE @tz::text), model
+ORDER BY DATE(bucket_hour AT TIME ZONE @tz::text) DESC, model;
+
+-- Runtime detail 趋势图 ListRuntimeUsage(按 viewer tz 切日,tz 来自 user 不是 runtime)
+SELECT DATE(bucket_hour AT TIME ZONE @tz::text) AS date,
+ provider, model,
+ SUM(input_tokens)::bigint AS input_tokens,
+ ...
+FROM task_usage_hourly
+WHERE runtime_id = $1
+ AND bucket_hour >= @since::timestamptz
+GROUP BY DATE(bucket_hour AT TIME ZONE @tz::text), provider, model
+ORDER BY DATE(bucket_hour AT TIME ZONE @tz::text) DESC, provider, model;
+
+-- Per-agent 视图 ListDashboardUsageByAgent / ListRuntimeUsageByAgent
+-- 不按日期分组 → 不需要 @tz,只用 @since 截断(@since 已是 viewer tz 折算后的 UTC 瞬间)。
+SELECT agent_id, model,
+ SUM(input_tokens)::bigint AS input_tokens,
+ ...
+FROM task_usage_hourly
+WHERE workspace_id = $1
+ AND bucket_hour >= @since::timestamptz
+GROUP BY agent_id, model
+ORDER BY agent_id, model;
+```
+
+**两类查询不走 `task_usage_hourly`**:
+
+- **Time / Tasks 指标**(dashboard 的"时长 / 任务数"标签页)由独立查询 `ListDashboardRunTimeDaily` / `ListDashboardAgentRunTime` 直接打 `agent_task_queue`,按 `completed_at AT TIME ZONE @tz` 切日——任务时长来自队列的 `started_at`/`completed_at`,不是 token rollup 能表达的。它们同样吃 `@tz`,保证 Tokens/Cost/Time/Tasks 四个标签页的日界一致。
+- **Runtime hour-of-day Heatmap**(`GetRuntimeUsageByHour` / `GetRuntimeTaskActivity`)仍直接扫原始 `task_usage` / `agent_task_queue`,按 **viewer tz**(`resolveViewingTZ` 解析出的 `@tz`)做 `EXTRACT(HOUR FROM ... AT TIME ZONE @tz)`。Heatmap 窗口小(单 runtime、近 30/90d),raw 扫描足够快,没有必要从 hourly 表派生。
+
+### 4.3 性能预估
+
+单 workspace 90d 窗口的 `task_usage_hourly` 行数:
+
+| 工况 | 行数估算 | 趋势图查询代价 |
+|---|---|---|
+| 小(5 agent × 2 model × 2 active hour × 90d) | ~1.8k | <5ms |
+| 中(5 agent × 2 model × 8 active hour × 90d) | ~7.2k | <10ms |
+| 大(5 agent × 2 model × 16 active hour × 90d) | ~14.4k | ~15ms |
+| 巨大(20 agent × 5 model × 16 active hour × 90d) | ~144k | ~50ms |
+
+和现有 daily rollup 在同一档。Leaderboard / per-agent / per-project 视图同样指标。
+
+### 4.4 Rollup worker 改造
+
+现有两张 rollup 表的写入逻辑合并成一条管线,实现见 migration `102_task_usage_hourly_pipeline`(触发器 + 窗口函数 + 失效队列 TTL + pg_cron 调度):
+
+- 源数据扫描不变(仍然扫 `task_usage` 增量 + 失效队列)。`bucket_hour` 用 `task_usage_hour_bucket(tu.created_at)`(UTC 整点截断)。
+- Upsert 目标从两张 daily 表改为一张 `task_usage_hourly`。
+- 失效队列维度由 `(bucket_date, …)` 改为 `(bucket_hour, …)`(`task_usage_hourly_dirty`),由 `task_usage` / `agent_task_queue` / `issue` 上的触发器写入。**必须配 TTL(保留 7 天)**,否则脏行在密集工况下无界增长——这是整个设计最容易漏的正确性要求(hourly 粒度把脏面比 daily 放大了 ~24×)。
+- 调度入口 `rollup_task_usage_hourly()` 由 pg_cron 周期触发:取 advisory lock → 从 `task_usage_hourly_rollup_state` 读 watermark → 调 `rollup_task_usage_hourly_window(from, to)` 重算脏 bucket → 推进 watermark → 释放锁后跑 `prune_task_usage_hourly_dirty()`。单 tick 窗口上限 1 天,watermark 落后时分多次 tick 追平,不会一条语句锁表重算多周。
+
+源表扫描是 worker 的主要开销,目标表换粒度只让单 tick 多几十 ms upsert,不会成倍增长。
+
+### 4.5 Migration 082 的副作用消除
+
+当前 `runtime.timezone` 的 PATCH 处理(migration 082 + 现有 handler)会触发该 runtime 的整张 `task_usage_daily` 重新物化——因为 `bucket_date` 含了 tz。
+
+新方案下 `bucket_hour` 永远是 UTC,**`runtime.timezone` 改变不再触发任何数据层操作**。改 tz 立即生效,零 backfill。这同时修掉了:
+
+- 改 tz 期间的 race condition(旧 bucket 还没重灌完,新查询已经按新 tz 渲染)。
+- daemon 第一次注册时探测到非 UTC 的 tz 但历史 rollup 还是 UTC 的尴尬过渡期。
+
+---
+
+## 5. UI / UX 影响
+
+### 5.1 Runtime Detail 页
+
+| 组件 | 重构前 tz 来源 | 重构后 tz 来源 |
+|---|---|---|
+| Daily / Weekly 趋势图 | `runtime.timezone` | `user.timezone ?? browserTimezone()` |
+| KPI 卡片 | `runtime.timezone`(隐式) | `user.timezone ?? browserTimezone()` |
+| 日历活跃热力图 | `runtime.timezone` 锚点 + viewer-tz 数据(不一致 bug) | `user.timezone ?? browserTimezone()`(锚点与数据统一) |
+| Hour-of-day Heatmap | `runtime.timezone` | `user.timezone ?? browserTimezone()` |
+| Timezone editor | 写 `runtime.timezone` | **删除** |
+
+**用户可感知的行为变化**:
+
+- Runtime Detail 页所有图表统一跟随 viewer 自己的 tz;页面上不再有任何 runtime 级 tz 控件。
+- 想换报表 tz 的用户去 Settings → Preferences 改一次,所有 workspace / runtime 的报表立刻全跟着变。
+- 跨 region 团队:hour-of-day heatmap 按查看者 tz 显示活跃时段(已知且接受的取舍,见 §2.1)。
+
+### 5.2 Workspace Usage 页
+
+恢复"按 viewing tz 渲染"的能力,但**不放页面级 picker**。理由:
+
+- Picker 当年被加上去就是因为没有持久化的 viewing tz 概念。现在有了 `user.timezone`,picker 的诉求被 Preferences 替代。
+- 页面级 picker 容易让用户误以为"这是一个 view-state",但 viewing tz 是全应用属性,不是单页设置。
+- 减少 UI 控件 = 减少认知负担。
+
+`packages/views/dashboard/components/dashboard-page.tsx` 里的 `WEEK_TZ = "UTC"` 改成 `useViewingTimezone()`(hook 见 `packages/views/common/use-viewing-timezone.ts`),相应的解释性注释删除。
+
+### 5.3 Preferences 页
+
+新增一个 Timezone setting,和现有的语言 / 主题等并列。
+
+---
+
+## 6. 实施
+
+> 产品尚未上线,无存量用户需保护,全部变更作为一组迁移一次性交付——旧的 daily 管线在同一分支里直接拆除,不保留共存期。
+
+整套变更落在分支 `feat/timezone-architecture`,migration 100–104:
+
+| Migration | 内容 |
+|---|---|
+| `100_user_timezone` | 加 `"user".timezone` 列(nullable) |
+| `101_task_usage_hourly_schema` | 建 `task_usage_hourly` + `task_usage_hourly_rollup_state` + `task_usage_hourly_dirty` + 索引 |
+| `102_task_usage_hourly_pipeline` | 失效触发器、`rollup_task_usage_hourly_window` 窗口函数、`prune_task_usage_hourly_dirty()` 失效队列 TTL、带单日 cap 与 prune 的 `rollup_task_usage_hourly()` cron 入口、pg_cron 调度 |
+| `103_drop_legacy_daily_rollups` | 拆掉 `task_usage_daily` / `task_usage_dashboard_daily` 两条旧管线(表、函数、触发器、pg_cron 任务) |
+| `104_drop_runtime_timezone` | 删除 `agent_runtime.timezone` 列(Operational 层移除,见 §2.1) |
+
+配套的代码侧改动:
+
+- **数据回填**:一次性命令 `cmd/backfill_task_usage_hourly`,按 workspace 切片把历史 `task_usage` 灌进新表。旧的 `cmd/backfill_task_usage_daily` / `cmd/backfill_task_usage_dashboard_daily` 已删除。
+- **查询切换**:后端所有报表查询迁到 `task_usage_hourly`(或 Time/Tasks 的 `agent_task_queue` 查询),统一接受 `@tz`;`UseDailyRollupForDashboard` / `UseDailyRollupForRuntimeUsage` 等 feature flag 与旧的 raw-scan / daily-rollup 双查询路径一并删除。
+- **前端打通**:`useViewingTimezone()` hook 解析 viewer tz,报表组件随请求带 `?tz=`;`dashboard-page.tsx` 的 `WEEK_TZ = "UTC"` 改为 `useViewingTimezone()`,原 UTC-lock 解释性注释删除。
+- **UI 文案**:Preferences 新增 Timezone setting。Runtime Detail 页的 timezone editor 整体删除。
+- **runtime tz 移除**:`PATCH /api/runtimes/:id` 的 `timezone` 字段删除,该端点只剩 `visibility`;daemon 注册不再上报 host tz;`agent_runtime.timezone` 列由 migration 104 删除。
+
+---
+
+## 7. Open questions / Risks
+
+### 7.1 Risks
+
+- **Invalidation queue TTL 是必做**。如果忘记加,密集工况下 queue 会无界增长。
+- **Hourly rollup backfill 期间的源表 read pressure**。按 workspace 切片、低峰期跑,预期 OK,但需要提前给 DB 团队打招呼。
+- **DST 当天的 23h/25h "日"**。`DATE(bucket_hour AT TIME ZONE @tz)` 会正确处理,但前端任何"一天 = 24 小时"的硬编码偏移逻辑要测一遍 DST 边界。
+- **现有 `runtime.timezone` 的 PATCH endpoint 行为变了**。改完不再触发 backfill——这是好事,但 API 文档和 changelog 要写清楚,避免下游集成误判。
+
+### 7.2 Open question
+
+- **Trigger 的 timezone 默认值**?目前用户必须手动选;可以默认 `user.timezone`,但用户写 trigger 时的 viewing tz 和 trigger 实际跑的 tz 是两件事,需要产品决策。
+
+### 7.3 非目标
+
+- **不做** workspace 级 tz 设置:跨 region 团队两个成员各自正确的"今天"不同,workspace 级 tz 必让其中一方看错位报表。
+- **不做** 预物化多 tz rollup:IANA tz 列表有 ~600 个无法穷举、DST 需逐 tz 维护,而 hourly rollup 已经够快。
+- **不做** issue / comment / inbox 等列表的 tz 切换——它们已经隐式用浏览器 tz,本 RFC 不动。后续如果要让这些也跟 `user.timezone`,是独立的 follow-up。
+
+---
+
+## 8. 决策汇总
+
+| 决策点 | 选择 |
+|---|---|
+| Timezone 概念分层 | Scheduling / Viewing 两层(Operational 经盘查后移除) |
+| `runtime.timezone` 角色 | ❌ 整列删除(migration 104) |
+| `user.timezone` 是否新增 | ✅ 新增,nullable,默认 fallback 到 browser |
+| `workspace.timezone` 是否新增 | ❌ 不引入 |
+| 数据层物化口径 | 统一 UTC, hourly grain |
+| Rollup 表合并 | `task_usage_daily` + `task_usage_dashboard_daily` → `task_usage_hourly` |
+| 报表 tz 切换粒度 | 全局 per-user(Preferences),不做 per-view picker |
+| hour-of-day heatmap tz | viewer tz(不再用机器物理 tz) |
diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.ts
index b0b656d9e9..bb546cfd09 100644
--- a/packages/core/agents/derive-presence.test.ts
+++ b/packages/core/agents/derive-presence.test.ts
@@ -50,7 +50,6 @@ function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
metadata: {},
owner_id: null,
visibility: "private",
- 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 7052db0408..8cff40894b 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -132,6 +132,10 @@ import {
ListWebhookDeliveriesResponseSchema,
OnboardingNoRuntimeBootstrapResponseSchema,
OnboardingRuntimeBootstrapResponseSchema,
+ RuntimeHourlyActivityListSchema,
+ RuntimeUsageByAgentListSchema,
+ RuntimeUsageByHourListSchema,
+ RuntimeUsageListSchema,
SquadMemberStatusListResponseSchema,
SubscribersListSchema,
TimelineEntriesSchema,
@@ -393,10 +397,13 @@ export class ApiClient {
completion_path?: OnboardingCompletionPath;
workspace_id?: string;
}): Promise<User> {
- return this.fetch("/api/me/onboarding/complete", {
+ const raw = await this.fetch<unknown>("/api/me/onboarding/complete", {
method: "POST",
body: payload ? JSON.stringify(payload) : undefined,
});
+ return parseWithFallback(raw, UserSchema, EMPTY_USER, {
+ endpoint: "POST /api/me/onboarding/complete",
+ });
}
async bootstrapOnboardingRuntime(payload: {
@@ -440,19 +447,25 @@ export class ApiClient {
email: string;
reason?: string;
}): Promise<User> {
- return this.fetch("/api/me/onboarding/cloud-waitlist", {
+ const raw = await this.fetch<unknown>("/api/me/onboarding/cloud-waitlist", {
method: "POST",
body: JSON.stringify(payload),
});
+ return parseWithFallback(raw, UserSchema, EMPTY_USER, {
+ endpoint: "POST /api/me/onboarding/cloud-waitlist",
+ });
}
async patchOnboarding(payload: {
questionnaire?: Record<string, unknown>;
}): Promise<User> {
- return this.fetch("/api/me/onboarding", {
+ const raw = await this.fetch<unknown>("/api/me/onboarding", {
method: "PATCH",
body: JSON.stringify(payload),
});
+ return parseWithFallback(raw, UserSchema, EMPTY_USER, {
+ endpoint: "PATCH /api/me/onboarding",
+ });
}
async updateMe(data: UpdateMeRequest): Promise<User> {
@@ -812,7 +825,7 @@ export class ApiClient {
async updateRuntime(
runtimeId: string,
- patch: { timezone?: string; visibility?: "private" | "public" },
+ patch: { visibility?: "private" | "public" },
): Promise<AgentRuntime> {
return this.fetch(`/api/runtimes/${runtimeId}`, {
method: "PATCH",
@@ -820,32 +833,77 @@ export class ApiClient {
});
}
- async getRuntimeUsage(runtimeId: string, params?: { days?: number }): Promise<RuntimeUsage[]> {
+ async getRuntimeUsage(
+ runtimeId: string,
+ params?: { days?: number; tz?: string },
+ ): Promise<RuntimeUsage[]> {
const search = new URLSearchParams();
if (params?.days) search.set("days", String(params.days));
- return this.fetch(`/api/runtimes/${runtimeId}/usage?${search}`);
+ // `tz` drives the calendar-day boundary for the trend chart (Viewing
+ // layer). Caller-supplied; the backend falls back to user.timezone /
+ // UTC if omitted.
+ if (params?.tz) search.set("tz", params.tz);
+ const raw = await this.fetch<unknown>(
+ `/api/runtimes/${runtimeId}/usage?${search}`,
+ );
+ return parseWithFallback<RuntimeUsage[]>(raw, RuntimeUsageListSchema, [], {
+ endpoint: "GET /api/runtimes/:id/usage",
+ });
}
- async getRuntimeTaskActivity(runtimeId: string): Promise<RuntimeHourlyActivity[]> {
- return this.fetch(`/api/runtimes/${runtimeId}/activity`);
+ async getRuntimeTaskActivity(
+ runtimeId: string,
+ params?: { tz?: string },
+ ): Promise<RuntimeHourlyActivity[]> {
+ // Hour-of-day heatmap follows the viewer's tz, like the other reports on
+ // this page. Pass the viewer's IANA zone so the server buckets correctly.
+ const search = new URLSearchParams();
+ if (params?.tz) search.set("tz", params.tz);
+ const raw = await this.fetch<unknown>(
+ `/api/runtimes/${runtimeId}/activity?${search}`,
+ );
+ return parseWithFallback<RuntimeHourlyActivity[]>(
+ raw,
+ RuntimeHourlyActivityListSchema,
+ [],
+ { endpoint: "GET /api/runtimes/:id/activity" },
+ );
}
async getRuntimeUsageByAgent(
runtimeId: string,
- params?: { days?: number },
+ params?: { days?: number; tz?: string },
): Promise<RuntimeUsageByAgent[]> {
const search = new URLSearchParams();
if (params?.days) search.set("days", String(params.days));
- return this.fetch(`/api/runtimes/${runtimeId}/usage/by-agent?${search}`);
+ if (params?.tz) search.set("tz", params.tz);
+ const raw = await this.fetch<unknown>(
+ `/api/runtimes/${runtimeId}/usage/by-agent?${search}`,
+ );
+ return parseWithFallback<RuntimeUsageByAgent[]>(
+ raw,
+ RuntimeUsageByAgentListSchema,
+ [],
+ { endpoint: "GET /api/runtimes/:id/usage/by-agent" },
+ );
}
async getRuntimeUsageByHour(
runtimeId: string,
- params?: { days?: number },
+ params?: { days?: number; tz?: string },
): Promise<RuntimeUsageByHour[]> {
const search = new URLSearchParams();
if (params?.days) search.set("days", String(params.days));
- return this.fetch(`/api/runtimes/${runtimeId}/usage/by-hour?${search}`);
+ if (params?.tz) search.set("tz", params.tz);
+ const raw = await this.fetch<unknown>(
+ `/api/runtimes/${runtimeId}/usage/by-hour?${search}`,
+ );
+ return parseWithFallback<RuntimeUsageByHour[]>(
+ raw,
+ RuntimeUsageByHourListSchema,
+ [],
+ { endpoint: "GET /api/runtimes/:id/usage/by-hour" },
+ );
}
// ---------------------------------------------------------------------------
@@ -856,11 +914,12 @@ export class ApiClient {
// ---------------------------------------------------------------------------
async getDashboardUsageDaily(
- params: { days?: number; project_id?: string | null },
+ params: { days?: number; project_id?: string | null; tz?: string },
): Promise<DashboardUsageDaily[]> {
const search = new URLSearchParams();
if (params.days) search.set("days", String(params.days));
if (params.project_id) search.set("project_id", params.project_id);
+ if (params.tz) search.set("tz", params.tz);
const raw = await this.fetch<unknown>(`/api/dashboard/usage/daily?${search}`);
return parseWithFallback<DashboardUsageDaily[]>(
raw,
@@ -871,11 +930,12 @@ export class ApiClient {
}
async getDashboardUsageByAgent(
- params: { days?: number; project_id?: string | null },
+ params: { days?: number; project_id?: string | null; tz?: string },
): Promise<DashboardUsageByAgent[]> {
const search = new URLSearchParams();
if (params.days) search.set("days", String(params.days));
if (params.project_id) search.set("project_id", params.project_id);
+ if (params.tz) search.set("tz", params.tz);
const raw = await this.fetch<unknown>(`/api/dashboard/usage/by-agent?${search}`);
return parseWithFallback<DashboardUsageByAgent[]>(
raw,
@@ -886,11 +946,14 @@ export class ApiClient {
}
async getDashboardAgentRunTime(
- params: { days?: number; project_id?: string | null },
+ params: { days?: number; project_id?: string | null; tz?: string },
): Promise<DashboardAgentRunTime[]> {
const search = new URLSearchParams();
if (params.days) search.set("days", String(params.days));
if (params.project_id) search.set("project_id", params.project_id);
+ // `tz` aligns the "last N days" cutoff with the viewer's calendar,
+ // matching the per-agent token card.
+ if (params.tz) search.set("tz", params.tz);
const raw = await this.fetch<unknown>(`/api/dashboard/agent-runtime?${search}`);
return parseWithFallback<DashboardAgentRunTime[]>(
raw,
@@ -901,11 +964,14 @@ export class ApiClient {
}
async getDashboardRunTimeDaily(
- params: { days?: number; project_id?: string | null },
+ params: { days?: number; project_id?: string | null; tz?: string },
): Promise<DashboardRunTimeDaily[]> {
const search = new URLSearchParams();
if (params.days) search.set("days", String(params.days));
if (params.project_id) search.set("project_id", params.project_id);
+ // `tz` cuts the day buckets in the viewer's calendar so Time / Tasks
+ // align with the Cost / Tokens charts.
+ if (params.tz) search.set("tz", params.tz);
const raw = await this.fetch<unknown>(`/api/dashboard/runtime/daily?${search}`);
return parseWithFallback<DashboardRunTimeDaily[]>(
raw,
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index fdac8748bc..7a0e254b17 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1,5 +1,17 @@
import { describe, expect, it } from "vitest";
-import { DuplicateIssueErrorBodySchema } from "./schemas";
+import {
+ DashboardAgentRunTimeListSchema,
+ DashboardUsageByAgentListSchema,
+ DashboardUsageDailyListSchema,
+ DuplicateIssueErrorBodySchema,
+ EMPTY_USER,
+ RuntimeHourlyActivityListSchema,
+ RuntimeUsageByAgentListSchema,
+ RuntimeUsageByHourListSchema,
+ RuntimeUsageListSchema,
+ UserSchema,
+} from "./schemas";
+import { parseWithFallback } from "./schema";
// The duplicate-issue branch in create-issue.tsx feeds ApiError.body
// (typed as `unknown`) through this schema. Any future server drift that
@@ -49,3 +61,106 @@ describe("DuplicateIssueErrorBodySchema", () => {
expect(DuplicateIssueErrorBodySchema.safeParse(without).success).toBe(true);
});
});
+
+// `user.timezone` (Viewing tz) was added in the timezone-architecture RFC.
+// A desktop build older than the server — or a server predating the
+// `user.timezone` migration — will return a `/api/me` body with no
+// `timezone` key. The schema must not fail closed on that: the field
+// defaults to `null`, which the frontend resolves to the browser-detected
+// tz at render time.
+describe("UserSchema timezone drift", () => {
+ const base = {
+ id: "11111111-1111-1111-1111-111111111111",
+ name: "Ada",
+ email: "[email protected]",
+ };
+
+ it("defaults timezone to null when the field is absent", () => {
+ const parsed = UserSchema.parse(base);
+ expect(parsed.timezone).toBe(null);
+ });
+
+ it("preserves an explicit IANA timezone", () => {
+ const parsed = UserSchema.parse({ ...base, timezone: "Asia/Tokyo" });
+ expect(parsed.timezone).toBe("Asia/Tokyo");
+ });
+
+ it("accepts an explicit null timezone", () => {
+ const parsed = UserSchema.parse({ ...base, timezone: null });
+ expect(parsed.timezone).toBe(null);
+ });
+
+ // Wrong-type drift: a future server bug sending `timezone` as a number
+ // must not throw into the UI. parseWithFallback degrades the whole user
+ // object to the explicit fallback (EMPTY_USER) so /api/me callers keep a
+ // valid shape instead of white-screening.
+ it("falls back to EMPTY_USER when timezone is the wrong type", () => {
+ const parsed = parseWithFallback(
+ { ...base, timezone: 42 },
+ UserSchema,
+ EMPTY_USER,
+ { endpoint: "GET /api/me" },
+ );
+ expect(parsed).toBe(EMPTY_USER);
+ });
+});
+
+// The workspace dashboard and runtime-detail pages were re-pointed at the
+// unified `task_usage_hourly` rollup. Every numeric field drives chart /
+// KPI math, and string keys (date / agent_id / model) bucket the series.
+// The contract these schemas must hold: a row missing a field degrades
+// that field to a sane default rather than dropping the WHOLE array to
+// the `[]` fallback — one drifted row must not blank the entire chart.
+describe("dashboard + runtime usage schema drift", () => {
+ it("coerces a missing numeric field to 0 instead of dropping the array", () => {
+ const parsed = DashboardUsageDailyListSchema.parse([
+ { date: "2026-05-19", model: "claude-opus-4-7", input_tokens: 100 },
+ ]);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.output_tokens).toBe(0);
+ expect(parsed[0]?.cache_read_tokens).toBe(0);
+ expect(parsed[0]?.cache_write_tokens).toBe(0);
+ });
+
+ it("coerces a missing date key to \"\" so the rest of the series survives", () => {
+ const parsed = DashboardUsageDailyListSchema.parse([
+ { model: "claude-opus-4-7", input_tokens: 5 },
+ ]);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.date).toBe("");
+ });
+
+ it("coerces a missing agent_id key to \"\" for the agent-runtime panel", () => {
+ const parsed = DashboardAgentRunTimeListSchema.parse([
+ { total_seconds: 42, task_count: 3, failed_count: 0 },
+ ]);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.agent_id).toBe("");
+ });
+
+ it("coerces a missing agent_id key to \"\" for the usage-by-agent panel", () => {
+ const parsed = DashboardUsageByAgentListSchema.parse([
+ { model: "claude-opus-4-7", input_tokens: 7 },
+ ]);
+ expect(parsed[0]?.agent_id).toBe("");
+ });
+
+ it("coerces missing fields on every runtime usage schema", () => {
+ expect(RuntimeUsageListSchema.parse([{ date: "2026-05-19" }])[0]?.input_tokens).toBe(0);
+ expect(RuntimeHourlyActivityListSchema.parse([{ hour: 9 }])[0]?.count).toBe(0);
+ expect(RuntimeUsageByAgentListSchema.parse([{ model: "x" }])[0]?.agent_id).toBe("");
+ expect(RuntimeUsageByHourListSchema.parse([{ hour: 9 }])[0]?.model).toBe("");
+ });
+
+ it("rejects a non-array body so parseWithFallback can return its fallback", () => {
+ expect(DashboardUsageDailyListSchema.safeParse(null).success).toBe(false);
+ expect(RuntimeUsageListSchema.safeParse({ rows: [] }).success).toBe(false);
+ });
+
+ it("keeps unknown server-side fields via .loose()", () => {
+ const parsed = RuntimeUsageListSchema.parse([
+ { date: "2026-05-19", region: "us-east" },
+ ]);
+ expect((parsed[0] as Record<string, unknown>).region).toBe("us-east");
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6a5b59f1ed..57b99bbe4a 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -216,13 +216,14 @@ export const OnboardingNoRuntimeBootstrapResponseSchema = z.object({
// The dashboard hits three independent rollup endpoints. Each returns a flat
// array, and every field is consumed by chart / KPI math — a missing number
// silently degrades to NaN downstream, so we coerce missing numbers to 0.
-// String fields stay lenient (no enum narrowing) to survive future model /
-// agent ID drift.
+// String fields default to "" (no enum narrowing) to survive future model /
+// agent ID drift, and so a single null from tz-aware SQL bucketing fails
+// only that row instead of dropping the whole array to the `[]` fallback.
// ---------------------------------------------------------------------------
const DashboardUsageDailySchema = z.object({
- date: z.string(),
- model: z.string(),
+ date: z.string().default(""),
+ model: z.string().default(""),
input_tokens: z.number().default(0),
output_tokens: z.number().default(0),
cache_read_tokens: z.number().default(0),
@@ -233,8 +234,8 @@ const DashboardUsageDailySchema = z.object({
export const DashboardUsageDailyListSchema = z.array(DashboardUsageDailySchema);
const DashboardUsageByAgentSchema = z.object({
- agent_id: z.string(),
- model: z.string(),
+ agent_id: z.string().default(""),
+ model: z.string().default(""),
input_tokens: z.number().default(0),
output_tokens: z.number().default(0),
cache_read_tokens: z.number().default(0),
@@ -245,7 +246,7 @@ const DashboardUsageByAgentSchema = z.object({
export const DashboardUsageByAgentListSchema = z.array(DashboardUsageByAgentSchema);
const DashboardAgentRunTimeSchema = z.object({
- agent_id: z.string(),
+ agent_id: z.string().default(""),
total_seconds: z.number().default(0),
task_count: z.number().default(0),
failed_count: z.number().default(0),
@@ -254,7 +255,7 @@ const DashboardAgentRunTimeSchema = z.object({
export const DashboardAgentRunTimeListSchema = z.array(DashboardAgentRunTimeSchema);
const DashboardRunTimeDailySchema = z.object({
- date: z.string(),
+ date: z.string().default(""),
total_seconds: z.number().default(0),
task_count: z.number().default(0),
failed_count: z.number().default(0),
@@ -262,6 +263,57 @@ const DashboardRunTimeDailySchema = z.object({
export const DashboardRunTimeDailyListSchema = z.array(DashboardRunTimeDailySchema);
+// ---------------------------------------------------------------------------
+// Runtime usage schemas — the runtime-detail page's four usage endpoints
+// (`/api/runtimes/:id/usage*`). Same leniency rules as the dashboard
+// schemas above: numbers default to 0, strings to "", `.loose()` passes
+// unknown fields.
+// ---------------------------------------------------------------------------
+
+const RuntimeUsageSchema = z.object({
+ runtime_id: z.string().default(""),
+ date: z.string().default(""),
+ provider: z.string().default(""),
+ model: z.string().default(""),
+ input_tokens: z.number().default(0),
+ output_tokens: z.number().default(0),
+ cache_read_tokens: z.number().default(0),
+ cache_write_tokens: z.number().default(0),
+}).loose();
+
+export const RuntimeUsageListSchema = z.array(RuntimeUsageSchema);
+
+const RuntimeHourlyActivitySchema = z.object({
+ hour: z.number().default(0),
+ count: z.number().default(0),
+}).loose();
+
+export const RuntimeHourlyActivityListSchema = z.array(RuntimeHourlyActivitySchema);
+
+const RuntimeUsageByAgentSchema = z.object({
+ agent_id: z.string().default(""),
+ model: z.string().default(""),
+ input_tokens: z.number().default(0),
+ output_tokens: z.number().default(0),
+ cache_read_tokens: z.number().default(0),
+ cache_write_tokens: z.number().default(0),
+ task_count: z.number().default(0),
+}).loose();
+
+export const RuntimeUsageByAgentListSchema = z.array(RuntimeUsageByAgentSchema);
+
+const RuntimeUsageByHourSchema = z.object({
+ hour: z.number().default(0),
+ model: z.string().default(""),
+ input_tokens: z.number().default(0),
+ output_tokens: z.number().default(0),
+ cache_read_tokens: z.number().default(0),
+ cache_write_tokens: z.number().default(0),
+ task_count: z.number().default(0),
+}).loose();
+
+export const RuntimeUsageByHourListSchema = z.array(RuntimeUsageByHourSchema);
+
// ---------------------------------------------------------------------------
// Agent template catalog — `/api/agent-templates*` and the
// create-from-template response. The desktop app's create-agent picker
@@ -506,6 +558,7 @@ export const UserSchema = z.object({
starter_content_state: z.string().nullable().default(null),
language: z.string().nullable().default(null),
profile_description: z.string().default(""),
+ timezone: z.string().nullable().default(null),
created_at: z.string().default(""),
updated_at: z.string().default(""),
}).loose();
@@ -520,6 +573,7 @@ export const EMPTY_USER: User = {
starter_content_state: null,
language: null,
profile_description: "",
+ timezone: null,
created_at: "",
updated_at: "",
};
diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.ts
index d58c26b67f..dba26de556 100644
--- a/packages/core/dashboard/queries.ts
+++ b/packages/core/dashboard/queries.ts
@@ -1,45 +1,55 @@
import { queryOptions } from "@tanstack/react-query";
import { api } from "../api";
-// Workspace dashboard query options. All three endpoints share the same
-// (wsId, days, projectId) key shape so workspace switching, time-range
-// changes, and the project filter each invalidate the cache cleanly.
-//
-// The cache key includes `wsId` explicitly: TanStack Query already isolates
-// per workspace via the key, but threading wsId into the queryFn lets
-// callers fail fast (return [] on empty wsId) instead of issuing a request
-// the server would reject.
-//
-// `projectId` is normalised to `null` (not undefined / "all") so the
-// queryKey shape is stable across renders even when the dropdown sits on
-// "all projects".
-
export const dashboardKeys = {
all: (wsId: string) => ["dashboard", wsId] as const,
- daily: (wsId: string, days: number, projectId: string | null) =>
- [...dashboardKeys.all(wsId), "daily", days, projectId] as const,
- byAgent: (wsId: string, days: number, projectId: string | null) =>
- [...dashboardKeys.all(wsId), "by-agent", days, projectId] as const,
- agentRuntime: (wsId: string, days: number, projectId: string | null) =>
- [...dashboardKeys.all(wsId), "agent-runtime", days, projectId] as const,
- runTimeDaily: (wsId: string, days: number, projectId: string | null) =>
- [...dashboardKeys.all(wsId), "runtime-daily", days, projectId] as const,
+ daily: (
+ wsId: string,
+ days: number,
+ projectId: string | null,
+ tz: string,
+ ) => [...dashboardKeys.all(wsId), "daily", days, projectId, tz] as const,
+ byAgent: (
+ wsId: string,
+ days: number,
+ projectId: string | null,
+ tz: string,
+ ) => [...dashboardKeys.all(wsId), "by-agent", days, projectId, tz] as const,
+ agentRuntime: (
+ wsId: string,
+ days: number,
+ projectId: string | null,
+ tz: string,
+ ) => [...dashboardKeys.all(wsId), "agent-runtime", days, projectId, tz] as const,
+ runTimeDaily: (
+ wsId: string,
+ days: number,
+ projectId: string | null,
+ tz: string,
+ ) => [...dashboardKeys.all(wsId), "runtime-daily", days, projectId, tz] as const,
};
-// 60s staleTime matches the per-runtime usage queries — the data is rollup-
-// driven on the server (5-min rollup cadence) and the dashboard isn't a
-// real-time view, so background refetches every minute are plenty.
+// 5-min rollup cadence on the server, 60s background refetch on the client.
const STALE_TIME = 60 * 1000;
+// `tz` participates in every dashboard key so a Preferences change
+// repoints the cache. All four series — token rollups and the
+// atq.completed_at-based run-time series — slice their day boundary in
+// the viewer's tz, so the four dashboard tabs always agree.
export function dashboardUsageDailyOptions(
wsId: string,
days: number,
projectId: string | null,
+ tz: string,
) {
return queryOptions({
- queryKey: dashboardKeys.daily(wsId, days, projectId),
+ queryKey: dashboardKeys.daily(wsId, days, projectId, tz),
queryFn: () =>
- api.getDashboardUsageDaily({ days, project_id: projectId ?? undefined }),
+ api.getDashboardUsageDaily({
+ days,
+ project_id: projectId ?? undefined,
+ tz,
+ }),
enabled: !!wsId,
staleTime: STALE_TIME,
});
@@ -49,11 +59,16 @@ export function dashboardUsageByAgentOptions(
wsId: string,
days: number,
projectId: string | null,
+ tz: string,
) {
return queryOptions({
- queryKey: dashboardKeys.byAgent(wsId, days, projectId),
+ queryKey: dashboardKeys.byAgent(wsId, days, projectId, tz),
queryFn: () =>
- api.getDashboardUsageByAgent({ days, project_id: projectId ?? undefined }),
+ api.getDashboardUsageByAgent({
+ days,
+ project_id: projectId ?? undefined,
+ tz,
+ }),
enabled: !!wsId,
staleTime: STALE_TIME,
});
@@ -63,11 +78,16 @@ export function dashboardAgentRunTimeOptions(
wsId: string,
days: number,
projectId: string | null,
+ tz: string,
) {
return queryOptions({
- queryKey: dashboardKeys.agentRuntime(wsId, days, projectId),
+ queryKey: dashboardKeys.agentRuntime(wsId, days, projectId, tz),
queryFn: () =>
- api.getDashboardAgentRunTime({ days, project_id: projectId ?? undefined }),
+ api.getDashboardAgentRunTime({
+ days,
+ project_id: projectId ?? undefined,
+ tz,
+ }),
enabled: !!wsId,
staleTime: STALE_TIME,
});
@@ -77,11 +97,16 @@ export function dashboardRunTimeDailyOptions(
wsId: string,
days: number,
projectId: string | null,
+ tz: string,
) {
return queryOptions({
- queryKey: dashboardKeys.runTimeDaily(wsId, days, projectId),
+ queryKey: dashboardKeys.runTimeDaily(wsId, days, projectId, tz),
queryFn: () =>
- api.getDashboardRunTimeDaily({ days, project_id: projectId ?? undefined }),
+ api.getDashboardRunTimeDaily({
+ days,
+ project_id: projectId ?? undefined,
+ tz,
+ }),
enabled: !!wsId,
staleTime: STALE_TIME,
});
diff --git a/packages/core/permissions/rules.test.ts b/packages/core/permissions/rules.test.ts
index 63d0b7c425..b23a174c07 100644
--- a/packages/core/permissions/rules.test.ts
+++ b/packages/core/permissions/rules.test.ts
@@ -94,7 +94,6 @@ function makeRuntime(ownerId: string | null): RuntimeDevice {
metadata: {},
owner_id: ownerId,
visibility: "private",
- 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 1e8e42985d..c6d4ac1103 100644
--- a/packages/core/runtimes/derive-health.test.ts
+++ b/packages/core/runtimes/derive-health.test.ts
@@ -18,7 +18,6 @@ function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
metadata: {},
owner_id: null,
visibility: "private",
- 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 645c622654..ee3af2a0b8 100644
--- a/packages/core/runtimes/mutations.ts
+++ b/packages/core/runtimes/mutations.ts
@@ -12,12 +12,8 @@ export function useDeleteRuntime(wsId: string) {
});
}
-// useUpdateRuntime patches editable fields on a runtime (timezone, visibility).
-// 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. A
-// visibility change only needs the runtime list to refetch so the picker
-// disabled-state recomputes.
+// useUpdateRuntime patches editable fields on a runtime (visibility).
+// Invalidates the runtime list so the picker disabled-state recomputes.
export function useUpdateRuntime(wsId: string) {
const qc = useQueryClient();
return useMutation({
@@ -26,23 +22,10 @@ export function useUpdateRuntime(wsId: string) {
patch,
}: {
runtimeId: string;
- patch: { timezone?: string; visibility?: "private" | "public" };
+ patch: { visibility?: "private" | "public" };
}) => api.updateRuntime(runtimeId, patch),
- onSettled: (_data, _err, vars) => {
+ onSettled: () => {
qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
- if (vars && vars.patch.timezone !== undefined) {
- // 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/runtimes/queries.ts b/packages/core/runtimes/queries.ts
index dbdd3c168d..47d0aaf187 100644
--- a/packages/core/runtimes/queries.ts
+++ b/packages/core/runtimes/queries.ts
@@ -5,43 +5,45 @@ export const runtimeKeys = {
all: (wsId: string) => ["runtimes", wsId] as const,
list: (wsId: string) => [...runtimeKeys.all(wsId), "list"] as const,
listMine: (wsId: string) => [...runtimeKeys.all(wsId), "list", "mine"] as const,
- usage: (rid: string, days: number) =>
- ["runtimes", "usage", rid, days] as const,
- usageByAgent: (rid: string, days: number) =>
- ["runtimes", "usage", "by-agent", rid, days] as const,
- usageByHour: (rid: string, days: number) =>
- ["runtimes", "usage", "by-hour", rid, days] as const,
+ usage: (rid: string, days: number, tz: string) =>
+ ["runtimes", "usage", rid, days, tz] as const,
+ usageByAgent: (rid: string, days: number, tz: string) =>
+ ["runtimes", "usage", "by-agent", rid, days, tz] as const,
+ // by-hour now follows the viewer's tz, like the other reports.
+ usageByHour: (rid: string, days: number, tz: string) =>
+ ["runtimes", "usage", "by-hour", rid, days, tz] as const,
latestVersion: () => ["runtimes", "latestVersion"] as const,
};
-// Per-runtime usage. Used by the list view (each row pulls its own activity
-// sparkline + 30d cost) and by the detail page. TanStack Query naturally
-// deduplicates concurrent calls for the same runtime, so multiple components
-// observing the same runtimeId share one network request.
-export function runtimeUsageOptions(runtimeId: string, days: number) {
+// `tz` is the viewer's IANA name — all reports follow the viewer's tz.
+export function runtimeUsageOptions(
+ runtimeId: string,
+ days: number,
+ tz: string,
+) {
return queryOptions({
- queryKey: runtimeKeys.usage(runtimeId, days),
- queryFn: () => api.getRuntimeUsage(runtimeId, { days }),
+ queryKey: runtimeKeys.usage(runtimeId, days, tz),
+ queryFn: () => api.getRuntimeUsage(runtimeId, { days, tz }),
staleTime: 60 * 1000,
});
}
-// Per-agent token totals for one runtime — drives the "Cost by agent" tab
-// on the runtime detail page. Server-side aggregation keeps the response
-// small (one row per agent) regardless of task volume.
-export function runtimeUsageByAgentOptions(runtimeId: string, days: number) {
+export function runtimeUsageByAgentOptions(
+ runtimeId: string,
+ days: number,
+ tz: string,
+) {
return queryOptions({
- queryKey: runtimeKeys.usageByAgent(runtimeId, days),
- queryFn: () => api.getRuntimeUsageByAgent(runtimeId, { days }),
+ queryKey: runtimeKeys.usageByAgent(runtimeId, days, tz),
+ queryFn: () => api.getRuntimeUsageByAgent(runtimeId, { days, tz }),
staleTime: 60 * 1000,
});
}
-// Hourly (0..23) token totals for one runtime — drives the "By hour" tab.
-export function runtimeUsageByHourOptions(runtimeId: string, days: number) {
+export function runtimeUsageByHourOptions(runtimeId: string, days: number, tz: string) {
return queryOptions({
- queryKey: runtimeKeys.usageByHour(runtimeId, days),
- queryFn: () => api.getRuntimeUsageByHour(runtimeId, { days }),
+ queryKey: runtimeKeys.usageByHour(runtimeId, days, tz),
+ queryFn: () => api.getRuntimeUsageByHour(runtimeId, { days, tz }),
staleTime: 60 * 1000,
});
}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 51ce226323..9dc5e2042e 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -26,7 +26,6 @@ export interface RuntimeDevice {
owner_id: string | null;
/** Defaults to "private" when the backend predates the visibility flag. */
visibility: RuntimeVisibility;
- timezone: string;
last_seen_at: string | null;
created_at: string;
updated_at: string;
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 8a3dcd0a67..9ca1f1c01d 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -155,6 +155,8 @@ export interface UpdateMeRequest {
language?: string;
/** Free-form self-description (max 2000 chars). Pass "" to clear. */
profile_description?: string;
+ /** IANA tz to pin; "" clears back to browser-tz; undefined leaves untouched. */
+ timezone?: string;
}
export interface CreateMemberRequest {
diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.ts
index b5a5ba23f7..b850c9a0ed 100644
--- a/packages/core/types/workspace.ts
+++ b/packages/core/types/workspace.ts
@@ -55,6 +55,8 @@ export interface User {
* NOT NULL DEFAULT '' at the column level, empty when unset.
*/
profile_description: string;
+ /** Pinned IANA tz; null means "use browser-detected tz at render time". */
+ timezone: string | null;
created_at: string;
updated_at: string;
}
diff --git a/packages/views/agents/components/create-agent-dialog.test.tsx b/packages/views/agents/components/create-agent-dialog.test.tsx
index 479514a01d..1b6f68d25f 100644
--- a/packages/views/agents/components/create-agent-dialog.test.tsx
+++ b/packages/views/agents/components/create-agent-dialog.test.tsx
@@ -87,7 +87,6 @@ function makeRuntime(overrides: Partial<RuntimeDevice>): RuntimeDevice {
metadata: {},
owner_id: ME,
visibility: "private",
- 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/views/common/timezone-select.tsx b/packages/views/common/timezone-select.tsx
index b6eab16f37..cf25170646 100644
--- a/packages/views/common/timezone-select.tsx
+++ b/packages/views/common/timezone-select.tsx
@@ -8,10 +8,10 @@ import {
SelectValue,
} from "@multica/ui/components/ui/select";
-// Common IANA zones surfaced as quick picks. Used as the fallback option set
-// when Intl.supportedValuesOf is not available, and promoted to the top of
-// the list when it is.
-const COMMON_TIMEZONES = [
+// Curated fallback list used when the runtime lacks `Intl.supportedValuesOf`.
+// Exported so every timezone picker draws from one source instead of
+// drifting copies.
+export const COMMON_TIMEZONES = [
"UTC",
"America/Los_Angeles",
"America/Denver",
@@ -33,13 +33,25 @@ const COMMON_TIMEZONES = [
"Pacific/Auckland",
];
+let cachedBrowserTZ: string | null = null;
export function browserTimezone(): string {
+ if (cachedBrowserTZ !== null) return cachedBrowserTZ;
try {
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
- return tz || "UTC";
+ cachedBrowserTZ = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
} catch {
- return "UTC";
+ cachedBrowserTZ = "UTC";
}
+ return cachedBrowserTZ;
+}
+
+// Clears the module-level browserTimezone() cache. Browser code never
+// needs this — the tz is stable for a session — but the cache survives
+// across Vitest files in the same worker, so any test that stubs
+// `Intl.DateTimeFormat` (directly or via a fake timezone) MUST call this
+// in `beforeEach`, otherwise a value cached by an earlier suite leaks in.
+// Tests that mock the whole `./timezone-select` module are unaffected.
+export function resetBrowserTimezoneCache(): void {
+ cachedBrowserTZ = null;
}
type IntlWithSupportedValues = typeof Intl & {
@@ -64,10 +76,6 @@ export function timezoneOptions(current: string): string[] {
).filter(Boolean);
}
-// Shared single-select timezone picker. Surfaces the browser-resolved zone
-// with a translated suffix (passed in by the caller — the picker itself stays
-// i18n-namespace agnostic), followed by a curated set of common IANA zones
-// and everything Intl.supportedValuesOf exposes.
export function TimezoneSelect({
value,
onValueChange,
diff --git a/packages/views/common/use-viewing-timezone.test.ts b/packages/views/common/use-viewing-timezone.test.ts
new file mode 100644
index 0000000000..43a4db8a74
--- /dev/null
+++ b/packages/views/common/use-viewing-timezone.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const userRef = vi.hoisted(
+ () => ({ current: null as { timezone?: string | null } | null }),
+);
+
+vi.mock("@multica/core/auth", () => {
+ type AuthState = { user: typeof userRef.current };
+ const useAuthStore = Object.assign(
+ (sel: (s: AuthState) => unknown) => sel({ user: userRef.current }),
+ { getState: () => ({ user: userRef.current }) },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("./timezone-select", () => ({
+ browserTimezone: () => "America/Chicago",
+}));
+
+import { useViewingTimezone } from "./use-viewing-timezone";
+
+describe("useViewingTimezone", () => {
+ beforeEach(() => {
+ userRef.current = null;
+ });
+
+ it("returns the stored preference when the user pinned one", () => {
+ userRef.current = { timezone: "Asia/Tokyo" };
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("Asia/Tokyo");
+ });
+
+ it("falls back to the browser tz when there is no user", () => {
+ userRef.current = null;
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("America/Chicago");
+ });
+
+ it("falls back to the browser tz when timezone is null", () => {
+ userRef.current = { timezone: null };
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("America/Chicago");
+ });
+
+ it("falls back to the browser tz when timezone is blank", () => {
+ userRef.current = { timezone: " " };
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("America/Chicago");
+ });
+
+ // The preferences clear-flow PATCHes timezone: "" and the server may echo
+ // the empty string back before normalising it to null. The hook must
+ // treat "" as "no preference" and fall back to the browser tz.
+ it("falls back to the browser tz when timezone is an empty string", () => {
+ userRef.current = { timezone: "" };
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("America/Chicago");
+ });
+
+ // Auth store still initialising: user is undefined, not null.
+ it("falls back to the browser tz when the user is undefined", () => {
+ userRef.current = undefined as never;
+ const { result } = renderHook(() => useViewingTimezone());
+ expect(result.current).toBe("America/Chicago");
+ });
+});
diff --git a/packages/views/common/use-viewing-timezone.ts b/packages/views/common/use-viewing-timezone.ts
new file mode 100644
index 0000000000..d45b612d3b
--- /dev/null
+++ b/packages/views/common/use-viewing-timezone.ts
@@ -0,0 +1,9 @@
+import { useAuthStore } from "@multica/core/auth";
+import { browserTimezone } from "./timezone-select";
+
+// Viewer's IANA tz: stored user preference, else browser-detected, else UTC.
+export function useViewingTimezone(): string {
+ const stored = useAuthStore((s) => s.user?.timezone ?? null);
+ if (stored && stored.trim() !== "") return stored;
+ return browserTimezone();
+}
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsx
new file mode 100644
index 0000000000..ebf8428f8a
--- /dev/null
+++ b/packages/views/dashboard/components/dashboard-page.test.tsx
@@ -0,0 +1,100 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { cleanup } from "@testing-library/react";
+import { renderWithI18n } from "../../test/i18n";
+
+// The viewing timezone flows: auth store `user.timezone` → useViewingTimezone()
+// → every dashboard query key. This test pins that chain: when the stored
+// timezone changes, the dashboard report query keys must change, which is
+// what makes TanStack Query refetch under the new tz.
+
+// Capture every queryKey passed to useQuery. queryOptions() inside the
+// dashboard options builders runs for real, so the key is the production key.
+const queryKeys = vi.hoisted(() => [] as unknown[][]);
+
+vi.mock("@tanstack/react-query", async () => {
+ const actual =
+ await vi.importActual<typeof import("@tanstack/react-query")>(
+ "@tanstack/react-query",
+ );
+ return {
+ ...actual,
+ useQuery: (opts: { queryKey: unknown[] }) => {
+ queryKeys.push(opts.queryKey);
+ return { data: undefined, isLoading: true };
+ },
+ };
+});
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+const tzRef = vi.hoisted(() => ({ current: "UTC" as string | null }));
+
+vi.mock("@multica/core/auth", () => {
+ type AuthState = { user: { timezone: string | null } | null };
+ const state = (): AuthState => ({ user: { timezone: tzRef.current } });
+ const useAuthStore = Object.assign(
+ (sel?: (s: AuthState) => unknown) => (sel ? sel(state()) : state()),
+ { getState: state },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("@multica/core/runtimes/custom-pricing-store", () => {
+ const state = () => ({ pricings: {} });
+ const useCustomPricingStore = Object.assign(
+ (sel?: (s: ReturnType<typeof state>) => unknown) =>
+ sel ? sel(state()) : state(),
+ { getState: state },
+ );
+ return { useCustomPricingStore };
+});
+
+import { DashboardPage } from "./dashboard-page";
+
+describe("DashboardPage — viewing timezone drives the query key", () => {
+ beforeEach(() => {
+ queryKeys.length = 0;
+ cleanup();
+ });
+
+ // The `tz` segment is the last element of every dashboard key
+ // (see dashboardKeys in @multica/core/dashboard/queries).
+ function tzSegments(): unknown[] {
+ return queryKeys
+ .filter((k) => k[0] === "dashboard")
+ .map((k) => k[k.length - 1]);
+ }
+
+ it("uses the stored timezone in every dashboard query key", () => {
+ tzRef.current = "UTC";
+ renderWithI18n(<DashboardPage />);
+
+ const tzs = tzSegments();
+ expect(tzs.length).toBeGreaterThan(0);
+ expect(tzs.every((tz) => tz === "UTC")).toBe(true);
+ });
+
+ it("flips the query key when the stored timezone changes", () => {
+ tzRef.current = "UTC";
+ renderWithI18n(<DashboardPage />);
+ const utcKeys = queryKeys.filter((k) => k[0] === "dashboard");
+
+ queryKeys.length = 0;
+ cleanup();
+
+ tzRef.current = "Asia/Tokyo";
+ renderWithI18n(<DashboardPage />);
+ const tokyoKeys = queryKeys.filter((k) => k[0] === "dashboard");
+
+ expect(utcKeys.length).toBe(tokyoKeys.length);
+ expect(utcKeys.length).toBeGreaterThan(0);
+ // Same number of dashboard queries, but no key is shared between the
+ // two timezones — so TanStack Query treats every series as a fresh
+ // fetch and refetches under the new tz.
+ for (let i = 0; i < utcKeys.length; i++) {
+ expect(utcKeys[i]).not.toEqual(tokyoKeys[i]);
+ }
+ });
+});
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 65eefc62b7..d5e08907a9 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -21,6 +21,7 @@ import {
dashboardRunTimeDailyOptions,
} from "@multica/core/dashboard";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
+import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { PageHeader } from "../../layout/page-header";
import { KpiCard } from "../../runtimes/components/shared";
import {
@@ -64,9 +65,9 @@ import {
// 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.
+// 1d semantic: "today" (the natural calendar day from 00:00 in the viewer's
+// timezone), 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 },
@@ -103,14 +104,6 @@ function fmtMoney(n: number): string {
return `$${n.toFixed(2)}`;
}
-// Weekly aggregation is locked to UTC: the dashboard daily rollup buckets
-// data by UTC `bucket_date` (and the raw fallback queries by `DATE(...)`,
-// also UTC), so any other zone for client-side week boundaries would put
-// cross-midnight rows into the wrong calendar week. Runtime-detail can use
-// the runtime's IANA tz because its rollup is materialized in that tz; the
-// workspace rollup has no equivalent, so weekly is UTC-only here.
-const WEEK_TZ = "UTC";
-
// Local segmented control — same visual language the runtime usage section
// uses for its period / tab toggles. shadcn's Tabs is wired for full tab
// pages with ARIA semantics the compact toolbar pill doesn't need.
@@ -157,6 +150,7 @@ function Segmented<T extends string | number>({
export function DashboardPage() {
const { t } = useT("usage");
const wsId = useWorkspaceId();
+ const viewTZ = useViewingTimezone();
const [dim, setDim] = useState<Dim>("daily");
const [days, setDays] = useState<TimeRange>(30);
const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);
@@ -198,12 +192,16 @@ export function DashboardPage() {
const chartFetchDays = dim === "weekly" ? weekCount * 7 : days;
const dailyQuery = useQuery(
- dashboardUsageDailyOptions(wsId, chartFetchDays, projectId),
+ dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ),
+ );
+ const byAgentQuery = useQuery(
+ dashboardUsageByAgentOptions(wsId, days, projectId, viewTZ),
+ );
+ const runTimeQuery = useQuery(
+ dashboardAgentRunTimeOptions(wsId, days, projectId, viewTZ),
);
- const byAgentQuery = useQuery(dashboardUsageByAgentOptions(wsId, days, projectId));
- const runTimeQuery = useQuery(dashboardAgentRunTimeOptions(wsId, days, projectId));
const runTimeDailyQuery = useQuery(
- dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId),
+ dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId, viewTZ),
);
const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;
@@ -213,14 +211,14 @@ export function DashboardPage() {
// Daily-aggregation surfaces (cost/tokens/time/tasks KPIs and the Daily
// 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. Applied in both dims so 1d strictly means "today" even
- // at the midnight UTC edge where the server's wall-clock cutoff would
+ // over-fetched for the weekly chart. The cutoff is anchored on the viewer's
+ // timezone — the same axis the backend slices `bucket_hour` on — so it
+ // lands on the same calendar boundary. Applied in both dims so 1d strictly
+ // means "today" even at the midnight edge where a wall-clock cutoff would
// otherwise include yesterday.
const dailyCutoffIso = useMemo(
- () => addDaysIso(todayIso(WEEK_TZ), -(days - 1)),
- [days],
+ () => addDaysIso(todayIso(viewTZ), -(days - 1)),
+ [days, viewTZ],
);
const dailyUsageInWindow = useMemo(
() => dailyUsage.filter((u) => u.date >= dailyCutoffIso),
@@ -273,21 +271,21 @@ export function DashboardPage() {
// leftmost trailing week always has data even when the user-selected `days`
// (e.g. 30D) is shorter than the chart's `weekCount * 7` span. Buckets are
// pre-zeroed inside the helpers, so sparse weeks render as empty bars
- // instead of being dropped (MUL-2382 weekly window scoping). Locked to
- // UTC so the week boundaries match the backend's UTC `bucket_date`.
+ // instead of being dropped (MUL-2382 weekly window scoping). Week
+ // boundaries follow the viewer's timezone.
const weekly = useMemo(
- () => aggregateByWeek(dailyUsage, WEEK_TZ, weekCount),
- [dailyUsage, weekCount],
+ () => aggregateByWeek(dailyUsage, viewTZ, weekCount),
+ [dailyUsage, viewTZ, weekCount],
);
const weeklyCost = weekly.weeklyCostStack;
const weeklyTokens = weekly.weeklyTokens;
const weeklyTime = useMemo(
- () => aggregateWeeklyTime(runTimeDailyRows, WEEK_TZ, weekCount),
- [runTimeDailyRows, weekCount],
+ () => aggregateWeeklyTime(runTimeDailyRows, viewTZ, weekCount),
+ [runTimeDailyRows, viewTZ, weekCount],
);
const weeklyTasks = useMemo(
- () => aggregateWeeklyTasks(runTimeDailyRows, WEEK_TZ, weekCount),
- [runTimeDailyRows, weekCount],
+ () => aggregateWeeklyTasks(runTimeDailyRows, viewTZ, weekCount),
+ [runTimeDailyRows, viewTZ, weekCount],
);
const agentTokenRows = useMemo(
() => aggregateAgentTokens(byAgentUsage),
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 61e1524484..1d2c0b345c 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -101,7 +101,6 @@
"diagnostics_title": "Diagnostics",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "Visibility",
- "diagnostics_timezone": "Timezone",
"visibility_label": {
"private": "Private",
"public": "Public"
@@ -112,10 +111,6 @@
},
"visibility_toast_updated": "Visibility set to {{visibility}}",
"visibility_toast_failed": "Failed to update visibility",
- "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/en/settings.json b/packages/views/locales/en/settings.json
index 30719e7cc6..0edb3d1592 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -11,6 +11,12 @@
"english": "English",
"chinese": "中文",
"sync_failed": "Language saved on this device, but failed to sync to your account. Other devices may show the previous language."
+ },
+ "timezone": {
+ "title": "Viewing Timezone",
+ "browser_suffix": " (browser)",
+ "hint": "Used for dashboards, charts, and any 'today' label shown to you. It's a personal preference that applies across all your workspaces.",
+ "sync_failed": "Failed to save your timezone preference."
}
},
"page": {
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 66a46a05e1..baec84eb5b 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -96,7 +96,6 @@
"diagnostics_title": "诊断",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "可见性",
- "diagnostics_timezone": "时区",
"visibility_label": {
"private": "私有",
"public": "公开"
@@ -107,10 +106,6 @@
},
"visibility_toast_updated": "可见性已设为「{{visibility}}」",
"visibility_toast_failed": "更新可见性失败",
- "timezone_browser_suffix": "(浏览器)",
- "timezone_hint": "该 Runtime 的 Token 用量图表会按此时区进行日期分桶。",
- "timezone_toast_updated": "时区已更新为 {{tz}}",
- "timezone_toast_failed": "更新时区失败",
"delete_dialog": {
"title": "删除运行时",
"description": "确定要删除\"{{name}}\"吗?此操作不可撤销。",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 1da6142ec9..93c01ad019 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -11,6 +11,12 @@
"english": "English",
"chinese": "中文",
"sync_failed": "语言已在本设备保存,但同步到账号失败。其他设备可能仍显示旧语言。"
+ },
+ "timezone": {
+ "title": "查看时区",
+ "browser_suffix": "(浏览器)",
+ "hint": "用于仪表盘、图表和「今天」标签。这是个人偏好,在你的所有工作区中通用。",
+ "sync_failed": "保存时区偏好失败。"
}
},
"page": {
diff --git a/packages/views/runtimes/components/charts/activity-heatmap.tsx b/packages/views/runtimes/components/charts/activity-heatmap.tsx
index 6625d677fc..4fbf7d7ede 100644
--- a/packages/views/runtimes/components/charts/activity-heatmap.tsx
+++ b/packages/views/runtimes/components/charts/activity-heatmap.tsx
@@ -71,7 +71,7 @@ export function ActivityHeatmap({
}
// Anchor the grid on the Monday of the week containing "today" in the
- // runtime's tz, then walk back HEATMAP_WEEKS-1 weeks. All dates are
+ // viewer's tz, then walk back HEATMAP_WEEKS-1 weeks. All dates are
// string-based YYYY-MM-DD so the host browser's tz can't shift a column.
// We stop drawing cells once we pass `today` so the in-progress week is
// partial (cells for "tomorrow onward" aren't rendered) — matches the
diff --git a/packages/views/runtimes/components/runtime-columns.tsx b/packages/views/runtimes/components/runtime-columns.tsx
index d09767b3e5..9f6b76f528 100644
--- a/packages/views/runtimes/components/runtime-columns.tsx
+++ b/packages/views/runtimes/components/runtime-columns.tsx
@@ -40,6 +40,7 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "../../common/actor-avatar";
+import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { workloadConfig } from "../../agents/presence";
import { ProviderLogo } from "./provider-logo";
import { HealthIcon, useHealthLabel } from "./shared";
@@ -333,13 +334,17 @@ const COST_CELL_DAYS = 14;
function CostCell({ runtimeId }: { runtimeId: string }) {
const { t } = useT("runtimes");
+ const tz = useViewingTimezone();
const { data: usage = [] } = useQuery(
- runtimeUsageOptions(runtimeId, COST_CELL_DAYS),
+ runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),
+ );
+ const cost7d = useMemo(
+ () => computeCostInWindow(usage, 7, tz),
+ [usage, tz],
);
- const cost7d = useMemo(() => computeCostInWindow(usage, 7), [usage]);
const costPrev7d = useMemo(
- () => computeCostInWindow(usage, 7, 7),
- [usage],
+ () => computeCostInWindow(usage, 7, tz, 7),
+ [usage, tz],
);
const delta = pctChange(cost7d, costPrev7d);
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index 5722bd3825..5248c83598 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -112,7 +112,6 @@ function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {
metadata: {},
owner_id: "user-me",
visibility: "private",
- 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/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index df58ccaba1..d3576ee47f 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -39,7 +39,6 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "../../common/actor-avatar";
-import { TimezoneSelect } from "../../common/timezone-select";
import { AppLink } from "../../navigation";
import { availabilityConfig, workloadConfig } from "../../agents/presence";
import { formatLastSeen } from "../utils";
@@ -520,16 +519,6 @@ function DiagnosticsCard({
<VisibilityReadout runtime={runtime} />
)}
</div>
- <div className="border-t pt-3">
- <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 className="border-t pt-3">
<div className="mb-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
@@ -681,59 +670,3 @@ function VisibilityChoice({
</Tooltip>
);
}
-
-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 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: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.detail.timezone_toast_failed),
- ),
- },
- );
- };
-
- return (
- <div className="space-y-1.5">
- <TimezoneSelect
- value={current}
- onValueChange={handleTimezoneChange}
- browserSuffix={t(($) => $.detail.timezone_browser_suffix)}
- disabled={updateRuntime.isPending}
- />
- <p className="text-[11px] leading-snug text-muted-foreground">
- {t(($) => $.detail.timezone_hint)}
- </p>
- </div>
- );
-}
diff --git a/packages/views/runtimes/components/runtime-machines.test.ts b/packages/views/runtimes/components/runtime-machines.test.ts
index acbd6bdb42..3d2e29b209 100644
--- a/packages/views/runtimes/components/runtime-machines.test.ts
+++ b/packages/views/runtimes/components/runtime-machines.test.ts
@@ -23,7 +23,6 @@ function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
metadata: { cli_version: "0.3.0" },
owner_id: "user-1",
visibility: "private",
- timezone: "UTC",
last_seen_at: new Date(NOW - 10_000).toISOString(),
created_at: "2026-05-17T11:00:00Z",
updated_at: "2026-05-17T11:00:00Z",
diff --git a/packages/views/runtimes/components/usage-section.test.tsx b/packages/views/runtimes/components/usage-section.test.tsx
new file mode 100644
index 0000000000..a79fecc4e0
--- /dev/null
+++ b/packages/views/runtimes/components/usage-section.test.tsx
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { AgentRuntime } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+
+const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
+
+// The viewer's tz (Viewing layer) drives both the trend and the heatmap.
+const VIEWER_TZ = "Asia/Tokyo";
+
+// runtimeUsageOptions is the trend-fetch query. Capture its args so the
+// test can assert which tz the trend was wired with.
+const runtimeUsageOptions = vi.hoisted(() =>
+ vi.fn((..._args: unknown[]) => ({ kind: "usage" as const })),
+);
+const runtimeUsageByAgentOptions = vi.hoisted(() =>
+ vi.fn((..._args: unknown[]) => ({ kind: "by-agent" as const })),
+);
+
+vi.mock("../../common/use-viewing-timezone", () => ({
+ useViewingTimezone: () => VIEWER_TZ,
+}));
+
+vi.mock("@multica/core/runtimes/queries", () => ({
+ runtimeUsageOptions,
+ runtimeUsageByAgentOptions,
+}));
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ kind: "agents" as const }),
+}));
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+// custom-pricing-store is consumed two ways: usage-section reads the store
+// hook, and runtimes/utils reads getCustomPricing(). The hook must be both
+// callable and expose getState(), mirroring a real Zustand store.
+vi.mock("@multica/core/runtimes/custom-pricing-store", () => {
+ const state = { pricings: {} as Record<string, unknown> };
+ const useCustomPricingStore = Object.assign(
+ (sel?: (s: typeof state) => unknown) => (sel ? sel(state) : state),
+ { getState: () => state },
+ );
+ return { useCustomPricingStore, getCustomPricing: () => undefined };
+});
+
+// useQuery is mocked so the component renders synchronously with canned
+// data — the `kind` tag on each query-options object routes the response.
+vi.mock("@tanstack/react-query", async () => {
+ const actual =
+ await vi.importActual<typeof import("@tanstack/react-query")>(
+ "@tanstack/react-query",
+ );
+ const usageRows = [
+ {
+ runtime_id: "r-1",
+ date: "2026-05-19",
+ provider: "anthropic",
+ model: "claude-sonnet-4-6",
+ input_tokens: 1_000,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ },
+ ];
+ return {
+ ...actual,
+ useQuery: (opts: { kind?: string }) => ({
+ data: opts?.kind === "usage" ? usageRows : [],
+ isLoading: false,
+ }),
+ };
+});
+
+// Charts are recharts-heavy; stub them. ActivityHeatmap echoes its `tz`
+// prop so the test can read which tz the heatmap was wired with.
+vi.mock("./charts", () => ({
+ DailyCostChart: () => <div data-testid="daily-cost-chart" />,
+ DailyTokensChart: () => <div data-testid="daily-tokens-chart" />,
+ WeeklyCostChart: () => <div data-testid="weekly-cost-chart" />,
+ WeeklyTokensChart: () => <div data-testid="weekly-tokens-chart" />,
+ ActivityHeatmap: ({ tz }: { tz: string }) => (
+ <div data-testid="heatmap-tz">{tz}</div>
+ ),
+}));
+
+vi.mock("./custom-pricing-dialog", () => ({
+ CustomPricingDialog: () => null,
+}));
+
+import { UsageSection } from "./usage-section";
+
+const RUNTIME: AgentRuntime = {
+ id: "r-1",
+ workspace_id: "ws-1",
+ daemon_id: null,
+ name: "test-runtime",
+ runtime_mode: "cloud",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: null,
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-05-01T00:00:00Z",
+ updated_at: "2026-05-01T00:00:00Z",
+};
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+describe("UsageSection — Viewing timezone wiring", () => {
+ beforeEach(() => {
+ runtimeUsageOptions.mockClear();
+ runtimeUsageByAgentOptions.mockClear();
+ });
+
+ it("fetches the trend in the viewer's tz", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ expect(runtimeUsageOptions).toHaveBeenCalled();
+ const [, days, tz] = runtimeUsageOptions.mock.calls[0]!;
+ expect(days).toBe(180);
+ expect(tz).toBe(VIEWER_TZ);
+ });
+
+ it("renders the heatmap in the viewer's tz", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ // The heatmap is an opt-in toggle inside the "When" card.
+ fireEvent.click(screen.getByRole("button", { name: "Heatmap" }));
+
+ expect(screen.getByTestId("heatmap-tz").textContent).toBe(VIEWER_TZ);
+ });
+});
diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsx
index 5d2de96c3d..c632ac7c09 100644
--- a/packages/views/runtimes/components/usage-section.tsx
+++ b/packages/views/runtimes/components/usage-section.tsx
@@ -13,6 +13,7 @@ import {
runtimeUsageByAgentOptions,
} from "@multica/core/runtimes/queries";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
+import { useViewingTimezone } from "../../common/use-viewing-timezone";
import {
formatTokens,
estimateCost,
@@ -129,12 +130,12 @@ function fmtMoney(n: number): string {
export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
const { t } = useT("runtimes");
const runtimeId = runtime.id;
- // Tz comes from the runtime itself — the backend already buckets daily
- // rows on `start-of-day in runtime tz`, so we use the same axis for every
- // frontend window calculation. No "user timezone" option here on purpose.
- const tz = runtime.timezone;
+ // Reports render in the viewer's timezone — the backend slices the UTC
+ // hourly rollup on the same `tz` we pass here, so every frontend window
+ // calculation shares one axis with the server.
+ const tz = useViewingTimezone();
const { data: usage = [], isLoading: loading } = useQuery(
- runtimeUsageOptions(runtimeId, 180),
+ runtimeUsageOptions(runtimeId, 180, tz),
);
const [dim, setDim] = useState<Exclude<WhenTab, "heatmap">>("daily");
const [days, setDays] = useState<TimeRange>(30);
@@ -283,7 +284,7 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
/>
{/* Layer 3 — WHO/WHAT burned the spend. */}
- <CostByBlock runtimeId={runtimeId} days={days} usage={filtered} />
+ <CostByBlock runtimeId={runtimeId} days={days} usage={filtered} tz={tz} />
{/* Layer 4 — Folded raw view. The Heatmap used to live here too; it
was promoted into the WHEN chart's toggle, leaving only the
@@ -599,10 +600,12 @@ function CostByBlock({
runtimeId,
days,
usage,
+ tz,
}: {
runtimeId: string;
days: number;
usage: RuntimeUsage[];
+ tz: string;
}) {
const { t } = useT("runtimes");
const [tab, setTab] = useState<"agent" | "model">("agent");
@@ -613,7 +616,7 @@ function CostByBlock({
// by-agent is server-side aggregation (fetched lazily on tab activation).
// by-model derives from the daily cache the parent already has — free.
const { data: byAgentRows = [] } = useQuery({
- ...runtimeUsageByAgentOptions(runtimeId, days),
+ ...runtimeUsageByAgentOptions(runtimeId, days, tz),
enabled: tab === "agent",
});
diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.ts
index c8476ac5b2..120a76a1af 100644
--- a/packages/views/runtimes/utils.test.ts
+++ b/packages/views/runtimes/utils.test.ts
@@ -7,6 +7,7 @@ import {
aggregateByWeek,
aggregateCostByModel,
collectUnmappedModels,
+ computeCostInWindow,
estimateCost,
isModelPriced,
sliceWindow,
@@ -603,3 +604,80 @@ describe("aggregateByWeek", () => {
}
});
});
+
+// computeCostInWindow drives the runtime-list cost cell and its ↑/↓ delta.
+// The `tz` argument was inserted as the THIRD positional parameter (before
+// `offsetDays`) in the timezone-architecture RFC — a positional-arg slip
+// here is otherwise silent, so the window math, the end-exclusive boundary,
+// the offset shift, and the tz-of-"today" all need explicit coverage.
+describe("computeCostInWindow", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // claude-sonnet-4-6 is priced at $3 / 1M input tokens, so a row with
+ // 1M input tokens contributes exactly $3.
+ function priced(date: string, inputTokens: number): RuntimeUsage {
+ return {
+ runtime_id: "r",
+ date,
+ provider: "anthropic",
+ model: "claude-sonnet-4-6",
+ input_tokens: inputTokens,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ };
+ }
+
+ it("sums cost over the trailing daysBack window, end-exclusive of today", () => {
+ // 2026-05-19 23:00 UTC is already 2026-05-20 in Asia/Shanghai, so
+ // "today" is 2026-05-20 and the 7-day window is [2026-05-13, 2026-05-20).
+ vi.setSystemTime(new Date("2026-05-19T23:00:00Z"));
+ const rows = [
+ priced("2026-05-12", 1_000_000), // before window — excluded
+ priced("2026-05-13", 1_000_000), // window start — included
+ priced("2026-05-19", 1_000_000), // included
+ priced("2026-05-20", 1_000_000), // today — excluded (end-exclusive)
+ ];
+ expect(computeCostInWindow(rows, 7, "Asia/Shanghai")).toBeCloseTo(6, 5);
+ });
+
+ it("offsetDays shifts the window back to the prior period", () => {
+ // today = 2026-05-20; offsetDays=7, daysBack=7 → window [05-06, 05-13).
+ vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
+ const rows = [
+ priced("2026-05-05", 1_000_000), // before prior window — excluded
+ priced("2026-05-06", 1_000_000), // prior window start — included
+ priced("2026-05-12", 1_000_000), // included
+ priced("2026-05-13", 1_000_000), // in the current window, not prior — excluded
+ ];
+ expect(computeCostInWindow(rows, 7, "UTC", 7)).toBeCloseTo(6, 5);
+ });
+
+ it("reads 'today' in the supplied tz, not the host clock", () => {
+ // Host clock is 2026-05-19 in UTC but already 2026-05-20 in Shanghai.
+ // A row dated 2026-05-19 falls inside the 1-day window only when the
+ // tz pushes "today" forward to 2026-05-20.
+ vi.setSystemTime(new Date("2026-05-19T20:00:00Z"));
+ const rows = [priced("2026-05-19", 1_000_000)];
+ expect(computeCostInWindow(rows, 1, "UTC")).toBe(0); // today=05-19, window [05-18,05-19)
+ expect(computeCostInWindow(rows, 1, "Asia/Shanghai")).toBeCloseTo(3, 5);
+ });
+
+ it("returns 0 for an unpriced model rather than NaN", () => {
+ vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
+ const rows: RuntimeUsage[] = [
+ { ...priced("2026-05-19", 1_000_000), model: "totally-made-up-model" },
+ ];
+ expect(computeCostInWindow(rows, 7, "UTC")).toBe(0);
+ });
+
+ it("returns 0 for an empty row set", () => {
+ vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
+ expect(computeCostInWindow([], 7, "UTC")).toBe(0);
+ });
+});
diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.ts
index 098c35a44d..9c1a6bc8cd 100644
--- a/packages/views/runtimes/utils.ts
+++ b/packages/views/runtimes/utils.ts
@@ -730,30 +730,29 @@ export function aggregateCostByModel(rows: RuntimeUsage[]): CostByKey[] {
return [...map.values()].sort((a, b) => b.cost - a.cost);
}
-// "Cost · 30D" KPI hint: percentage delta vs. the immediately prior window
-// of equal length. Returns null when there's no comparable prior data
-// (caller renders nothing rather than a misleading "+∞%").
// Sum of estimated cost over the trailing window
// [today − offsetDays − daysBack, today − offsetDays).
// `offsetDays = 0, daysBack = 7` → last 7 days.
// `offsetDays = 7, daysBack = 7` → the 7 days *before* the last 7 (the
// "previous" window for the runtime-list ↑/↓ delta).
//
+// "Today" is read in `tz` (the viewer's timezone) so the cutoff lands on
+// the same calendar boundary the backend used when bucketing rows — the
+// rows arrive bucketed in the viewer's tz, so slicing them with the JS
+// engine's local tz would shift the window by a day at the edges.
+//
// Walks the same daily-grain `RuntimeUsage` rows that `aggregateByDate` uses,
// so the runtime-list cost stays consistent with the runtime-detail KPIs
// (and crucially, hits the same TanStack Query cache key).
export function computeCostInWindow(
rows: readonly RuntimeUsage[],
daysBack: number,
+ tz: string,
offsetDays: number = 0,
): number {
- const now = new Date();
- const end = new Date(now);
- end.setDate(now.getDate() - offsetDays);
- const start = new Date(now);
- start.setDate(now.getDate() - offsetDays - daysBack);
- const isoEnd = end.toISOString().slice(0, 10);
- const isoStart = start.toISOString().slice(0, 10);
+ const today = todayIso(tz);
+ const isoEnd = addDaysIso(today, -offsetDays);
+ const isoStart = addDaysIso(today, -offsetDays - daysBack);
let total = 0;
for (const r of rows) {
if (r.date >= isoStart && r.date < isoEnd) total += estimateCost(r);
diff --git a/packages/views/settings/components/preferences-tab.test.tsx b/packages/views/settings/components/preferences-tab.test.tsx
index 0c168ee89a..37a321d117 100644
--- a/packages/views/settings/components/preferences-tab.test.tsx
+++ b/packages/views/settings/components/preferences-tab.test.tsx
@@ -1,6 +1,6 @@
import type { ReactNode } from "react";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { render, screen, act } from "@testing-library/react";
+import { render, screen, act, cleanup, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
@@ -11,8 +11,10 @@ const mockPersist = vi.hoisted(() => vi.fn());
const mockUpdateMe = vi.hoisted(() => vi.fn());
const mockReload = vi.hoisted(() => vi.fn());
const mockToastWarning = vi.hoisted(() => vi.fn());
+const mockToastError = vi.hoisted(() => vi.fn());
+const mockSetUser = vi.hoisted(() => vi.fn());
const userRef = vi.hoisted(() => ({
- current: null as { id: string } | null,
+ current: null as { id: string; timezone?: string | null } | null,
}));
vi.mock("@multica/ui/components/common/theme-provider", () => ({
@@ -39,7 +41,7 @@ vi.mock("@multica/core/api", () => ({
}));
vi.mock("sonner", () => ({
- toast: { warning: mockToastWarning },
+ toast: { warning: mockToastWarning, error: mockToastError },
}));
vi.mock("@multica/core/auth", async () => {
@@ -47,10 +49,18 @@ vi.mock("@multica/core/auth", async () => {
await vi.importActual<typeof import("@multica/core/auth")>(
"@multica/core/auth",
);
+ type AuthState = {
+ user: typeof userRef.current;
+ setUser: typeof mockSetUser;
+ };
+ const state = (): AuthState => ({
+ user: userRef.current,
+ setUser: mockSetUser,
+ });
const useAuthStore = Object.assign(
- (sel?: (s: { user: typeof userRef.current }) => unknown) =>
- sel ? sel({ user: userRef.current }) : { user: userRef.current },
- { getState: () => ({ user: userRef.current }) },
+ (sel?: (s: AuthState) => unknown) =>
+ sel ? sel(state()) : state(),
+ { getState: state },
);
return { ...actual, useAuthStore };
});
@@ -144,3 +154,87 @@ describe("PreferencesTab — Language switcher", () => {
expect(mockReload).toHaveBeenCalledTimes(1);
});
});
+
+describe("PreferencesTab — Timezone section", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ userRef.current = null;
+ });
+
+ // Base UI Select portals its popup onto document.body; unmount each
+ // render fully between tests so a prior test's trigger/popup can't
+ // shadow the next one's.
+ afterEach(() => {
+ cleanup();
+ });
+
+ // Opens the Select popup and clicks the option whose accessible name
+ // matches. Re-queries the trigger each call so it operates on the
+ // current render, never a stale node.
+ async function pickTimezone(
+ user: ReturnType<typeof userEvent.setup>,
+ name: RegExp | string,
+ ) {
+ await user.click(screen.getByRole("combobox"));
+ await user.click(await screen.findByRole("option", { name }));
+ }
+
+ it("renders the stored timezone in the trigger", () => {
+ userRef.current = { id: "user-1", timezone: "Asia/Shanghai" };
+ render(<PreferencesTab />, { wrapper: I18nWrapper });
+
+ expect(screen.getByRole("combobox").textContent).toContain("Asia/Shanghai");
+ });
+
+ // handleChange PATCHes then updates the store asynchronously, so the
+ // post-pick assertions must waitFor it to settle. The extended timeout
+ // covers querying the Select's full ~600-option IANA list on slow CI.
+ it("saving a new timezone PATCHes /api/me and updates the auth store", async () => {
+ userRef.current = { id: "user-1", timezone: "Asia/Shanghai" };
+ const updatedUser = { id: "user-1", timezone: "Asia/Tokyo" };
+ mockUpdateMe.mockResolvedValueOnce(updatedUser);
+ const user = userEvent.setup();
+ render(<PreferencesTab />, { wrapper: I18nWrapper });
+
+ await pickTimezone(user, "Asia/Tokyo");
+
+ await waitFor(() => {
+ expect(mockUpdateMe).toHaveBeenCalledWith({ timezone: "Asia/Tokyo" });
+ expect(mockSetUser).toHaveBeenCalledWith(updatedUser);
+ });
+ }, 20000);
+
+ it("surfaces a toast when the PATCH fails", async () => {
+ userRef.current = { id: "user-1", timezone: "Asia/Shanghai" };
+ mockUpdateMe.mockRejectedValueOnce(new Error("network down"));
+ const user = userEvent.setup();
+ render(<PreferencesTab />, { wrapper: I18nWrapper });
+
+ await pickTimezone(user, "Asia/Tokyo");
+
+ await waitFor(() => {
+ expect(mockUpdateMe).toHaveBeenCalledWith({ timezone: "Asia/Tokyo" });
+ expect(mockToastError).toHaveBeenCalledTimes(1);
+ });
+ expect(mockSetUser).not.toHaveBeenCalled();
+ }, 20000);
+
+ it("clearing the preference sends an empty-string timezone", async () => {
+ userRef.current = { id: "user-1", timezone: "Asia/Shanghai" };
+ const clearedUser = { id: "user-1", timezone: null };
+ mockUpdateMe.mockResolvedValueOnce(clearedUser);
+ const user = userEvent.setup();
+ render(<PreferencesTab />, { wrapper: I18nWrapper });
+
+ // The "(browser)" sentinel option resets the preference to NULL; the
+ // wire payload is an empty string the backend translates to NULL.
+ await pickTimezone(user, /browser/i);
+
+ await waitFor(() => {
+ expect(mockUpdateMe).toHaveBeenCalledWith({ timezone: "" });
+ // The PATCH response (timezone: null) is pushed into the auth store
+ // so the picker switches back to "(browser)" without a refetch.
+ expect(mockSetUser).toHaveBeenCalledWith(clearedUser);
+ });
+ }, 20000);
+});
diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsx
index bc45ccd1da..62bb59e12e 100644
--- a/packages/views/settings/components/preferences-tab.tsx
+++ b/packages/views/settings/components/preferences-tab.tsx
@@ -1,6 +1,14 @@
"use client";
+import { useMemo } from "react";
import { toast } from "sonner";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
import { useTheme } from "@multica/ui/components/common/theme-provider";
import { cn } from "@multica/ui/lib/utils";
import {
@@ -11,6 +19,7 @@ import {
import { useLocaleAdapter } from "@multica/core/i18n/react";
import { useAuthStore } from "@multica/core/auth";
import { api } from "@multica/core/api";
+import { browserTimezone, timezoneOptions } from "../../common/timezone-select";
import { useT } from "../../i18n";
const LIGHT_COLORS = {
@@ -227,6 +236,82 @@ export function PreferencesTab() {
})}
</div>
</section>
+
+ <TimezoneSection />
</div>
);
}
+
+// Base UI rejects "" as a SelectItem value, so route the "no preference"
+// state through this sentinel and translate at the wire boundary.
+const BROWSER_TZ_VALUE = "__browser__";
+
+function TimezoneSection() {
+ const { t } = useT("settings");
+ const user = useAuthStore((s) => s.user);
+ const setUser = useAuthStore((s) => s.setUser);
+ const stored = user?.timezone ?? null;
+ const browser = browserTimezone();
+ const value = stored ?? BROWSER_TZ_VALUE;
+
+ // Full IANA list (from timezoneOptions in common/timezone-select) so a
+ // user needing a non-curated zone isn't stuck with ~18 common ones.
+ // Memoized — timezoneOptions enumerates ~600 IANA zones per call.
+ const options = useMemo(
+ () => timezoneOptions(stored ?? browser),
+ [stored, browser],
+ );
+
+ const handleChange = async (next: string) => {
+ if (next === value) return;
+ const payload = next === BROWSER_TZ_VALUE ? "" : next;
+ try {
+ const updated = await api.updateMe({ timezone: payload });
+ setUser(updated);
+ } catch (err) {
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.preferences.timezone.sync_failed),
+ );
+ }
+ };
+
+ const formatTZLabel = (tz: string) => {
+ if (tz === BROWSER_TZ_VALUE) {
+ return `${browser}${t(($) => $.preferences.timezone.browser_suffix)}`;
+ }
+ return tz;
+ };
+
+ return (
+ <section className="space-y-2">
+ <h2 className="text-sm font-semibold">
+ {t(($) => $.preferences.timezone.title)}
+ </h2>
+ <Select
+ value={value}
+ onValueChange={(next) => {
+ if (next) handleChange(next);
+ }}
+ >
+ <SelectTrigger size="sm" className="w-72 rounded-md font-mono text-xs">
+ <SelectValue>{formatTZLabel(value)}</SelectValue>
+ </SelectTrigger>
+ <SelectContent align="start" className="max-h-72">
+ <SelectItem value={BROWSER_TZ_VALUE} className="font-mono text-xs">
+ {formatTZLabel(BROWSER_TZ_VALUE)}
+ </SelectItem>
+ {options.map((tz) => (
+ <SelectItem key={tz} value={tz} className="font-mono text-xs">
+ {formatTZLabel(tz)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-[11px] leading-snug text-muted-foreground">
+ {t(($) => $.preferences.timezone.hint)}
+ </p>
+ </section>
+ );
+}
diff --git a/server/cmd/backfill_task_usage_daily/main.go b/server/cmd/backfill_task_usage_daily/main.go
deleted file mode 100644
index 11e09058fe..0000000000
--- a/server/cmd/backfill_task_usage_daily/main.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Backfill_task_usage_daily seeds the `task_usage_daily` rollup table
-// from the historical contents of `task_usage`. Intended to be run once
-// after migrations 072..078 are applied, before flipping the
-// USAGE_DAILY_ROLLUP_ENABLED feature flag and before scheduling the
-// pg_cron job. The cron schedule is intentionally NOT created by a
-// migration (see 076 header) — operators run this backfill, then
-// schedule cron, then enable the read-path flag.
-//
-// Strategy:
-// 1. Walk the time range covered by task_usage in monthly slices.
-// 2. For each slice, call rollup_task_usage_daily_window(p_from, p_to)
-// — the same primitive the cron path uses, so semantics are
-// guaranteed identical.
-// 3. After all slices succeed, advance task_usage_rollup_state.watermark_at
-// to (now() - 5 minutes) so the cron tick that follows doesn't
-// reprocess the same window we just rolled up.
-//
-// Re-running IS safe. The window function (introduced in 073, refined in
-// 077) recomputes each dirty bucket from raw and REPLACES the daily row,
-// so rerunning a slice produces the same result. Use this property to
-// recover from partial backfill failures without TRUNCATEing
-// task_usage_daily first.
-package main
-
-import (
- "context"
- "flag"
- "fmt"
- "log/slog"
- "os"
- "time"
-
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/jackc/pgx/v5/pgxpool"
- "github.com/multica-ai/multica/server/internal/logger"
-)
-
-func main() {
- logger.Init()
-
- var (
- dryRun = flag.Bool("dry-run", false, "log slices that would be processed without touching task_usage_daily")
- monthsBack = flag.Int("months-back", 0, "limit backfill to the last N months (0 = all available history)")
- )
- flag.Parse()
-
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
- }
-
- ctx := context.Background()
- pool, err := pgxpool.New(ctx, dbURL)
- if err != nil {
- slog.Error("unable to connect to database", "error", err)
- os.Exit(1)
- }
- defer pool.Close()
-
- if err := pool.Ping(ctx); err != nil {
- slog.Error("unable to ping database", "error", err)
- os.Exit(1)
- }
-
- // Discover the time range we need to cover. If task_usage is empty
- // we just stamp the watermark to now and exit.
- var minTS, maxTS pgtype.Timestamptz
- if err := pool.QueryRow(ctx, `SELECT MIN(created_at), MAX(created_at) FROM task_usage`).Scan(&minTS, &maxTS); err != nil {
- slog.Error("scan task_usage time range", "error", err)
- os.Exit(1)
- }
- if !minTS.Valid {
- slog.Info("task_usage is empty; nothing to backfill")
- stampWatermark(ctx, pool)
- return
- }
-
- from := monthFloor(minTS.Time.UTC())
- end := monthFloor(maxTS.Time.UTC()).AddDate(0, 1, 0)
-
- if *monthsBack > 0 {
- cutoff := monthFloor(time.Now().UTC()).AddDate(0, -(*monthsBack), 0)
- if cutoff.After(from) {
- from = cutoff
- }
- }
-
- slog.Info("backfill range", "from", from.Format(time.RFC3339), "to", end.Format(time.RFC3339), "dry_run", *dryRun)
-
- cursor := from
- var totalRows int64
- for cursor.Before(end) {
- next := cursor.AddDate(0, 1, 0)
- if *dryRun {
- slog.Info("would roll up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339))
- cursor = next
- continue
- }
- var rows int64
- err := pool.QueryRow(
- ctx,
- `SELECT rollup_task_usage_daily_window($1::timestamptz, $2::timestamptz)`,
- cursor, next,
- ).Scan(&rows)
- if err != nil {
- slog.Error("rollup slice failed", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339), "error", err)
- os.Exit(1)
- }
- totalRows += rows
- slog.Info("rolled up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339), "rows_touched", rows)
- cursor = next
- }
-
- if !*dryRun {
- stampWatermark(ctx, pool)
- }
- slog.Info("backfill complete", "total_rows_touched", totalRows)
-}
-
-// stampWatermark moves the rollup state's watermark to (now() - 5 min)
-// so the next cron tick picks up only events newer than the backfill's
-// upper bound. Mirrors the same lag the cron uses to avoid racing
-// not-yet-visible inserts.
-func stampWatermark(ctx context.Context, pool *pgxpool.Pool) {
- tag, err := pool.Exec(ctx, `
- UPDATE task_usage_rollup_state
- SET watermark_at = now() - INTERVAL '5 minutes'
- WHERE id = 1
- `)
- if err != nil {
- slog.Error("stamp watermark failed", "error", err)
- os.Exit(1)
- }
- if tag.RowsAffected() == 0 {
- slog.Warn("no rollup state row to stamp; was migration 073 applied?")
- return
- }
- fmt.Println("watermark stamped to now() - 5 minutes")
-}
-
-func monthFloor(t time.Time) time.Time {
- return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
-}
diff --git a/server/cmd/backfill_task_usage_dashboard_daily/main.go b/server/cmd/backfill_task_usage_dashboard_daily/main.go
deleted file mode 100644
index 1437223727..0000000000
--- a/server/cmd/backfill_task_usage_dashboard_daily/main.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Backfill_task_usage_dashboard_daily seeds the dashboard rollup table
-// (`task_usage_dashboard_daily`, migration 084) from historical
-// `task_usage` rows. Run once after migration 084 ships, BEFORE enabling
-// USAGE_DASHBOARD_ROLLUP_ENABLED and scheduling the pg_cron job.
-//
-// Mirrors the per-runtime backfill in `cmd/backfill_task_usage_daily`:
-// walk task_usage's time range in monthly slices, call the same idempotent
-// window primitive the cron path uses, then stamp the rollup-state
-// watermark so the cron tick doesn't reprocess history.
-//
-// Re-running is safe — the window function recomputes each dirty bucket
-// from raw and REPLACES the daily row, so a partially completed backfill
-// can be re-run without TRUNCATEing.
-package main
-
-import (
- "context"
- "flag"
- "fmt"
- "log/slog"
- "os"
- "time"
-
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/jackc/pgx/v5/pgxpool"
- "github.com/multica-ai/multica/server/internal/logger"
-)
-
-func main() {
- logger.Init()
-
- var (
- dryRun = flag.Bool("dry-run", false, "log slices that would be processed without touching task_usage_dashboard_daily")
- monthsBack = flag.Int("months-back", 0, "limit backfill to the last N months (0 = all available history)")
- )
- flag.Parse()
-
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
- }
-
- ctx := context.Background()
- pool, err := pgxpool.New(ctx, dbURL)
- if err != nil {
- slog.Error("unable to connect to database", "error", err)
- os.Exit(1)
- }
- defer pool.Close()
-
- if err := pool.Ping(ctx); err != nil {
- slog.Error("unable to ping database", "error", err)
- os.Exit(1)
- }
-
- var minTS, maxTS pgtype.Timestamptz
- if err := pool.QueryRow(ctx, `SELECT MIN(created_at), MAX(created_at) FROM task_usage`).Scan(&minTS, &maxTS); err != nil {
- slog.Error("scan task_usage time range", "error", err)
- os.Exit(1)
- }
- if !minTS.Valid {
- slog.Info("task_usage is empty; nothing to backfill")
- stampWatermark(ctx, pool)
- return
- }
-
- from := monthFloor(minTS.Time.UTC())
- end := monthFloor(maxTS.Time.UTC()).AddDate(0, 1, 0)
-
- if *monthsBack > 0 {
- cutoff := monthFloor(time.Now().UTC()).AddDate(0, -(*monthsBack), 0)
- if cutoff.After(from) {
- from = cutoff
- }
- }
-
- slog.Info("backfill range", "from", from.Format(time.RFC3339), "to", end.Format(time.RFC3339), "dry_run", *dryRun)
-
- cursor := from
- var totalRows int64
- for cursor.Before(end) {
- next := cursor.AddDate(0, 1, 0)
- if *dryRun {
- slog.Info("would roll up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339))
- cursor = next
- continue
- }
- var rows int64
- err := pool.QueryRow(
- ctx,
- `SELECT rollup_task_usage_dashboard_daily_window($1::timestamptz, $2::timestamptz)`,
- cursor, next,
- ).Scan(&rows)
- if err != nil {
- slog.Error("rollup slice failed", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339), "error", err)
- os.Exit(1)
- }
- totalRows += rows
- slog.Info("rolled up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339), "rows_touched", rows)
- cursor = next
- }
-
- if !*dryRun {
- stampWatermark(ctx, pool)
- }
- slog.Info("backfill complete", "total_rows_touched", totalRows)
-}
-
-// stampWatermark moves the rollup state's watermark to (now() - 5 min) so
-// the cron tick that follows picks up only events newer than the backfill's
-// upper bound. Mirrors the per-runtime backfill's stampWatermark.
-func stampWatermark(ctx context.Context, pool *pgxpool.Pool) {
- tag, err := pool.Exec(ctx, `
- UPDATE task_usage_dashboard_rollup_state
- SET watermark_at = now() - INTERVAL '5 minutes'
- WHERE id = 1
- `)
- if err != nil {
- slog.Error("stamp watermark failed", "error", err)
- os.Exit(1)
- }
- if tag.RowsAffected() == 0 {
- slog.Warn("no rollup state row to stamp; was migration 084 applied?")
- return
- }
- fmt.Println("watermark stamped to now() - 5 minutes")
-}
-
-func monthFloor(t time.Time) time.Time {
- return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
-}
diff --git a/server/cmd/backfill_task_usage_hourly/main.go b/server/cmd/backfill_task_usage_hourly/main.go
new file mode 100644
index 0000000000..004d16af73
--- /dev/null
+++ b/server/cmd/backfill_task_usage_hourly/main.go
@@ -0,0 +1,219 @@
+// Backfill_task_usage_hourly seeds the unified hourly rollup table
+// (`task_usage_hourly`) from historical `task_usage`
+// rows. Run once after the hourly-pipeline migrations ship, BEFORE registering
+// the pg_cron job for rollup_task_usage_hourly().
+//
+// SELF-HOST UPGRADE ORDER — migrations 100–104 are one group, but they
+// must NOT be applied in a single `make migrate-up`:
+//
+// 1. Apply 101+102 (creates task_usage_hourly + installs the triggers).
+// 2. Run THIS backfill to seed historical buckets.
+// 3. Apply 103+104 (drops the legacy daily rollups + runtime.timezone)
+// and register the pg_cron job.
+//
+// If you run `migrate-up` straight through to 103/104 before this
+// backfill, the legacy daily pipelines are gone while task_usage_hourly
+// only holds buckets the triggers wrote since 102 — dashboards will show
+// empty history until backfill + cron catch up (tens to hundreds of
+// ticks on a DB with years of data, given the per-tick 1-day cap).
+//
+// Mirrors backfill_task_usage_dashboard_daily: walk task_usage's time
+// range in monthly slices and call the same idempotent window
+// primitive the cron path uses. Then stamp the rollup-state watermark
+// so the first cron tick after backfill does not reprocess history.
+//
+// Re-running is safe — rollup_task_usage_hourly_window is idempotent
+// (recomputes each dirty key from raw and REPLACES the bucket), so a
+// partially completed backfill can be resumed without TRUNCATEing
+// task_usage_hourly first.
+//
+// Read pressure: each slice scans task_usage / agent_task_queue / agent
+// / issue. On a database with years of history that is sustained heavy
+// load. Use --sleep-between-slices to throttle on a busy production DB,
+// and coordinate a maintenance window with the DB team before a
+// full-history run (see docs/timezone-architecture-rfc.md §7.1).
+//
+// Operator note: this command does NOT call prune_task_usage_hourly_dirty.
+// The dirty queue starts empty during backfill (triggers fire only on
+// future writes), so there is nothing to prune until the rollup worker
+// has been running for a while.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/logger"
+)
+
+func main() {
+ logger.Init()
+ if err := run(); err != nil {
+ slog.Error("backfill failed", "error", err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ var (
+ dryRun = flag.Bool("dry-run", false, "log slices that would be processed without touching task_usage_hourly")
+ monthsBack = flag.Int("months-back", 0, "limit backfill to the last N months (0 = all available history)")
+ forcePartial = flag.Bool("force-partial", false, "acknowledge that --months-back permanently abandons buckets older than the cutoff (the watermark still advances past them)")
+ sleep = flag.Duration("sleep-between-slices", 0, "pause this long between monthly slices to throttle source-table read pressure on a busy DB (e.g. 2s)")
+ )
+ flag.Parse()
+
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+
+ // SIGINT/SIGTERM cancels ctx so an in-flight slice stops cleanly —
+ // each slice runs in its own transaction (the window function), so
+ // Postgres rolls back the interrupted one and the idempotent design
+ // lets a later run resume from where this one stopped.
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ return fmt.Errorf("connect to database: %w", err)
+ }
+ defer pool.Close()
+
+ if err := pool.Ping(ctx); err != nil {
+ return fmt.Errorf("ping database: %w", err)
+ }
+
+ // Serialise against the cron rollup and any other backfill run via
+ // advisory lock 4246 — the same id the cron entry checks with
+ // pg_try_advisory_lock. While this backfill holds it, the cron tick
+ // no-ops instead of racing on task_usage_hourly row locks; a second
+ // concurrent backfill blocks here until this one finishes. The lock
+ // is held on a dedicated session connection for the whole run.
+ lockConn, err := pool.Acquire(ctx)
+ if err != nil {
+ return fmt.Errorf("acquire advisory-lock connection: %w", err)
+ }
+ defer lockConn.Release()
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock(4246)`); err != nil {
+ return fmt.Errorf("acquire advisory lock 4246: %w", err)
+ }
+ defer func() {
+ // Unlock on a fresh context so a cancelled ctx (SIGINT) does not
+ // skip the release. Releasing the connection afterwards would end
+ // the session anyway, but an explicit unlock frees it immediately.
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock(4246)`)
+ }()
+
+ var minTS, maxTS pgtype.Timestamptz
+ if err := pool.QueryRow(ctx, `SELECT MIN(created_at), MAX(created_at) FROM task_usage`).Scan(&minTS, &maxTS); err != nil {
+ return fmt.Errorf("scan task_usage time range: %w", err)
+ }
+ if !minTS.Valid {
+ slog.Info("task_usage is empty; nothing to backfill")
+ if *dryRun {
+ return nil
+ }
+ return stampWatermark(ctx, pool)
+ }
+
+ from := monthFloor(minTS.Time.UTC())
+ end := monthFloor(maxTS.Time.UTC()).AddDate(0, 1, 0)
+
+ if *monthsBack > 0 {
+ cutoff := monthFloor(time.Now().UTC()).AddDate(0, -(*monthsBack), 0)
+ // A partial backfill still stamps the watermark at now()-5min, so
+ // buckets older than the cutoff are abandoned permanently: the cron
+ // worker will never look back that far. That data loss must be an
+ // explicit operator decision — require --force-partial to proceed.
+ if cutoff.After(from) {
+ if !*forcePartial {
+ return fmt.Errorf("--months-back=%d would skip buckets before %s (oldest available %s) and the watermark would still advance past them; re-run with --force-partial to accept this, or omit --months-back for a full backfill",
+ *monthsBack, cutoff.Format(time.RFC3339), minTS.Time.UTC().Format(time.RFC3339))
+ }
+ from = cutoff
+ slog.Warn("partial backfill: --months-back limits coverage; older buckets will be left empty and the watermark will still advance past them",
+ "months_back", *monthsBack, "effective_from", from.Format(time.RFC3339),
+ "oldest_available", minTS.Time.UTC().Format(time.RFC3339))
+ }
+ }
+
+ slog.Info("backfill range", "from", from.Format(time.RFC3339), "to", end.Format(time.RFC3339), "dry_run", *dryRun, "sleep_between_slices", sleep.String())
+
+ cursor := from
+ var totalRows int64
+ for cursor.Before(end) {
+ next := cursor.AddDate(0, 1, 0)
+ if *dryRun {
+ slog.Info("would roll up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339))
+ cursor = next
+ continue
+ }
+ var rows int64
+ err := pool.QueryRow(
+ ctx,
+ `SELECT rollup_task_usage_hourly_window($1::timestamptz, $2::timestamptz)`,
+ cursor, next,
+ ).Scan(&rows)
+ if err != nil {
+ return fmt.Errorf("rollup slice %s..%s: %w", cursor.Format(time.RFC3339), next.Format(time.RFC3339), err)
+ }
+ totalRows += rows
+ slog.Info("rolled up slice", "from", cursor.Format(time.RFC3339), "to", next.Format(time.RFC3339), "rows_touched", rows)
+ cursor = next
+ if *sleep > 0 && cursor.Before(end) {
+ select {
+ case <-time.After(*sleep):
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ }
+
+ if *dryRun {
+ slog.Info("dry-run complete; watermark left untouched")
+ return nil
+ }
+ // Stamp on a fresh context so a SIGINT arriving after the slices
+ // complete cannot skip the watermark UPDATE — losing it would force the
+ // next run to restart from epoch. Mirrors the deferred advisory-unlock.
+ if err := stampWatermark(context.Background(), pool); err != nil {
+ return err
+ }
+ slog.Info("backfill complete", "total_rows_touched", totalRows)
+ return nil
+}
+
+// stampWatermark moves the hourly rollup state's watermark to
+// `now() - 5 min`, mirroring the cron entry's upper bound. The next
+// scheduled tick therefore picks up only events newer than the
+// backfill horizon and does not redo work the backfill already did.
+func stampWatermark(ctx context.Context, pool *pgxpool.Pool) error {
+ tag, err := pool.Exec(ctx, `
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = now() - INTERVAL '5 minutes'
+ WHERE id = 1
+ `)
+ if err != nil {
+ return fmt.Errorf("stamp watermark: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ slog.Warn("no rollup state row to stamp; was the task_usage_hourly schema migration applied?")
+ return nil
+ }
+ fmt.Println("watermark stamped to now() - 5 minutes")
+ return nil
+}
+
+func monthFloor(t time.Time) time.Time {
+ return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 633ff12f3a..2c8a7f2c02 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -131,15 +131,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
cfSigner := auth.NewCloudFrontSignerFromEnv()
signupConfig := handler.Config{
- AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
- AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),
- AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),
- UseDailyRollupForRuntimeUsage: os.Getenv("USAGE_DAILY_ROLLUP_ENABLED") == "true",
- UseDailyRollupForDashboard: os.Getenv("USAGE_DASHBOARD_ROLLUP_ENABLED") == "true",
- PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),
- TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
- CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),
- CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),
+ AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
+ AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),
+ AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),
+ PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),
+ TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
+ CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),
+ CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
if opts.DaemonWakeup != nil {
@@ -554,12 +552,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
})
- // Usage
- r.Route("/api/usage", func(r chi.Router) {
- r.Get("/daily", h.GetWorkspaceUsageByDay)
- r.Get("/summary", h.GetWorkspaceUsageSummary)
- })
-
// Dashboard — workspace-wide token + run-time rollups for the
// "/{slug}/dashboard" page. Optional ?project_id filter scopes
// the rollup to a single project.
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 76a15c5bf8..3c612530e7 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -742,7 +742,6 @@ 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,
}
@@ -757,41 +756,6 @@ 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/auth.go b/server/internal/handler/auth.go
index cc895baf83..3688bad69b 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -54,6 +54,8 @@ type UserResponse struct {
Email string `json:"email"`
AvatarURL *string `json:"avatar_url"`
Language *string `json:"language"`
+ // Pinned IANA tz; nil = no preference (use browser-detected tz).
+ Timezone *string `json:"timezone"`
OnboardedAt *string `json:"onboarded_at"`
OnboardingQuestionnaire json.RawMessage `json:"onboarding_questionnaire"`
StarterContentState *string `json:"starter_content_state"`
@@ -82,6 +84,7 @@ func userToResponse(u db.User) UserResponse {
Email: u.Email,
AvatarURL: textToPtr(u.AvatarUrl),
Language: textToPtr(u.Language),
+ Timezone: textToPtr(u.Timezone),
OnboardedAt: timestampToPtr(u.OnboardedAt),
OnboardingQuestionnaire: json.RawMessage(q),
StarterContentState: textToPtr(u.StarterContentState),
@@ -434,6 +437,8 @@ type UpdateMeRequest struct {
AvatarURL *string `json:"avatar_url"`
Language *string `json:"language"`
ProfileDescription *string `json:"profile_description"`
+ // IANA tz to pin; "" clears back to NULL; nil leaves untouched.
+ Timezone *string `json:"timezone"`
}
type GoogleLoginRequest struct {
@@ -690,6 +695,20 @@ func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
params.ProfileDescription = pgtype.Text{String: desc, Valid: true}
}
+ if req.Timezone != nil {
+ // Valid=false → column untouched; Valid=true + "" → clear to
+ // NULL; Valid=true + IANA → set. Three-way semantics enforced
+ // in the UpdateUser SQL CASE.
+ tz := strings.TrimSpace(*req.Timezone)
+ if tz != "" {
+ if loc, err := time.LoadLocation(tz); err != nil || loc == nil {
+ writeError(w, http.StatusBadRequest, "invalid timezone")
+ return
+ }
+ }
+ params.Timezone = pgtype.Text{String: tz, Valid: true}
+ }
+
updatedUser, err := h.Queries.UpdateUser(r.Context(), params)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update user")
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 4e8f52e312..41eed956e1 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -161,15 +161,6 @@ 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
- // 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"`
@@ -185,24 +176,6 @@ type daemonWorkspaceReposResponse struct {
Settings json.RawMessage `json:"settings,omitempty"`
}
-// 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{}
@@ -355,7 +328,6 @@ 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(
@@ -386,7 +358,6 @@ 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/dashboard.go b/server/internal/handler/dashboard.go
index 738a788f86..679c5a310d 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -65,10 +65,8 @@ type DashboardUsageDailyResponse struct {
}
// GetDashboardUsageDaily returns per-(date, model) token rows for the
-// workspace, optionally scoped to a project. When the dashboard rollup
-// is enabled (USAGE_DASHBOARD_ROLLUP_ENABLED=true) reads come from
-// `task_usage_dashboard_daily` (migration 084); otherwise from the raw
-// task_usage stream.
+// workspace, optionally scoped to a project. Backed by task_usage_hourly,
+// sliced into calendar days under the viewer's tz.
func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
@@ -78,9 +76,10 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- since := parseSinceParam(r, 30)
+ tz := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, tz)
- resp, err := h.listDashboardUsageDaily(r.Context(), parseUUID(workspaceID), since, projectID)
+ resp, err := h.listDashboardUsageDaily(r.Context(), parseUUID(workspaceID), tz, since, projectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list usage")
return
@@ -91,34 +90,13 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)
func (h *Handler) listDashboardUsageDaily(
ctx context.Context,
workspaceID pgtype.UUID,
+ tz string,
since pgtype.Timestamptz,
projectID pgtype.UUID,
) ([]DashboardUsageDailyResponse, error) {
- if h.cfg.UseDailyRollupForDashboard {
- rows, err := h.Queries.ListDashboardUsageDailyRollup(ctx, db.ListDashboardUsageDailyRollupParams{
- WorkspaceID: workspaceID,
- Since: since,
- ProjectID: projectID,
- })
- if err != nil {
- return nil, err
- }
- resp := make([]DashboardUsageDailyResponse, len(rows))
- for i, row := range rows {
- resp[i] = DashboardUsageDailyResponse{
- Date: row.Date.Time.Format("2006-01-02"),
- Model: row.Model,
- InputTokens: row.InputTokens,
- OutputTokens: row.OutputTokens,
- CacheReadTokens: row.CacheReadTokens,
- CacheWriteTokens: row.CacheWriteTokens,
- TaskCount: row.TaskCount,
- }
- }
- return resp, nil
- }
rows, err := h.Queries.ListDashboardUsageDaily(ctx, db.ListDashboardUsageDailyParams{
WorkspaceID: workspaceID,
+ Tz: tz,
Since: since,
ProjectID: projectID,
})
@@ -151,10 +129,9 @@ type DashboardUsageByAgentResponse struct {
TaskCount int32 `json:"task_count"`
}
-// GetDashboardUsageByAgent returns per-(agent, model) token aggregates for
-// the workspace, optionally scoped to a project. Switches to the rollup
-// table when UseDailyRollupForDashboard is on (same gating as the daily
-// endpoint above).
+// GetDashboardUsageByAgent returns per-(agent, model) token aggregates
+// for the workspace, optionally scoped to a project. Backed by
+// task_usage_hourly with the viewer's tz applied to the `?days=` cutoff.
func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
@@ -164,7 +141,10 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
- since := parseSinceParam(r, 30)
+ // "By agent" has no date grouping in the SQL — tz only determines
+ // the cutoff boundary, not the bucket axis.
+ tz := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, tz)
resp, err := h.listDashboardUsageByAgent(r.Context(), parseUUID(workspaceID), since, projectID)
if err != nil {
@@ -180,29 +160,6 @@ func (h *Handler) listDashboardUsageByAgent(
since pgtype.Timestamptz,
projectID pgtype.UUID,
) ([]DashboardUsageByAgentResponse, error) {
- if h.cfg.UseDailyRollupForDashboard {
- rows, err := h.Queries.ListDashboardUsageByAgentRollup(ctx, db.ListDashboardUsageByAgentRollupParams{
- WorkspaceID: workspaceID,
- Since: since,
- ProjectID: projectID,
- })
- if err != nil {
- return nil, err
- }
- resp := make([]DashboardUsageByAgentResponse, len(rows))
- for i, row := range rows {
- resp[i] = DashboardUsageByAgentResponse{
- AgentID: uuidToString(row.AgentID),
- Model: row.Model,
- InputTokens: row.InputTokens,
- OutputTokens: row.OutputTokens,
- CacheReadTokens: row.CacheReadTokens,
- CacheWriteTokens: row.CacheWriteTokens,
- TaskCount: row.TaskCount,
- }
- }
- return resp, nil
- }
rows, err := h.Queries.ListDashboardUsageByAgent(ctx, db.ListDashboardUsageByAgentParams{
WorkspaceID: workspaceID,
Since: since,
@@ -250,7 +207,10 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
- since := parseSinceParam(r, 30)
+ // Cutoff in the viewer's tz so the "last N days" window matches the
+ // per-agent cost card (GetDashboardUsageByAgent).
+ tz := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, tz)
rows, err := h.Queries.ListDashboardAgentRunTime(r.Context(), db.ListDashboardAgentRunTimeParams{
WorkspaceID: parseUUID(workspaceID),
@@ -298,10 +258,14 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
- since := parseSinceParam(r, 30)
+ // Slice day buckets in the viewer's tz so the Time / Tasks charts cut
+ // their calendar day identically to the Cost / Tokens charts.
+ tz := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, tz)
rows, err := h.Queries.ListDashboardRunTimeDaily(r.Context(), db.ListDashboardRunTimeDailyParams{
WorkspaceID: parseUUID(workspaceID),
+ Tz: tz,
Since: since,
ProjectID: projectID,
})
diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.go
index 0624834263..bff5c339e6 100644
--- a/server/internal/handler/dashboard_test.go
+++ b/server/internal/handler/dashboard_test.go
@@ -99,6 +99,16 @@ func TestDashboardEndpoints(t *testing.T) {
mkTaskWithUsage(projectIssueID, "completed", 1000)
mkTaskWithUsage(otherIssueID, "completed", 500)
+ // All dashboard endpoints now read from task_usage_hourly (post-RFC
+ // Phase 3). Drive the underlying window function directly so the
+ // freshly inserted fixture rows are aggregated before assertions —
+ // in production the cron tick handles this with a 5-min lag.
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("rollup window: %v", err)
+ }
+
type dailyRow struct {
Date string `json:"date"`
Model string `json:"model"`
@@ -215,50 +225,13 @@ func TestDashboardEndpoints(t *testing.T) {
}
}
- // Rollup path — run the dashboard window function, flip the feature
- // flag, and verify daily + by-agent reads come back with the same
- // project-filtered totals. The raw path above already passed, so this
- // validates that the rollup table mirrors the raw aggregation
- // (modulo project_id snapshot semantics, which match here since
- // nothing has changed since the rows were created).
+ // Workspace-wide by-agent through the same rollup, just to confirm
+ // the no-project-filter shape matches up.
{
- // rollup the full window in one shot; same idempotent primitive
- // the cron path uses.
- if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
- `); err != nil {
- t.Fatalf("rollup window: %v", err)
- }
- origRollup := testHandler.cfg.UseDailyRollupForDashboard
- testHandler.cfg.UseDailyRollupForDashboard = true
- t.Cleanup(func() { testHandler.cfg.UseDailyRollupForDashboard = origRollup })
-
- // daily — project-scoped through rollup
w := httptest.NewRecorder()
- testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=1&project_id="+projectID, nil))
- if w.Code != http.StatusOK {
- t.Fatalf("rollup daily: expected 200, got %d: %s", w.Code, w.Body.String())
- }
- var dRows []dailyRow
- _ = json.NewDecoder(w.Body).Decode(&dRows)
- var dTotal int64
- for _, r := range dRows {
- if r.Model == "claude-3-5-sonnet" {
- dTotal += r.InputTokens
- }
- }
- if dTotal < 1000 {
- t.Errorf("rollup daily project: expected >=1000 tokens, got %d", dTotal)
- }
- if dTotal >= 1500 {
- t.Errorf("rollup daily project: filter leaked — expected <1500, got %d", dTotal)
- }
-
- // by-agent — workspace-wide through rollup
- w = httptest.NewRecorder()
testHandler.GetDashboardUsageByAgent(w, newRequest("GET", "/api/dashboard/usage/by-agent?days=1", nil))
if w.Code != http.StatusOK {
- t.Fatalf("rollup by-agent: expected 200, got %d: %s", w.Code, w.Body.String())
+ t.Fatalf("by-agent ws: expected 200, got %d: %s", w.Code, w.Body.String())
}
var aRows []byAgentRow
_ = json.NewDecoder(w.Body).Decode(&aRows)
@@ -269,9 +242,491 @@ func TestDashboardEndpoints(t *testing.T) {
}
}
if aTotal < 1500 {
- t.Errorf("rollup by-agent: expected >=1500 tokens across workspace, got %d", aTotal)
+ t.Errorf("by-agent ws: expected >=1500 tokens across workspace, got %d", aTotal)
+ }
+ }
+}
+
+// TestDashboardUsageDailyBucketsByViewerTimezone proves the `?tz=` query
+// param drives the calendar-day boundary: the same UTC instant lands under
+// a different `date` for a UTC viewer vs an America/Los_Angeles viewer.
+// This is the core promise of the timezone-architecture RFC.
+func TestDashboardUsageDailyBucketsByViewerTimezone(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ 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)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE runtime_id = $1 AND provider = 'tz-bucket-test'`, runtimeID)
+ })
+ // One bucket at 04:00 UTC two days ago. 04:00 UTC is still the
+ // previous evening in America/Los_Angeles (UTC-7/-8), so the UTC
+ // viewer and the LA viewer must see this row under different dates.
+ var bucketHour time.Time
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO task_usage_hourly (
+ bucket_hour, workspace_id, runtime_id, agent_id, project_id,
+ provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, event_count
+ )
+ VALUES (
+ ((CURRENT_DATE - 2)::timestamp + interval '4 hours') AT TIME ZONE 'UTC',
+ $1, $2, $3, NULL, 'tz-bucket-test', 'tz-bucket-model',
+ 999, 0, 0, 0, 1
+ )
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE
+ SET input_tokens = EXCLUDED.input_tokens
+ RETURNING bucket_hour
+ `, testWorkspaceID, runtimeID, agentID).Scan(&bucketHour); err != nil {
+ t.Fatalf("seed hourly row: %v", err)
+ }
+
+ utcDate := bucketHour.UTC().Format("2006-01-02")
+ laLoc, err := time.LoadLocation("America/Los_Angeles")
+ if err != nil {
+ t.Fatalf("load LA location: %v", err)
+ }
+ laDate := bucketHour.In(laLoc).Format("2006-01-02")
+ if utcDate == laDate {
+ t.Fatalf("test setup: UTC and LA dates must differ, both %s", utcDate)
+ }
+
+ readDate := func(tz string) string {
+ w := httptest.NewRecorder()
+ testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=10&tz="+tz, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("tz=%s: expected 200, got %d: %s", tz, w.Code, w.Body.String())
+ }
+ var rows []struct {
+ Date string `json:"date"`
+ Model string `json:"model"`
+ }
+ _ = json.NewDecoder(w.Body).Decode(&rows)
+ for _, r := range rows {
+ if r.Model == "tz-bucket-model" {
+ return r.Date
+ }
+ }
+ t.Fatalf("tz=%s: tz-bucket-model row not found in %v", tz, rows)
+ return ""
+ }
+
+ if got := readDate("UTC"); got != utcDate {
+ t.Errorf("UTC viewer: expected date %s, got %s", utcDate, got)
+ }
+ if got := readDate("America/Los_Angeles"); got != laDate {
+ t.Errorf("LA viewer: expected date %s, got %s", laDate, got)
+ }
+}
+
+// TestDashboardRunTimeDailyBucketsByViewerTimezone proves the `?tz=` query
+// param drives the calendar-day boundary of the Time / Tasks dashboard tab:
+// GetDashboardRunTimeDaily applies `@tz` to `completed_at AT TIME ZONE @tz`
+// on agent_task_queue. A task completed at 04:00 UTC is still the previous
+// evening in America/Los_Angeles (UTC-7/-8), so the LA viewer must see the
+// row under the prior calendar date relative to a UTC viewer.
+func TestDashboardRunTimeDailyBucketsByViewerTimezone(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ 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)
+ }
+
+ // Issue tagged so we can clean up just this test's rows.
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'runtime-daily tz test', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ // completed_at at 04:00 UTC two days ago — still the prior evening in LA.
+ // started_at 10 minutes earlier so the run has a non-zero duration.
+ var completedAt time.Time
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)
+ VALUES (
+ $1, $2, $3, 'completed',
+ ((CURRENT_DATE - 2)::timestamp + interval '3 hours 50 minutes') AT TIME ZONE 'UTC',
+ ((CURRENT_DATE - 2)::timestamp + interval '4 hours') AT TIME ZONE 'UTC',
+ now()
+ )
+ RETURNING id, completed_at
+ `, agentID, issueID, runtimeID).Scan(&taskID, &completedAt); err != nil {
+ t.Fatalf("insert completed task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ utcDate := completedAt.UTC().Format("2006-01-02")
+ laLoc, err := time.LoadLocation("America/Los_Angeles")
+ if err != nil {
+ t.Fatalf("load LA location: %v", err)
+ }
+ laDate := completedAt.In(laLoc).Format("2006-01-02")
+ if utcDate == laDate {
+ t.Fatalf("test setup: UTC and LA dates must differ, both %s", utcDate)
+ }
+
+ readRow := func(tz string) (string, int64, int32) {
+ w := httptest.NewRecorder()
+ testHandler.GetDashboardRunTimeDaily(w, newRequest("GET", "/api/dashboard/runtime/daily?days=10&tz="+tz, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("tz=%s: expected 200, got %d: %s", tz, w.Code, w.Body.String())
+ }
+ var rows []struct {
+ Date string `json:"date"`
+ TotalSeconds int64 `json:"total_seconds"`
+ TaskCount int32 `json:"task_count"`
+ }
+ _ = json.NewDecoder(w.Body).Decode(&rows)
+ want := utcDate
+ if tz == "America/Los_Angeles" {
+ want = laDate
+ }
+ for _, r := range rows {
+ if r.Date == want {
+ return r.Date, r.TotalSeconds, r.TaskCount
+ }
+ }
+ t.Fatalf("tz=%s: no row on expected date %s in %v", tz, want, rows)
+ return "", 0, 0
+ }
+
+ if date, secs, count := readRow("UTC"); date != utcDate || count < 1 || secs < 600 {
+ t.Errorf("UTC viewer: got date=%s seconds=%d count=%d, want date=%s seconds>=600 count>=1",
+ date, secs, count, utcDate)
+ }
+ if date, secs, count := readRow("America/Los_Angeles"); date != laDate || count < 1 || secs < 600 {
+ t.Errorf("LA viewer: got date=%s seconds=%d count=%d, want date=%s seconds>=600 count>=1",
+ date, secs, count, laDate)
+ }
+}
+
+// TestRollupTaskUsageHourlyIdempotentAndWatermark covers two pipeline
+// invariants the deleted runtime_rollup_test.go used to guard for the
+// legacy daily rollup: (1) re-running the window function over the same
+// range produces identical totals, and (2) the cron entry point advances
+// the rollup-state watermark and clears last_error.
+func TestRollupTaskUsageHourlyIdempotentAndWatermark(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ 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, taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'rollup idempotency', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)
+ VALUES ($1, $2, $3, 'completed', now() - interval '20 minutes') RETURNING id
+ `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES ($1, 'claude', 'rollup-idem-model', 3333, 0, now() - interval '20 minutes')
+ `, taskID); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+
+ readTotal := func() int64 {
+ var total int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
+ WHERE runtime_id = $1 AND model = 'rollup-idem-model'
+ `, runtimeID).Scan(&total); err != nil {
+ t.Fatalf("read total: %v", err)
+ }
+ return total
+ }
+
+ // Idempotency: two passes over the same range must not double-count.
+ for i := 0; i < 2; i++ {
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("rollup pass %d: %v", i, err)
+ }
+ }
+ if got := readTotal(); got != 3333 {
+ t.Errorf("idempotency: expected exactly 3333 tokens after two passes, got %d", got)
+ }
+
+ // Watermark advance: park the watermark an hour back, run the cron
+ // entry, confirm it moved forward to ~now()-5min with no error.
+ if _, err := testPool.Exec(ctx, `
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = now() - interval '1 hour', last_error = 'stale'
+ WHERE id = 1
+ `); err != nil {
+ t.Fatalf("park watermark: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {
+ t.Fatalf("rollup_task_usage_hourly: %v", err)
+ }
+ var watermarkAge time.Duration
+ var lastError *string
+ var ageSeconds float64
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXTRACT(EPOCH FROM (now() - watermark_at)), last_error
+ FROM task_usage_hourly_rollup_state WHERE id = 1
+ `).Scan(&ageSeconds, &lastError); err != nil {
+ t.Fatalf("read rollup state: %v", err)
+ }
+ watermarkAge = time.Duration(ageSeconds) * time.Second
+ // Watermark should sit at now()-5min (the cron upper bound), well
+ // short of the 1-hour-back value we parked it at.
+ if watermarkAge > 10*time.Minute {
+ t.Errorf("watermark did not advance: still %s behind now()", watermarkAge)
+ }
+ if lastError != nil {
+ t.Errorf("expected last_error cleared, got %q", *lastError)
+ }
+}
+
+// TestRollupTaskUsageHourlyReassignBetweenRuntimes ports the invalidation
+// coverage the deleted runtime_rollup_test.go held for the legacy daily
+// rollup. Reassigning a task between runtimes (the runtime-merge path) must
+// move its usage: the `trg_atq_dirty_hourly` trigger enqueues both the old
+// and new runtime buckets, and the next window run drains the queue,
+// empties the old bucket, and fills the new one. Without this the rollup
+// keeps attributing usage to the merged-away runtime.
+func TestRollupTaskUsageHourlyReassignBetweenRuntimes(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ oldRuntimeID := handlerTestRuntimeID(t)
+ var newRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, 'reassign-target-hourly', 'cloud', 'reassign-target-hourly', 'online', '{}'::jsonb, '{}'::jsonb, now())
+ RETURNING id
+ `, testWorkspaceID).Scan(&newRuntimeID); err != nil {
+ t.Fatalf("create dest runtime: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, newRuntimeID) })
+
+ 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, number)
+ VALUES ($1, 'reassign hourly test', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ usageAt := time.Date(2021, 3, 14, 1, 0, 0, 0, time.UTC)
+ 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, oldRuntimeID, usageAt).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at, updated_at)
+ VALUES ($1, 'claude', 'm-reassign-hourly', 700, 70, $2, $2)
+ `, taskID, usageAt); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'm-reassign-hourly'`)
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'm-reassign-hourly'`)
+ })
+
+ runWindow := func(label string) {
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('-infinity'::timestamptz, 'infinity'::timestamptz)
+ `); err != nil {
+ t.Fatalf("%s: %v", label, err)
}
}
+ runtimeTotal := func(rt string) int64 {
+ var total int64
+ testPool.QueryRow(ctx, `
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
+ WHERE runtime_id = $1 AND model = 'm-reassign-hourly'
+ `, rt).Scan(&total)
+ return total
+ }
+
+ runWindow("initial rollup")
+ if old, new := runtimeTotal(oldRuntimeID), runtimeTotal(newRuntimeID); old != 700 || new != 0 {
+ t.Fatalf("initial: expected old=700 new=0, got old=%d new=%d", old, new)
+ }
+
+ // Reassignment fires trg_atq_dirty_hourly, which enqueues the OLD and
+ // NEW runtime buckets (same bucket_hour, two runtime_ids).
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, newRuntimeID, taskID); err != nil {
+ t.Fatalf("reassign task: %v", err)
+ }
+ var dirtyCount int
+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE model = 'm-reassign-hourly'`).Scan(&dirtyCount)
+ if dirtyCount != 2 {
+ t.Fatalf("expected 2 dirty entries (old+new runtime), got %d", dirtyCount)
+ }
+
+ runWindow("rollup after reassign")
+ if old, new := runtimeTotal(oldRuntimeID), runtimeTotal(newRuntimeID); old != 0 || new != 700 {
+ t.Fatalf("after reassign: expected old=0 new=700, got old=%d new=%d", old, new)
+ }
+ // The window function must drain every queue row whose enqueued_at
+ // predates p_to — a regression on that DELETE pins recomputes forever.
+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE model = 'm-reassign-hourly'`).Scan(&dirtyCount)
+ if dirtyCount != 0 {
+ t.Errorf("expected dirty queue drained, got %d entries", dirtyCount)
+ }
+}
+
+// TestRollupTaskUsageHourlyWorkspaceMismatch constructs an atq row whose
+// agent.workspace_id differs from issue.workspace_id and verifies the
+// hourly rollup resolves workspace_id consistently from `agent` across the
+// trigger, dirty_from_updates, and the recompute join. If any path leaked
+// back to issue.workspace_id the dirty key would miss the recompute join
+// and the bucket would be dropped or mis-attributed across tenants. The
+// schema does not enforce the two workspace_ids match, so this canary
+// keeps the alignment honest.
+func TestRollupTaskUsageHourlyWorkspaceMismatch(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var foreignWorkspaceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug)
+ VALUES ('ws-mismatch-hourly', 'ws-mismatch-hourly-' || gen_random_uuid()::text)
+ RETURNING id
+ `).Scan(&foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID) })
+
+ var foreignRuntimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, 'mismatch-rt-hourly', 'cloud', 'mismatch-rt-hourly', 'online', '{}'::jsonb, '{}'::jsonb, now())
+ RETURNING id
+ `, foreignWorkspaceID).Scan(&foreignRuntimeID); err != nil {
+ t.Fatalf("create foreign runtime: %v", err)
+ }
+ var foreignAgentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id,
+ instructions, custom_env, custom_args, mcp_config
+ )
+ VALUES ($1, 'mismatch-agent-hourly', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3, '', '{}'::jsonb, '[]'::jsonb, '[]'::jsonb)
+ RETURNING id
+ `, foreignWorkspaceID, foreignRuntimeID, testUserID).Scan(&foreignAgentID); err != nil {
+ t.Fatalf("create foreign agent: %v", err)
+ }
+
+ // Issue lives in the primary test workspace; the agent lives in the
+ // foreign one — so agent.workspace_id != issue.workspace_id.
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'mismatch hourly test', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ usageAt := time.Date(2021, 9, 9, 1, 0, 0, 0, time.UTC)
+ 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
+ `, foreignAgentID, issueID, foreignRuntimeID, usageAt).Scan(&taskID); err != nil {
+ t.Fatalf("insert atq: %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', 'm-mismatch-hourly', 333, 33, $2, $2)
+ `, taskID, usageAt); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'm-mismatch-hourly'`)
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'm-mismatch-hourly'`)
+ })
+
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('-infinity'::timestamptz, 'infinity'::timestamptz)
+ `); err != nil {
+ t.Fatalf("rollup: %v", err)
+ }
+
+ wsTotal := func(ws string) int64 {
+ var total int64
+ testPool.QueryRow(ctx, `
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
+ WHERE workspace_id = $1 AND model = 'm-mismatch-hourly'
+ `, ws).Scan(&total)
+ return total
+ }
+ if got := wsTotal(foreignWorkspaceID); got != 333 {
+ t.Fatalf("expected foreign workspace bucket = 333 (resolved from agent), got %d", got)
+ }
+ if got := wsTotal(testWorkspaceID); got != 0 {
+ t.Errorf("expected primary workspace bucket = 0 (issue.workspace_id must not leak), got %d", got)
+ }
}
// TestDashboardRollupReattributesOnProjectChange verifies the trigger that
@@ -335,13 +790,13 @@ func TestDashboardRollupReattributesOnProjectChange(t *testing.T) {
// First rollup pass: tokens attributed to project A.
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup A: %v", err)
}
var aTokens int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3
`, testWorkspaceID, projectA, agentID).Scan(&aTokens); err != nil {
t.Fatalf("read A rollup: %v", err)
@@ -357,20 +812,20 @@ func TestDashboardRollupReattributesOnProjectChange(t *testing.T) {
// Second rollup pass: A bucket drops to zero (deleted_empty), B
// bucket gets the tokens.
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup B: %v", err)
}
var bTokens, aTokensAfter int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3
`, testWorkspaceID, projectB, agentID).Scan(&bTokens); err != nil {
t.Fatalf("read B rollup: %v", err)
}
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3
`, testWorkspaceID, projectA, agentID).Scan(&aTokensAfter); err != nil {
t.Fatalf("read A rollup after move: %v", err)
@@ -440,13 +895,13 @@ func TestDashboardRollupClearsOnIssueDelete(t *testing.T) {
// First rollup: project bucket exists with 4242 tokens.
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup before delete: %v", err)
}
var before int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2
`, testWorkspaceID, projectID).Scan(&before); err != nil {
t.Fatalf("read before: %v", err)
@@ -463,13 +918,13 @@ func TestDashboardRollupClearsOnIssueDelete(t *testing.T) {
}
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup after delete: %v", err)
}
var after int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2
`, testWorkspaceID, projectID).Scan(&after); err != nil {
t.Fatalf("read after: %v", err)
@@ -517,13 +972,13 @@ func TestDashboardRollupReattributesOnLinkTaskToIssue(t *testing.T) {
// First rollup: tokens attributed to the no-project bucket (NULL).
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup pre-link: %v", err)
}
var nullBefore int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id IS NULL AND agent_id = $2
`, testWorkspaceID, agentID).Scan(&nullBefore); err != nil {
t.Fatalf("read NULL bucket pre-link: %v", err)
@@ -563,20 +1018,20 @@ func TestDashboardRollupReattributesOnLinkTaskToIssue(t *testing.T) {
}
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_dashboard_daily_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
`); err != nil {
t.Fatalf("rollup post-link: %v", err)
}
var projectAfter, nullAfter int64
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3
`, testWorkspaceID, projectID, agentID).Scan(&projectAfter); err != nil {
t.Fatalf("read project bucket post-link: %v", err)
}
if err := testPool.QueryRow(ctx, `
- SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_dashboard_daily
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
WHERE workspace_id = $1 AND project_id IS NULL AND agent_id = $2
`, testWorkspaceID, agentID).Scan(&nullAfter); err != nil {
t.Fatalf("read NULL bucket post-link: %v", err)
@@ -588,3 +1043,355 @@ func TestDashboardRollupReattributesOnLinkTaskToIssue(t *testing.T) {
t.Errorf("NULL bucket: expected 0 tokens after link, got %d", nullAfter)
}
}
+
+// TestPruneTaskUsageHourlyDirty covers the dirty-queue TTL. Both the RFC
+// (§7.1) and the rollup-pipeline migration call this THE most-easily-missed correctness
+// requirement of the hourly pipeline: without the prune, a row that escapes
+// the per-tick drain (crash mid-tick, worker paused during an incident)
+// pins its bucket's recompute forever and the queue grows unbounded.
+func TestPruneTaskUsageHourlyDirty(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ // task_usage_hourly_dirty carries no FKs (it is a queue), so synthetic
+ // UUIDs are fine. `provider` tags the rows for isolated cleanup.
+ const tag = "ttl-prune-test"
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE provider = $1`, tag)
+ })
+ seed := func(model, age string) {
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id, project_id,
+ provider, model, enqueued_at
+ )
+ VALUES (
+ date_trunc('hour', now()), gen_random_uuid(), gen_random_uuid(),
+ gen_random_uuid(), NULL, $1, $2, now() - $3::interval
+ )
+ `, tag, model, age); err != nil {
+ t.Fatalf("seed dirty row %s: %v", model, err)
+ }
+ }
+ countModel := func(model string) int {
+ var n int
+ testPool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE provider = $1 AND model = $2`,
+ tag, model,
+ ).Scan(&n)
+ return n
+ }
+
+ seed("stale-row", "8 days")
+ seed("fresh-row", "1 day")
+
+ // Default 7-day retention: the 8-day row goes, the 1-day row stays.
+ var pruned int64
+ if err := testPool.QueryRow(ctx, `SELECT prune_task_usage_hourly_dirty()`).Scan(&pruned); err != nil {
+ t.Fatalf("prune (default retention): %v", err)
+ }
+ if pruned < 1 {
+ t.Errorf("expected prune to report at least the one stale row deleted, got %d", pruned)
+ }
+ if got := countModel("stale-row"); got != 0 {
+ t.Errorf("default prune: expected stale row deleted, still %d present", got)
+ }
+ if got := countModel("fresh-row"); got != 1 {
+ t.Errorf("default prune: expected fresh row kept, got %d", got)
+ }
+
+ // An explicit retention shorter than the surviving row's age drops it.
+ if _, err := testPool.Exec(ctx, `SELECT prune_task_usage_hourly_dirty(interval '12 hours')`); err != nil {
+ t.Fatalf("prune (12h retention): %v", err)
+ }
+ if got := countModel("fresh-row"); got != 0 {
+ t.Errorf("12h-retention prune: expected fresh row deleted, still %d present", got)
+ }
+
+ // The cron entry folds the prune in so operators do
+ // not need a second scheduled job. A single tick must drop a stale row.
+ seed("cron-fold-row", "9 days")
+ if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {
+ t.Fatalf("rollup_task_usage_hourly: %v", err)
+ }
+ if got := countModel("cron-fold-row"); got != 0 {
+ t.Errorf("cron entry did not fold in the prune: stale row still present (%d)", got)
+ }
+}
+
+// TestRollupTaskUsageHourlyCapsWindowAtOneDay covers the catch-up cap
+// in rollup_task_usage_hourly(): when the watermark has
+// fallen far behind (worker paused for an incident or a migration freeze),
+// a single tick must advance it by at most one day, so a multi-week backlog
+// drains in bounded steps instead of one giant statement holding advisory
+// lock 4246. The existing watermark test only parks the watermark one hour
+// back, so the cap itself is never exercised there.
+func TestRollupTaskUsageHourlyCapsWindowAtOneDay(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ // Other tests drive rollup_task_usage_hourly_window directly and never
+ // read the watermark; the idempotency test parks it itself. Restore to
+ // now() so nothing downstream observes a stale value.
+ t.Cleanup(func() {
+ testPool.Exec(ctx,
+ `UPDATE task_usage_hourly_rollup_state SET watermark_at = now(), last_error = NULL WHERE id = 1`)
+ })
+
+ park := func(behind string) {
+ if _, err := testPool.Exec(ctx, `
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = now() - $1::interval, last_error = NULL
+ WHERE id = 1
+ `, behind); err != nil {
+ t.Fatalf("park watermark: %v", err)
+ }
+ }
+ ageDays := func() float64 {
+ var sec float64
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXTRACT(EPOCH FROM (now() - watermark_at))
+ FROM task_usage_hourly_rollup_state WHERE id = 1
+ `).Scan(&sec); err != nil {
+ t.Fatalf("read watermark: %v", err)
+ }
+ return sec / 86400
+ }
+ tick := func(label string) {
+ if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {
+ t.Fatalf("%s: %v", label, err)
+ }
+ }
+
+ // Park 3 days back. One tick advances by exactly one day (v_from + 1d,
+ // well short of now()-5min), leaving the watermark ~2 days behind.
+ park("3 days")
+ tick("tick 1")
+ if age := ageDays(); age < 1.9 || age > 2.1 {
+ t.Fatalf("after one tick: expected watermark ~2 days behind, got %.3f days", age)
+ }
+
+ // A second tick advances another bounded day → ~1 day behind.
+ tick("tick 2")
+ if age := ageDays(); age < 0.9 || age > 1.1 {
+ t.Fatalf("after two ticks: expected watermark ~1 day behind, got %.3f days", age)
+ }
+
+ // Once within a day of now, the tick snaps the watermark to now()-5min
+ // (LEAST picks the now bound) rather than taking a further fixed day.
+ tick("tick 3")
+ if age := ageDays(); age > 0.02 {
+ t.Fatalf("after catch-up: expected watermark within minutes of now, got %.3f days", age)
+ }
+}
+
+// TestDashboardUsageDailyCrossMidnightFullPipeline runs the WHOLE timezone
+// pipeline end to end: insert a raw `task_usage` row near UTC midnight →
+// run `rollup_task_usage_hourly_window` to bucket it → call
+// GetDashboardUsageDaily with a non-UTC viewer tz. It asserts the tokens
+// land on the viewer's correct calendar day and NOT on the UTC day.
+//
+// This is the #2822 bug class the RFC exists to prevent. The existing
+// TestDashboardUsageDailyBucketsByViewerTimezone seeds a pre-built
+// task_usage_hourly row and only exercises the SQL read path; here the
+// row travels from raw task_usage through the rollup, so a regression in
+// task_usage_hour_bucket or the recompute join is also caught.
+func TestDashboardUsageDailyCrossMidnightFullPipeline(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ 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, number)
+ VALUES ($1, 'cross-midnight pipeline test', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ 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', now()) RETURNING id
+ `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ // Raw task_usage at 00:30 UTC two days ago — genuinely near UTC
+ // midnight. 00:30 UTC is still the PRIOR evening (~16:30/17:30) in
+ // America/Los_Angeles (UTC-7/-8), so the UTC viewer and the LA viewer
+ // must see this row under different calendar days. Using CURRENT_DATE
+ // keeps the row inside the days=10 window without a fixed-date drift.
+ var usageAt time.Time
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES (
+ $1, 'claude', 'cross-midnight-model', 8888, 0,
+ ((CURRENT_DATE - 2)::timestamp + interval '30 minutes') AT TIME ZONE 'UTC'
+ )
+ RETURNING created_at
+ `, taskID).Scan(&usageAt); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'cross-midnight-model'`)
+ })
+
+ // Run the rollup so the raw row is aggregated into task_usage_hourly.
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("rollup window: %v", err)
+ }
+
+ utcDate := usageAt.UTC().Format("2006-01-02")
+ laLoc, err := time.LoadLocation("America/Los_Angeles")
+ if err != nil {
+ t.Fatalf("load LA location: %v", err)
+ }
+ laDate := usageAt.In(laLoc).Format("2006-01-02")
+ if utcDate == laDate {
+ t.Fatalf("test setup: UTC and LA dates must differ, both %s", utcDate)
+ }
+
+ readDate := func(tz string) string {
+ w := httptest.NewRecorder()
+ testHandler.GetDashboardUsageDaily(w, newRequest("GET", "/api/dashboard/usage/daily?days=10&tz="+tz, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("tz=%s: expected 200, got %d: %s", tz, w.Code, w.Body.String())
+ }
+ var rows []struct {
+ Date string `json:"date"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ }
+ _ = json.NewDecoder(w.Body).Decode(&rows)
+ for _, r := range rows {
+ if r.Model == "cross-midnight-model" {
+ if r.InputTokens != 8888 {
+ t.Errorf("tz=%s: expected 8888 tokens, got %d", tz, r.InputTokens)
+ }
+ return r.Date
+ }
+ }
+ t.Fatalf("tz=%s: cross-midnight-model row not found in %v", tz, rows)
+ return ""
+ }
+
+ if got := readDate("UTC"); got != utcDate {
+ t.Errorf("UTC viewer: expected date %s, got %s", utcDate, got)
+ }
+ if got := readDate("America/Los_Angeles"); got != laDate {
+ t.Errorf("LA viewer: expected date %s, got %s; row must NOT land on the UTC day %s",
+ laDate, got, utcDate)
+ }
+}
+
+// TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete covers the
+// `trg_tu_dirty_hourly` trigger — a BEFORE DELETE trigger on task_usage.
+// Migration 102 notes it has no production callers today and exists purely
+// as defensive convergence guard, so a single minimal test is enough:
+// seed a task_usage row, roll it up, DELETE the task_usage row directly,
+// roll up again, and assert the hourly bucket is recomputed down to zero.
+// Without the trigger the deleted row's bucket would never be re-enqueued.
+func TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID, agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("fetch runtime: %v", err)
+ }
+ 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, number)
+ VALUES ($1, 'tu-delete trigger test', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ 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', now() - interval '30 minutes') RETURNING id
+ `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("insert task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ var usageID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES ($1, 'claude', 'tu-delete-model', 5050, 0, now() - interval '30 minutes')
+ RETURNING id
+ `, taskID).Scan(&usageID); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'tu-delete-model'`)
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'tu-delete-model'`)
+ })
+
+ bucketTotal := func() int64 {
+ var total int64
+ testPool.QueryRow(ctx, `
+ SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourly
+ WHERE runtime_id = $1 AND model = 'tu-delete-model'
+ `, runtimeID).Scan(&total)
+ return total
+ }
+ runWindow := func(label string) {
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("%s: %v", label, err)
+ }
+ }
+
+ runWindow("initial rollup")
+ if got := bucketTotal(); got != 5050 {
+ t.Fatalf("initial: expected bucket = 5050, got %d", got)
+ }
+
+ // Delete the task_usage row directly — fires trg_tu_dirty_hourly,
+ // which enqueues the bucket on task_usage_hourly_dirty.
+ if _, err := testPool.Exec(ctx, `DELETE FROM task_usage WHERE id = $1`, usageID); err != nil {
+ t.Fatalf("delete task_usage: %v", err)
+ }
+ var dirtyCount int
+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE model = 'tu-delete-model'`).Scan(&dirtyCount)
+ if dirtyCount != 1 {
+ t.Fatalf("expected 1 dirty entry from task_usage DELETE trigger, got %d", dirtyCount)
+ }
+
+ runWindow("rollup after delete")
+ if got := bucketTotal(); got != 0 {
+ t.Errorf("after delete: expected bucket recomputed to 0, got %d", got)
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 05bbc02649..e43f51fdb4 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -50,27 +50,6 @@ type Config struct {
AllowSignup bool
AllowedEmails []string
AllowedEmailDomains []string
- // UseDailyRollupForRuntimeUsage routes ListRuntimeUsage to the
- // task_usage_daily rollup table when true. Default false: the read
- // path stays on the raw task_usage stream so rollup-related issues
- // (pg_cron not running, backfill not yet performed, watermark stuck)
- // can never make the dashboard return empty/stale data. Operators
- // flip this on per environment AFTER:
- // 1) migrations 072..076 applied,
- // 2) backfill_task_usage_daily ran successfully,
- // 3) cron job scheduled and task_usage_rollup_lag_seconds() < 900.
- UseDailyRollupForRuntimeUsage bool
- // UseDailyRollupForDashboard routes the workspace `/dashboard` page's
- // token-aggregation reads to `task_usage_dashboard_daily` (migration
- // 084). Mirrors UseDailyRollupForRuntimeUsage above with the same
- // fail-safe default (false → raw scan). Operators flip per
- // environment AFTER:
- // 1) migration 084 applied,
- // 2) `backfill_task_usage_dashboard_daily` succeeded and stamped
- // the dashboard rollup watermark,
- // 3) cron job scheduled (`rollup_task_usage_dashboard_daily`) and
- // `task_usage_dashboard_rollup_lag_seconds()` < 900.
- UseDailyRollupForDashboard bool
// PublicURL is the absolute base URL the API is reachable at from the
// public internet, with no trailing slash (e.g. "https://app.multica.ai").
// Used only to build webhook_url responses for autopilot webhook triggers
diff --git a/server/internal/handler/parse_since_param_test.go b/server/internal/handler/parse_since_param_test.go
index 0015de38fa..ee0af9639c 100644
--- a/server/internal/handler/parse_since_param_test.go
+++ b/server/internal/handler/parse_since_param_test.go
@@ -6,42 +6,162 @@ import (
"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)
+// TestSinceFromDays pins the DST-boundary behaviour of the pure core that
+// parseSinceParamInTZ delegates to. time.Now() is injected as `now`, so the
+// maths can be exercised at exact transition dates without waiting for a
+// real DST change. The invariant: the returned instant is genuine local
+// midnight (00:00:00) of the calendar day `days` days before `now`'s local
+// day — even when the subtracted span crosses a spring-forward (a 23h day)
+// or fall-back (a 25h day).
+func TestSinceFromDays(t *testing.T) {
+ mustLoad := func(name string) *time.Location {
+ loc, err := time.LoadLocation(name)
+ if err != nil {
+ t.Fatalf("load %s: %v", name, err)
+ }
+ return loc
+ }
+ ny := mustLoad("America/New_York")
+ la := mustLoad("America/Los_Angeles")
cases := []struct {
- name string
- path string
- want time.Time
+ name string
+ loc *time.Location
+ now time.Time
+ days int
+ wantYMD [3]int // year, month, day of expected local midnight
}{
- {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)},
+ {
+ // NY spring-forward is 2025-03-09 (clocks jump 02:00→03:00).
+ // From 03-12, days=3 lands on 03-09 local midnight, and the
+ // 3-day span swallows the 23-hour DST day.
+ name: "NY spring-forward span",
+ loc: ny,
+ now: time.Date(2025, 3, 12, 15, 30, 0, 0, ny),
+ days: 3,
+ wantYMD: [3]int{2025, 3, 9},
+ },
+ {
+ // Land exactly ON the spring-forward day.
+ name: "NY spring-forward day itself",
+ loc: ny,
+ now: time.Date(2025, 3, 9, 10, 0, 0, 0, ny),
+ days: 0,
+ wantYMD: [3]int{2025, 3, 9},
+ },
+ {
+ // NY fall-back is 2025-11-02 (clocks fall 02:00→01:00, 25h day).
+ name: "NY fall-back span",
+ loc: ny,
+ now: time.Date(2025, 11, 5, 8, 0, 0, 0, ny),
+ days: 4,
+ wantYMD: [3]int{2025, 11, 1},
+ },
+ {
+ name: "NY fall-back day itself",
+ loc: ny,
+ now: time.Date(2025, 11, 2, 23, 59, 0, 0, ny),
+ days: 0,
+ wantYMD: [3]int{2025, 11, 2},
+ },
+ {
+ // LA spring-forward also 2025-03-09.
+ name: "LA spring-forward span",
+ loc: la,
+ now: time.Date(2025, 3, 10, 6, 15, 0, 0, la),
+ days: 2,
+ wantYMD: [3]int{2025, 3, 8},
+ },
+ {
+ // LA fall-back also 2025-11-02.
+ name: "LA fall-back span",
+ loc: la,
+ now: time.Date(2025, 11, 3, 0, 30, 0, 0, la),
+ days: 5,
+ wantYMD: [3]int{2025, 10, 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)
+ got := sinceFromDays(tc.now, tc.days, tc.loc)
+
+ // Result must be genuine local midnight in tc.loc.
+ y, m, d := got.In(tc.loc).Date()
+ hh, mm, ss := got.In(tc.loc).Clock()
+ if hh != 0 || mm != 0 || ss != 0 {
+ t.Errorf("not local midnight: got %s in %s", got.In(tc.loc).Format(time.RFC3339), tc.loc)
+ }
+ if y != tc.wantYMD[0] || int(m) != tc.wantYMD[1] || d != tc.wantYMD[2] {
+ t.Errorf("calendar day: got %04d-%02d-%02d, want %04d-%02d-%02d",
+ y, m, d, tc.wantYMD[0], tc.wantYMD[1], tc.wantYMD[2])
+ }
+
+ // Cross-check: it equals time.Date midnight of the target day.
+ want := time.Date(tc.wantYMD[0], time.Month(tc.wantYMD[1]), tc.wantYMD[2], 0, 0, 0, 0, tc.loc)
+ if !got.Equal(want) {
+ t.Errorf("instant mismatch: got %s, want %s",
+ got.Format(time.RFC3339), want.Format(time.RFC3339))
+ }
+ })
+ }
+}
+
+// TestParseSinceParamInTZ guards the HTTP-layer parsing in
+// parseSinceParamInTZ — the `strconv.Atoi` + `parsed > 0 && parsed <= 365`
+// validation and the no-param default. TestSinceFromDays covers the pure
+// date maths; this covers how the `days` query param is read and clamped.
+// The expected cutoff is recomputed via sinceFromDays, so each case asserts
+// the param resolved to the day count the handler should have used.
+func TestParseSinceParamInTZ(t *testing.T) {
+ utc := time.UTC
+
+ // expectDays builds the cutoff parseSinceParamInTZ must return for a
+ // given effective day count, anchored to "now" at call time. The window
+ // is computed against time.Now() inside parseSinceParamInTZ, so a tiny
+ // skew across a day boundary is possible; cases run well clear of it.
+ expectDays := func(days int) time.Time {
+ return sinceFromDays(time.Now(), days, utc)
+ }
+
+ cases := []struct {
+ name string
+ query string // raw query string, no leading '?'
+ defaultDays int
+ wantDays int // effective day count the cutoff must reflect
+ }{
+ // Invalid / out-of-range inputs all fall back to defaultDays.
+ {"days=0 rejected (not > 0)", "days=0", 30, 30},
+ {"days=abc rejected (not an int)", "days=abc", 30, 30},
+ {"days=400 rejected (over 365 cap)", "days=400", 30, 30},
+ {"days=-5 rejected (negative)", "days=-5", 30, 30},
+ {"no days param uses default", "", 30, 30},
+ {"empty days param uses default", "days=", 30, 30},
+ // Valid inputs are honoured, including the 365 boundary.
+ {"valid days=7 honoured", "days=7", 30, 7},
+ {"days=365 honoured (at cap)", "days=365", 30, 365},
+ {"days=1 honoured (lower bound)", "days=1", 90, 1},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ url := "/api/dashboard/usage/daily"
+ if tc.query != "" {
+ url += "?" + tc.query
+ }
+ req := httptest.NewRequest("GET", url, nil)
+
+ got := parseSinceParamInTZ(req, tc.defaultDays, "UTC")
if !got.Valid {
- t.Fatalf("expected Valid timestamptz, got invalid")
+ t.Fatalf("expected a valid timestamptz, got Valid=false")
}
- 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))
+ want := expectDays(tc.wantDays)
+ // Allow a 2s slop for the now() skew between the two calls.
+ if diff := got.Time.Sub(want); diff < -2*time.Second || diff > 2*time.Second {
+ t.Errorf("cutoff mismatch: got %s, want ~%s (effective days=%d)",
+ got.Time.Format(time.RFC3339), want.Format(time.RFC3339), tc.wantDays)
}
})
}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index e485aaae35..27d78293ae 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -6,10 +6,12 @@ import (
"log/slog"
"net/http"
"strconv"
+ "strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -31,7 +33,6 @@ type AgentRuntimeResponse struct {
// can bind agents) or "public" (any workspace member can). See migration
// 083 and canUseRuntimeForAgent.
Visibility string `json:"visibility"`
- Timezone string `json:"timezone"`
LastSeenAt *string `json:"last_seen_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
@@ -59,7 +60,6 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {
Metadata: metadata,
OwnerID: uuidToPtr(rt.OwnerID),
Visibility: rt.Visibility,
- Timezone: rt.Timezone,
LastSeenAt: timestampToPtr(rt.LastSeenAt),
CreatedAt: timestampToString(rt.CreatedAt),
UpdatedAt: timestampToString(rt.UpdatedAt),
@@ -102,9 +102,11 @@ func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {
return
}
- since := parseSinceParamInTZ(r, 90, rt.Timezone)
+ // All runtime reports render in the viewer's tz.
+ viewTZ := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 90, viewTZ)
- resp, err := h.listRuntimeUsage(r.Context(), rt.ID, rt.Timezone, since)
+ resp, err := h.listRuntimeUsage(r.Context(), rt.ID, viewTZ, since)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list usage")
return
@@ -113,37 +115,10 @@ func (h *Handler) GetRuntimeUsage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
-// listRuntimeUsage dispatches between the raw task_usage scan and the
-// 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.
+// listRuntimeUsage reads the daily-bucketed trend from task_usage_hourly,
+// applying the viewer's tz to project bucket_hour into local days.
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
- }
- resp := make([]RuntimeUsageResponse, len(rows))
- for i, row := range rows {
- resp[i] = RuntimeUsageResponse{
- RuntimeID: resolvedRuntimeID,
- Date: row.Date.Time.Format("2006-01-02"),
- Provider: row.Provider,
- Model: row.Model,
- InputTokens: row.InputTokens,
- OutputTokens: row.OutputTokens,
- CacheReadTokens: row.CacheReadTokens,
- CacheWriteTokens: row.CacheWriteTokens,
- }
- }
- return resp, nil
- }
-
rows, err := h.Queries.ListRuntimeUsage(ctx, db.ListRuntimeUsageParams{
RuntimeID: runtimeID,
Since: since,
@@ -186,9 +161,10 @@ func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request)
return
}
+ viewTZ := h.resolveViewingTZ(r)
rows, err := h.Queries.GetRuntimeTaskHourlyActivity(r.Context(), db.GetRuntimeTaskHourlyActivityParams{
RuntimeID: rt.ID,
- Tz: rt.Timezone,
+ Tz: viewTZ,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to get task activity")
@@ -226,8 +202,12 @@ type RuntimeUsageByAgentResponse struct {
// since the cutoff window. Drives the runtime-detail "Cost by agent" tab.
func (h *Handler) GetRuntimeUsageByAgent(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(), parseUUID(runtimeID))
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
if err != nil {
writeError(w, http.StatusNotFound, "runtime not found")
return
@@ -237,10 +217,13 @@ func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request)
return
}
- since := parseSinceParamInTZ(r, 30, rt.Timezone)
+ // No date bucketing — tz only sets the cutoff boundary so "last 30
+ // days" means 30 of the viewer's days.
+ viewTZ := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, viewTZ)
rows, err := h.Queries.ListRuntimeUsageByAgent(r.Context(), db.ListRuntimeUsageByAgentParams{
- RuntimeID: parseUUID(runtimeID),
+ RuntimeID: rt.ID,
Since: since,
})
if err != nil {
@@ -279,10 +262,18 @@ type RuntimeUsageByHourResponse struct {
// GetRuntimeUsageByHour returns hourly (0..23) token aggregates for a
// runtime since the cutoff window. Drives the "By hour" tab.
+//
+// The hour-of-day axis is bucketed in the viewer's tz like every other
+// report — the same timezone resolved by resolveViewingTZ from the request's
+// `?tz=` param or the authenticated user's stored user.timezone.
func (h *Handler) GetRuntimeUsageByHour(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(), parseUUID(runtimeID))
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), runtimeUUID)
if err != nil {
writeError(w, http.StatusNotFound, "runtime not found")
return
@@ -292,12 +283,13 @@ func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request)
return
}
- since := parseSinceParamInTZ(r, 30, rt.Timezone)
+ viewTZ := h.resolveViewingTZ(r)
+ since := parseSinceParamInTZ(r, 30, viewTZ)
rows, err := h.Queries.GetRuntimeUsageByHour(r.Context(), db.GetRuntimeUsageByHourParams{
- RuntimeID: parseUUID(runtimeID),
+ RuntimeID: rt.ID,
Since: since,
- Tz: rt.Timezone,
+ Tz: viewTZ,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to get usage by hour")
@@ -320,109 +312,30 @@ func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, resp)
}
-// GetWorkspaceUsageByDay returns daily token usage aggregated by model for the workspace.
-func (h *Handler) GetWorkspaceUsageByDay(w http.ResponseWriter, r *http.Request) {
- workspaceID := h.resolveWorkspaceID(r)
- since := parseSinceParam(r, 30)
-
- rows, err := h.Queries.GetWorkspaceUsageByDay(r.Context(), db.GetWorkspaceUsageByDayParams{
- WorkspaceID: parseUUID(workspaceID),
- Since: since,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to get usage")
- return
- }
-
- type DailyUsageRow struct {
- Date string `json:"date"`
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- TotalOutputTokens int64 `json:"total_output_tokens"`
- TotalCacheReadTokens int64 `json:"total_cache_read_tokens"`
- TotalCacheWriteTokens int64 `json:"total_cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
- }
-
- resp := make([]DailyUsageRow, len(rows))
- for i, row := range rows {
- resp[i] = DailyUsageRow{
- Date: row.Date.Time.Format("2006-01-02"),
- Model: row.Model,
- TotalInputTokens: row.TotalInputTokens,
- TotalOutputTokens: row.TotalOutputTokens,
- TotalCacheReadTokens: row.TotalCacheReadTokens,
- TotalCacheWriteTokens: row.TotalCacheWriteTokens,
- TaskCount: row.TaskCount,
- }
- }
-
- writeJSON(w, http.StatusOK, resp)
-}
-
-// GetWorkspaceUsageSummary returns total token usage aggregated by model for the workspace.
-func (h *Handler) GetWorkspaceUsageSummary(w http.ResponseWriter, r *http.Request) {
- workspaceID := h.resolveWorkspaceID(r)
- since := parseSinceParam(r, 30)
-
- rows, err := h.Queries.GetWorkspaceUsageSummary(r.Context(), db.GetWorkspaceUsageSummaryParams{
- WorkspaceID: parseUUID(workspaceID),
- Since: since,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to get usage summary")
- return
- }
-
- type UsageSummaryRow struct {
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- TotalOutputTokens int64 `json:"total_output_tokens"`
- TotalCacheReadTokens int64 `json:"total_cache_read_tokens"`
- TotalCacheWriteTokens int64 `json:"total_cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
- }
-
- resp := make([]UsageSummaryRow, len(rows))
- for i, row := range rows {
- resp[i] = UsageSummaryRow{
- Model: row.Model,
- TotalInputTokens: row.TotalInputTokens,
- TotalOutputTokens: row.TotalOutputTokens,
- TotalCacheReadTokens: row.TotalCacheReadTokens,
- TotalCacheWriteTokens: row.TotalCacheWriteTokens,
- TaskCount: row.TaskCount,
- }
- }
-
- writeJSON(w, http.StatusOK, resp)
-}
-
-// 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.
+// sinceFromDays is the pure, now-injectable core of parseSinceParamInTZ.
+// Given the current instant, a day count and an IANA location, it returns
+// the instant of local midnight `days` days before `now`'s local calendar
+// day. `now` is a parameter so the DST boundary maths can be tested at
+// pinned dates (see TestSinceFromDays).
//
-// 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 := defaultDays
- if d := r.URL.Query().Get("days"); d != "" {
- if parsed, err := strconv.Atoi(d); err == nil && parsed > 0 && parsed <= 365 {
- days = parsed
- }
- }
- 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}
+// The cutoff yields N+1 calendar buckets (today-days … today inclusive).
+// The extra day versus a naive "-(days-1)" is deliberate headroom, not an
+// off-by-one:
+// - Runtime detail's sliceWindow filters `date >= today-days` (closed) and
+// its prior-window delta reaches back to today-2*days, so the today-days
+// bucket MUST exist or the oldest bar / KPI delta silently loses data.
+// - The workspace dashboard re-filters client-side with -(days-1); the one
+// extra day the backend returns is trimmed there — harmless.
+//
+// Do not "tighten" this to -(days-1): it would break the runtime detail page.
+func sinceFromDays(now time.Time, days int, loc *time.Location) time.Time {
+ local := now.In(loc)
+ startOfToday := time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc)
+ return startOfToday.AddDate(0, 0, -days)
}
-// parseSinceParamInTZ is the timezone-aware variant of parseSinceParam.
-// Anchors the cutoff to start-of-day-(N) in the supplied IANA zone so that
+// parseSinceParamInTZ parses the "days" query parameter into a cutoff
+// timestamptz. 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.
@@ -437,30 +350,61 @@ func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype
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}
+ return pgtype.Timestamptz{Time: sinceFromDays(time.Now(), days, loc), Valid: true}
+}
+
+// resolveViewingTZ resolves the IANA tz to render the response in:
+// `?tz=` query param, else the authenticated user's stored
+// user.timezone, else "UTC". Invalid values fall through rather than
+// erroring — tz is a display concern.
+//
+// The browser app always sends `?tz=` (resolved client-side by
+// useViewingTimezone), so the `GetUser` lookup below is a COLD fallback
+// hit only by API clients / older builds that omit the param — it is not
+// a hot path. Do not replicate this DB-read pattern into a handler that
+// runs without a `?tz=`-supplying client in front of it.
+func (h *Handler) resolveViewingTZ(r *http.Request) string {
+ if tz := strings.TrimSpace(r.URL.Query().Get("tz")); tz != "" {
+ if loc, err := time.LoadLocation(tz); err == nil && loc != nil {
+ return tz
+ }
+ }
+ if userID := requestUserID(r); userID != "" {
+ uid, err := util.ParseUUID(userID)
+ if err != nil {
+ slog.Warn("resolveViewingTZ: malformed X-User-ID, falling back to UTC",
+ "path", r.URL.Path, "user_id", userID)
+ }
+ if err == nil {
+ slog.Debug("resolveViewingTZ cold path: ?tz= missing, reading user.timezone",
+ "path", r.URL.Path, "user_id", userID)
+ if user, err := h.Queries.GetUser(r.Context(), uid); err == nil && user.Timezone.Valid {
+ stored := strings.TrimSpace(user.Timezone.String)
+ if stored != "" {
+ if loc, err := time.LoadLocation(stored); err == nil && loc != nil {
+ return stored
+ }
+ }
+ }
+ }
+ }
+ return "UTC"
}
// 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"`
// Visibility flips a runtime between "private" (default — only the owner
// or workspace admins can bind agents) and "public" (any workspace
// member can). Owner / workspace admin only, gated by canEditRuntime.
Visibility *string `json:"visibility,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.
+// UpdateAgentRuntime handles PATCH /api/runtimes/:id. Currently visibility
+// is editable; the request shape is open-ended so future fields (display
+// name, description) can be added without a route change.
+// Workspace-membership-checked; write access is gated by canEditRuntime.
func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")
@@ -489,35 +433,10 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
return
}
- // Validate every field that's present BEFORE running any mutation. A
- // PATCH that carries both `timezone` and `visibility` must succeed or
- // fail atomically from the caller's perspective: writing timezone first
- // and then 400-ing on a bad visibility would leave the row half-updated
- // (and the usage rollup rebuilt under a tz the caller never asked for).
- //
- // This loop also fixes the no-op short-circuit: the prior version
- // returned early when `timezone == rt.Timezone`, silently dropping a
- // concurrent visibility patch in the same request body.
var (
- newTimezone string
- needTimezone bool
newVisibility string
needVisibility bool
)
- 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 {
- newTimezone = tz
- needTimezone = true
- }
- }
if req.Visibility != nil {
v := *req.Visibility
if v != "private" && v != "public" {
@@ -530,52 +449,6 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
}
- if needTimezone {
- 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: newTimezone,
- })
- 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
- }
-
if needVisibility {
updated, err := h.Queries.UpdateAgentRuntimeVisibility(r.Context(), db.UpdateAgentRuntimeVisibilityParams{
ID: runtimeUUID,
diff --git a/server/internal/handler/runtime_rollup_test.go b/server/internal/handler/runtime_rollup_test.go
deleted file mode 100644
index 040324c472..0000000000
--- a/server/internal/handler/runtime_rollup_test.go
+++ /dev/null
@@ -1,605 +0,0 @@
-package handler
-
-import (
- "context"
- "testing"
- "time"
-)
-
-// TestRollupTaskUsageDaily_AggregatesAndIsIdempotent exercises the
-// rollup_task_usage_daily_window() SQL function directly. This is the
-// shared aggregation primitive used by both the cron-driven watermark
-// loop and the offline backfill command, so its correctness underpins
-// the entire ListRuntimeUsage read path. Two properties matter:
-//
-// 1. It correctly groups raw `task_usage` rows by (date, runtime,
-// workspace, provider, model) and sums the four token columns.
-// 2. Re-aggregating an already-rolled-up window is *idempotent*: the
-// function recomputes each dirty bucket from ground truth and
-// REPLACES the daily row, so overlap with backfill / replay is
-// safe and corrections via UpsertTaskUsage propagate cleanly.
-func TestRollupTaskUsageDaily_AggregatesAndIsIdempotent(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- runtimeID := handlerTestRuntimeID(t)
- 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, 'rollup test', $2, 'member')
- RETURNING id
- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
- t.Fatalf("create issue: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
- })
-
- // Pin the test to a fixed historical day so we don't collide with
- // concurrent rollups of "today" running against the same fixture
- // runtime. 2020-06-15 is far outside any backfill window the rest
- // of the suite touches.
- day := time.Date(2020, 6, 15, 0, 0, 0, 0, time.UTC)
-
- // Two rows on the same (date, provider, model) — must collapse to
- // a single output row whose totals sum the inputs.
- insertUsage := func(usageAt time.Time, model string, in, out int64) {
- 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', $2, $3, $4, $5, $5)
- `, taskID, model, in, out, usageAt); err != nil {
- t.Fatalf("insert task_usage: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
- })
- }
-
- insertUsage(day.Add(1*time.Hour), "claude-3-5-sonnet", 100, 10)
- insertUsage(day.Add(2*time.Hour), "claude-3-5-sonnet", 200, 20)
- // A second model on the same day must produce a *separate* output
- // row (different group key).
- insertUsage(day.Add(3*time.Hour), "claude-3-5-haiku", 50, 5)
-
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date`, runtimeID, day)
- })
-
- // --- 1) Initial aggregation produces the expected totals.
- if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_daily_window($1::timestamptz, $2::timestamptz)
- `, day, day.Add(24*time.Hour)); err != nil {
- t.Fatalf("rollup_task_usage_daily_window: %v", err)
- }
-
- type row struct {
- Model string
- InputTokens int64
- Output int64
- EventCount int64
- }
- read := func() map[string]row {
- rs, err := testPool.Query(ctx, `
- SELECT model, input_tokens, output_tokens, event_count
- FROM task_usage_daily
- WHERE runtime_id = $1 AND bucket_date = $2::date
- `, runtimeID, day)
- if err != nil {
- t.Fatalf("read task_usage_daily: %v", err)
- }
- defer rs.Close()
- out := map[string]row{}
- for rs.Next() {
- var r row
- if err := rs.Scan(&r.Model, &r.InputTokens, &r.Output, &r.EventCount); err != nil {
- t.Fatalf("scan: %v", err)
- }
- out[r.Model] = r
- }
- return out
- }
-
- got := read()
- if len(got) != 2 {
- t.Fatalf("expected 2 rows (one per model), got %d: %+v", len(got), got)
- }
- if got["claude-3-5-sonnet"].InputTokens != 300 || got["claude-3-5-sonnet"].Output != 30 || got["claude-3-5-sonnet"].EventCount != 2 {
- t.Errorf("sonnet bucket wrong: %+v", got["claude-3-5-sonnet"])
- }
- if got["claude-3-5-haiku"].InputTokens != 50 || got["claude-3-5-haiku"].Output != 5 || got["claude-3-5-haiku"].EventCount != 1 {
- t.Errorf("haiku bucket wrong: %+v", got["claude-3-5-haiku"])
- }
-
- // --- 2) Re-aggregating the same window is idempotent.
- // The new function recomputes each dirty bucket from ground truth and
- // REPLACES the daily row, so callers can safely overlap windows
- // (cron + backfill, replay, manual ops). Verifying it explicitly so
- // the property doesn't silently regress.
- if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_daily_window($1::timestamptz, $2::timestamptz)
- `, day, day.Add(24*time.Hour)); err != nil {
- t.Fatalf("rollup_task_usage_daily_window (second call): %v", err)
- }
- got = read()
- if got["claude-3-5-sonnet"].InputTokens != 300 || got["claude-3-5-sonnet"].EventCount != 2 {
- t.Errorf("after second call, sonnet should be unchanged (idempotent), got: %+v", got["claude-3-5-sonnet"])
- }
- if got["claude-3-5-haiku"].InputTokens != 50 || got["claude-3-5-haiku"].EventCount != 1 {
- t.Errorf("after second call, haiku should be unchanged (idempotent), got: %+v", got["claude-3-5-haiku"])
- }
-
- // --- 3) Correction propagates: bumping a row's updated_at into a
- // new window must cause the bucket to be recomputed from ground
- // truth (covers the UpsertTaskUsage correction path that the old
- // additive design dropped silently).
- correctionMark := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
- if _, err := testPool.Exec(ctx, `
- UPDATE task_usage SET input_tokens = 1000, updated_at = $1
- WHERE task_id IN (
- SELECT id FROM agent_task_queue WHERE runtime_id = $2 AND created_at::date = $3::date
- )
- AND model = 'claude-3-5-sonnet'
- AND input_tokens = 100
- `, correctionMark, runtimeID, day); err != nil {
- t.Fatalf("simulate correction: %v", err)
- }
- if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_daily_window($1::timestamptz, $2::timestamptz)
- `, correctionMark.Add(-time.Minute), correctionMark.Add(time.Minute)); err != nil {
- t.Fatalf("rollup correction window: %v", err)
- }
- got = read()
- // New sonnet total: 1000 + 200 = 1200, still 2 events.
- if got["claude-3-5-sonnet"].InputTokens != 1200 || got["claude-3-5-sonnet"].EventCount != 2 {
- t.Errorf("after correction, sonnet should reflect new total 1200, got: %+v", got["claude-3-5-sonnet"])
- }
-}
-
-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.
-// We seed the watermark to a known value, force time to pass via a
-// fixture, and assert the watermark moves forward by exactly the
-// elapsed-window minus the 5 minute safety lag built into the function.
-func TestRollupTaskUsageDaily_WatermarkAdvances(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- // Seed the watermark to "long ago" so the next call has a non-empty
- // window. Use a test-scoped low value so we don't clobber any other
- // test's state — the singleton row gets restored at the end.
- var prevWatermark time.Time
- if err := testPool.QueryRow(ctx, `SELECT watermark_at FROM task_usage_rollup_state WHERE id = 1`).Scan(&prevWatermark); err != nil {
- t.Fatalf("read prev watermark: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `UPDATE task_usage_rollup_state SET watermark_at = $1 WHERE id = 1`, prevWatermark)
- })
-
- if _, err := testPool.Exec(ctx, `
- UPDATE task_usage_rollup_state
- SET watermark_at = '2020-01-01 00:00:00+00', last_error = NULL
- WHERE id = 1
- `); err != nil {
- t.Fatalf("seed watermark: %v", err)
- }
-
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily()`); err != nil {
- t.Fatalf("rollup_task_usage_daily: %v", err)
- }
-
- var newWatermark time.Time
- var lastError *string
- if err := testPool.QueryRow(ctx, `SELECT watermark_at, last_error FROM task_usage_rollup_state WHERE id = 1`).Scan(&newWatermark, &lastError); err != nil {
- t.Fatalf("read new watermark: %v", err)
- }
- if lastError != nil {
- t.Fatalf("rollup recorded error: %s", *lastError)
- }
-
- // New watermark must be near now() - 5 min. Allow a wide window
- // (±2 min) so this isn't flaky on slow CI.
- expected := time.Now().UTC().Add(-5 * time.Minute)
- delta := newWatermark.Sub(expected)
- if delta < -2*time.Minute || delta > 2*time.Minute {
- t.Errorf("watermark %s not within 2min of expected %s (delta %s)", newWatermark, expected, delta)
- }
-}
-
-// TestRollupTaskUsageDaily_InvalidationOnReassign verifies that the
-// trigger-driven dirty-bucket queue handles task reassignment between
-// runtimes (the ReassignTasksToRuntime path used during runtime merge).
-// Without invalidation the rollup would keep attributing usage to the
-// old runtime; the raw fallback would not — so the two read paths would
-// silently disagree.
-func TestRollupTaskUsageDaily_InvalidationOnReassign(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- oldRuntimeID := handlerTestRuntimeID(t)
- // Spin up a second runtime to receive the reassigned task.
- var newRuntimeID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO agent_runtime (
-workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
-)
-VALUES ($1, NULL, 'reassign-target', 'cloud', 'reassign-target', 'online', '{}'::jsonb, '{}'::jsonb, now())
-RETURNING id
-`, testWorkspaceID).Scan(&newRuntimeID); err != nil {
- t.Fatalf("create dest runtime: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, newRuntimeID)
- })
-
- 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, 'reassign test', $2, 'member')
-RETURNING id
-`, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
- t.Fatalf("create issue: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
- })
-
- day := time.Date(2021, 3, 14, 0, 0, 0, 0, time.UTC)
- 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, oldRuntimeID, day.Add(time.Hour)).Scan(&taskID); err != nil {
- t.Fatalf("insert task: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
- })
- if _, err := testPool.Exec(ctx, `
-INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at, updated_at)
-VALUES ($1, 'claude', 'm-reassign', 700, 70, $2, $2)
-`, taskID, day.Add(time.Hour)); err != nil {
- t.Fatalf("insert task_usage: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE bucket_date = $1::date AND model = 'm-reassign'`, day)
- testPool.Exec(ctx, `DELETE FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-reassign'`, day)
- })
-
- // Initial roll-up: usage should attach to OLD runtime.
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("initial rollup: %v", err)
- }
- var oldTokens, newTokens int64
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-reassign'`, oldRuntimeID, day).Scan(&oldTokens)
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-reassign'`, newRuntimeID, day).Scan(&newTokens)
- if oldTokens != 700 || newTokens != 0 {
- t.Fatalf("initial: expected old=700 new=0, got old=%d new=%d", oldTokens, newTokens)
- }
-
- // Trigger should enqueue both old + new buckets.
- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, newRuntimeID, taskID); err != nil {
- t.Fatalf("reassign task: %v", err)
- }
- var dirtyCount int
- testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-reassign'`, day).Scan(&dirtyCount)
- if dirtyCount != 2 {
- t.Fatalf("expected 2 dirty entries (old+new runtime), got %d", dirtyCount)
- }
-
- // Re-run rollup. Old bucket should be deleted (no source rows left),
- // new bucket should receive the moved usage.
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("rollup after reassign: %v", err)
- }
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-reassign'`, oldRuntimeID, day).Scan(&oldTokens)
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-reassign'`, newRuntimeID, day).Scan(&newTokens)
- if oldTokens != 0 || newTokens != 700 {
- t.Fatalf("after reassign: expected old=0 new=700, got old=%d new=%d", oldTokens, newTokens)
- }
- // Dirty queue should be drained.
- testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-reassign'`, day).Scan(&dirtyCount)
- if dirtyCount != 0 {
- t.Errorf("expected dirty queue drained, got %d entries", dirtyCount)
- }
-}
-
-// TestRollupTaskUsageDaily_InvalidationOnIssueDelete verifies that
-// cascade delete (issue → agent_task_queue → task_usage) clears the
-// matching daily rows via the trigger-driven dirty queue.
-func TestRollupTaskUsageDaily_InvalidationOnIssueDelete(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- runtimeID := handlerTestRuntimeID(t)
- 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, 'delete test', $2, 'member') RETURNING id
-`, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
- t.Fatalf("create issue: %v", err)
- }
-
- day := time.Date(2021, 7, 4, 0, 0, 0, 0, time.UTC)
- 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, day.Add(time.Hour)).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', 'm-delete', 500, 50, $2, $2)
-`, taskID, day.Add(time.Hour)); err != nil {
- t.Fatalf("insert task_usage: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE bucket_date = $1::date AND model = 'm-delete'`, day)
- testPool.Exec(ctx, `DELETE FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-delete'`, day)
- })
-
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("initial rollup: %v", err)
- }
- var tokens int64
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-delete'`, runtimeID, day).Scan(&tokens)
- if tokens != 500 {
- t.Fatalf("initial: expected 500, got %d", tokens)
- }
-
- // Cascade delete via issue. Trigger fires on agent_task_queue BEFORE
- // DELETE — that's when the task_usage children + issue parent are
- // still readable inside the same statement.
- if _, err := testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID); err != nil {
- t.Fatalf("delete issue: %v", err)
- }
- var dirtyCount int
- testPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-delete'`, day).Scan(&dirtyCount)
- if dirtyCount == 0 {
- t.Fatalf("expected dirty entry after cascade delete, got 0")
- }
-
- // Re-run rollup: bucket should be deleted because no source rows exist.
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("rollup after delete: %v", err)
- }
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-delete'`, runtimeID, day).Scan(&tokens)
- if tokens != 0 {
- t.Errorf("after issue delete: expected 0 (bucket cleared), got %d", tokens)
- }
-}
-
-// TestRollupTaskUsageDaily_WorkspaceMismatch constructs an atq row whose
-// agent.workspace_id != issue.workspace_id and verifies that the rollup
-// resolves workspace_id consistently from `agent` across triggers,
-// dirty_from_updates, and recompute. If any of those paths leaked back
-// to the issue.workspace_id the dirty queue would be misaligned with
-// the recompute join and the bucket would either be silently dropped
-// (recompute returns 0 rows → deleted_empty branch fires) or attributed
-// to the wrong workspace.
-//
-// The schema does not enforce agent.workspace_id == issue.workspace_id,
-// so this canary keeps the alignment honest as the schema evolves.
-func TestRollupTaskUsageDaily_WorkspaceMismatch(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- // Create a foreign workspace + a runtime + an agent there.
- var foreignWorkspaceID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO workspace (name, slug) VALUES ('ws-mismatch', 'ws-mismatch-' || gen_random_uuid()::text) RETURNING id
-`).Scan(&foreignWorkspaceID); err != nil {
- t.Fatalf("create foreign workspace: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
- })
- var foreignRuntimeID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO agent_runtime (
-workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
-)
-VALUES ($1, NULL, 'mismatch-rt', 'cloud', 'mismatch-rt', 'online', '{}'::jsonb, '{}'::jsonb, now())
-RETURNING id
-`, foreignWorkspaceID).Scan(&foreignRuntimeID); err != nil {
- t.Fatalf("create foreign runtime: %v", err)
- }
- var foreignAgentID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO agent (
-workspace_id, name, description, runtime_mode, runtime_config,
-runtime_id, visibility, max_concurrent_tasks, owner_id,
-instructions, custom_env, custom_args, mcp_config
-)
-VALUES ($1, 'mismatch-agent', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3, '', '{}'::jsonb, '[]'::jsonb, '[]'::jsonb)
-RETURNING id
-`, foreignWorkspaceID, foreignRuntimeID, testUserID).Scan(&foreignAgentID); err != nil {
- t.Fatalf("create foreign agent: %v", err)
- }
-
- // Issue lives in the *primary* test workspace, agent in foreign one.
- var issueID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO issue (workspace_id, title, creator_id, creator_type)
-VALUES ($1, 'mismatch test', $2, 'member') RETURNING id
-`, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
- t.Fatalf("create issue: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
- })
-
- day := time.Date(2021, 9, 9, 0, 0, 0, 0, time.UTC)
- 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
-`, foreignAgentID, issueID, foreignRuntimeID, day.Add(time.Hour)).Scan(&taskID); err != nil {
- t.Fatalf("insert atq: %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', 'm-mismatch', 333, 33, $2, $2)
-`, taskID, day.Add(time.Hour)); err != nil {
- t.Fatalf("insert task_usage: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM task_usage_daily WHERE bucket_date = $1::date AND model = 'm-mismatch'`, day)
- testPool.Exec(ctx, `DELETE FROM task_usage_daily_dirty WHERE bucket_date = $1::date AND model = 'm-mismatch'`, day)
- })
-
- // Rollup. The bucket must be attributed to FOREIGN workspace
- // (agent.workspace_id), not the primary one (issue.workspace_id).
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("rollup: %v", err)
- }
- var foreignTokens, primaryTokens int64
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE workspace_id = $1 AND bucket_date = $2::date AND model = 'm-mismatch'`, foreignWorkspaceID, day).Scan(&foreignTokens)
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE workspace_id = $1 AND bucket_date = $2::date AND model = 'm-mismatch'`, testWorkspaceID, day).Scan(&primaryTokens)
- if foreignTokens != 333 {
- t.Fatalf("expected foreign workspace bucket = 333, got %d", foreignTokens)
- }
- if primaryTokens != 0 {
- t.Errorf("expected primary workspace bucket = 0, got %d", primaryTokens)
- }
-
- // Now reassign atq.runtime_id within the foreign workspace and
- // verify the trigger / recompute pair still agree on workspace_id.
- var foreignRuntime2ID string
- if err := testPool.QueryRow(ctx, `
-INSERT INTO agent_runtime (
-workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
-)
-VALUES ($1, NULL, 'mismatch-rt2', 'cloud', 'mismatch-rt2', 'online', '{}'::jsonb, '{}'::jsonb, now())
-RETURNING id
-`, foreignWorkspaceID).Scan(&foreignRuntime2ID); err != nil {
- t.Fatalf("create foreign runtime 2: %v", err)
- }
- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, foreignRuntime2ID, taskID); err != nil {
- t.Fatalf("reassign: %v", err)
- }
- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)`); err != nil {
- t.Fatalf("rollup after reassign: %v", err)
- }
- var oldRTTokens, newRTTokens int64
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-mismatch'`, foreignRuntimeID, day).Scan(&oldRTTokens)
- testPool.QueryRow(ctx, `SELECT COALESCE(SUM(input_tokens),0) FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date = $2::date AND model = 'm-mismatch'`, foreignRuntime2ID, day).Scan(&newRTTokens)
- if oldRTTokens != 0 || newRTTokens != 333 {
- t.Fatalf("after reassign in mismatched ws: expected old=0 new=333, got old=%d new=%d", oldRTTokens, newRTTokens)
- }
-}
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index 787a30d2df..c33a35a0e7 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -9,7 +9,6 @@ import (
"time"
"github.com/jackc/pgx/v5/pgtype"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {
@@ -142,24 +141,23 @@ func TestGetRuntimeUsage_BucketsByUsageTime(t *testing.T) {
insertTaskWithUsage(yesterdayLate, todayEarly, 1000) // cross-midnight
insertTaskWithUsage(yesterdayMorning, yesterdayMorning, 2000) // full-day yesterday
- // ListRuntimeUsage now reads from the `task_usage_daily` rollup
- // table maintained by the cron-driven rollup_task_usage_daily()
- // function. In production the watermarked wrapper waits a 5 min
- // safety lag before consuming rows; here we drive the underlying
- // window function directly with a wide-open range so the freshly
- // inserted fixture rows are guaranteed to be aggregated before the
- // handler is called. Each test invocation gets its own isolated
- // daily buckets keyed by (date, runtime, provider, model), so
- // re-running the test is idempotent (the upsert just rewrites the
- // same totals).
+ // ListRuntimeUsage reads from task_usage_hourly,
+ // aggregated to per-(date, provider, model) at query time. The
+ // window function is idempotent, so re-running this test rewrites
+ // the same totals.
if _, err := testPool.Exec(ctx, `
- SELECT rollup_task_usage_daily_window('-infinity'::timestamptz, 'infinity'::timestamptz)
+ SELECT rollup_task_usage_hourly_window('-infinity'::timestamptz, 'infinity'::timestamptz)
`); err != nil {
- t.Fatalf("rollup_task_usage_daily_window: %v", err)
+ t.Fatalf("rollup window: %v", err)
}
t.Cleanup(func() {
+ // Hourly buckets touched by this test cover the two calendar
+ // days in fixture data (today and yesterday in UTC, which is
+ // what the test uses for `today` / `yesterday` mocks).
testPool.Exec(ctx, `
- DELETE FROM task_usage_daily WHERE runtime_id = $1 AND bucket_date IN ($2::date, $3::date)
+ DELETE FROM task_usage_hourly
+ WHERE runtime_id = $1
+ AND DATE(bucket_hour AT TIME ZONE 'UTC') IN ($2::date, $3::date)
`, runtimeID, today, today.Add(-24*time.Hour))
})
@@ -198,7 +196,11 @@ func TestGetRuntimeUsage_BucketsByUsageTime(t *testing.T) {
}
}
-func TestGetRuntimeUsageDailyRollupCutoffUsesRuntimeTimezone(t *testing.T) {
+// TestListRuntimeUsageBucketsByViewerTimezone proves the runtime trend reads
+// bucket the day boundary in the VIEWER's tz (the argument passed to
+// listRuntimeUsage). The viewer tz is Asia/Shanghai; assertions only pass if
+// listRuntimeUsage applies that tz correctly.
+func TestListRuntimeUsageBucketsByViewerTimezone(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -213,40 +215,40 @@ func TestGetRuntimeUsageDailyRollupCutoffUsesRuntimeTimezone(t *testing.T) {
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)
+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly 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)
- }
+ // Seed task_usage_hourly directly with one bucket per Shanghai calendar
+ // day. Pick 04:00 local (= 20:00 UTC the previous day) to catch
+ // off-by-one tz-cutoff bugs.
+ var agentID pgtype.UUID
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent WHERE workspace_id = $1 ORDER BY id LIMIT 1
+ `, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("pick fixture agent: %v", err)
+ }
if _, err := testPool.Exec(ctx, `
- INSERT INTO task_usage_daily (
- bucket_date, workspace_id, runtime_id, provider, model,
+ INSERT INTO task_usage_hourly (
+ bucket_hour, workspace_id, runtime_id, agent_id, project_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
+ (($1::date + interval '4 hours') AT TIME ZONE 'Asia/Shanghai', $3, $4, $5, NULL,
+ 'cutoff-test', 'old-day', 111, 0, 0, 0, 1),
+ (($2::date + interval '4 hours') AT TIME ZONE 'Asia/Shanghai', $3, $4, $5, NULL,
+ 'cutoff-test', 'cutoff-day', 222, 0, 0, 0, 1)
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key 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)
+ `, extraDate, cutoffDate, testWorkspaceID, runtimeID, agentID); err != nil {
+ t.Fatalf("seed hourly 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,
@@ -268,128 +270,113 @@ func TestGetRuntimeUsageDailyRollupCutoffUsesRuntimeTimezone(t *testing.T) {
}
}
-func TestUpdateAgentRuntimeTimezoneValidatesPermissionAndValue(t *testing.T) {
+// TestResolveViewingTZ covers the three legs of resolveViewingTZ:
+// explicit `?tz=` query param, the authenticated user's stored
+// user.timezone, and the UTC fallback when neither yields a valid zone.
+func TestResolveViewingTZ(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())
+ var userID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email, timezone)
+ VALUES ('TZ Resolve', '[email protected]', 'Asia/Tokyo') RETURNING id`,
+ ).Scan(&userID); err != nil {
+ t.Fatalf("insert user: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, userID) })
+
+ // Explicit ?tz= wins over the stored preference.
+ req := newRequest("GET", "/api/dashboard/usage/daily?tz=America/New_York", nil)
+ req.Header.Set("X-User-ID", userID)
+ if got := testHandler.resolveViewingTZ(req); got != "America/New_York" {
+ t.Fatalf("query param: expected America/New_York, got %q", got)
+ }
+
+ // No ?tz= → falls back to the authenticated user's stored timezone.
+ req = newRequest("GET", "/api/dashboard/usage/daily", nil)
+ req.Header.Set("X-User-ID", userID)
+ if got := testHandler.resolveViewingTZ(req); got != "Asia/Tokyo" {
+ t.Fatalf("stored fallback: expected Asia/Tokyo, got %q", got)
+ }
+
+ // An unparseable ?tz= is ignored, falling through to the stored value.
+ req = newRequest("GET", "/api/dashboard/usage/daily?tz=Mars/Olympus", nil)
+ req.Header.Set("X-User-ID", userID)
+ if got := testHandler.resolveViewingTZ(req); got != "Asia/Tokyo" {
+ t.Fatalf("invalid query param: expected Asia/Tokyo fallback, got %q", got)
+ }
+
+ // No ?tz= and no stored value → UTC.
+ var bareUserID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email)
+ VALUES ('TZ Bare', '[email protected]') RETURNING id`,
+ ).Scan(&bareUserID); err != nil {
+ t.Fatalf("insert bare user: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, bareUserID) })
+ req = newRequest("GET", "/api/dashboard/usage/daily", nil)
+ req.Header.Set("X-User-ID", bareUserID)
+ if got := testHandler.resolveViewingTZ(req); got != "UTC" {
+ t.Fatalf("no preference: expected UTC, got %q", got)
+ }
+
+ // A stored timezone that is itself an invalid IANA zone — e.g. a row
+ // written before server-side validation existed — must fall through
+ // to UTC. Without the LoadLocation guard on the stored value this
+ // string would reach SQL `AT TIME ZONE` and 500 every dashboard read.
+ var badTZUserID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email, timezone)
+ VALUES ('TZ Bad', '[email protected]', 'Bad/Zone') RETURNING id`,
+ ).Scan(&badTZUserID); err != nil {
+ t.Fatalf("insert bad-tz user: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, badTZUserID) })
+ req = newRequest("GET", "/api/dashboard/usage/daily", nil)
+ req.Header.Set("X-User-ID", badTZUserID)
+ if got := testHandler.resolveViewingTZ(req); got != "UTC" {
+ t.Fatalf("invalid stored tz: expected UTC fallback, got %q", got)
+ }
+
+ // No X-User-ID header and no ?tz= — an unauthenticated caller has
+ // neither signal, so the resolver must return UTC without attempting
+ // (and panicking on) a GetUser lookup.
+ req = newRequest("GET", "/api/dashboard/usage/daily", nil)
+ if got := testHandler.resolveViewingTZ(req); got != "UTC" {
+ t.Fatalf("unauthenticated caller: expected UTC, got %q", got)
}
}
-func TestUpsertAgentRuntimePreservesTimezoneOverride(t *testing.T) {
+// TestRuntimeHeatmapEndpointsUseViewerTZ verifies that the hour-of-day
+// heatmap endpoints (GetRuntimeUsageByHour and GetRuntimeTaskActivity) bucket
+// in the viewer's tz supplied via ?tz= and return 200.
+func TestRuntimeHeatmapEndpointsUseViewerTZ(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)
- }
+ runtimeID := handlerTestRuntimeID(t)
- 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)
+ cases := []struct {
+ name string
+ path string
+ handle func(http.ResponseWriter, *http.Request)
+ }{
+ {"usage by-hour", "/api/runtimes/" + runtimeID + "/usage/by-hour?tz=Asia/Shanghai", testHandler.GetRuntimeUsageByHour},
+ {"task activity", "/api/runtimes/" + runtimeID + "/activity?tz=Asia/Shanghai", testHandler.GetRuntimeTaskActivity},
}
- if row.Timezone != "America/New_York" {
- t.Fatalf("daemon reconnect should preserve user override, got %q", row.Timezone)
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("GET", c.path, nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ c.handle(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: expected 200, got %d: %s", c.name, w.Code, w.Body.String())
+ }
+ })
}
}
diff --git a/server/internal/handler/runtime_visibility_test.go b/server/internal/handler/runtime_visibility_test.go
index 618484d948..084f75014e 100644
--- a/server/internal/handler/runtime_visibility_test.go
+++ b/server/internal/handler/runtime_visibility_test.go
@@ -274,65 +274,89 @@ func TestUpdateAgent_RejectsRebindToPrivateRuntime(t *testing.T) {
}
}
-// TestUpdateAgentRuntime_CombinedPatchAppliesBoth pins the post-review
-// invariant that a PATCH carrying BOTH `timezone` and `visibility` runs
-// both mutations. Before the fix, the timezone branch returned early on
-// a tz no-op (`tz == rt.Timezone`) and the visibility branch was never
-// reached, silently dropping half of a legitimate request.
-func TestUpdateAgentRuntime_CombinedPatchAppliesBoth(t *testing.T) {
+// TestUpdateAgentRuntime_VisibilityPatchApplies pins the invariant that
+// a PATCH carrying `visibility` correctly updates the runtime.
+func TestUpdateAgentRuntime_VisibilityPatchApplies(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID, runtimeOwnerID, _ := runtimeVisibilityFixture(t)
- // Use the runtime's CURRENT timezone (UTC by default) so the timezone
- // branch is a no-op — that's the exact case the old short-circuit hit.
w := httptest.NewRecorder()
req := newRequestAs(runtimeOwnerID, http.MethodPatch, "/api/runtimes/"+runtimeID, map[string]any{
- "timezone": "UTC",
"visibility": "public",
})
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.UpdateAgentRuntime(w, req)
if w.Code != http.StatusOK {
- t.Fatalf("PATCH timezone+visibility (tz no-op): expected 200, got %d: %s", w.Code, w.Body.String())
+ t.Fatalf("PATCH visibility: 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.Visibility != "public" {
- t.Fatalf("combined patch dropped visibility: got %q, want public", resp.Visibility)
+ t.Fatalf("visibility patch: got %q, want public", resp.Visibility)
}
}
-// TestUpdateAgentRuntime_InvalidVisibilityDoesNotMutateTimezone pins the
-// other half of the ordering fix: when visibility is invalid the handler
-// must 400 BEFORE running the timezone mutation, so a malformed request
-// can't leave the row half-updated (timezone written, visibility rejected).
-func TestUpdateAgentRuntime_InvalidVisibilityDoesNotMutateTimezone(t *testing.T) {
+// TestUpdateAgentRuntime_IgnoresTimezoneField guards the RFC migration that
+// dropped `timezone` from UpdateAgentRuntimeRequest: a PATCH body still
+// carrying `timezone` must not error, must not echo a `timezone` key back,
+// and must still apply the recognised `visibility` field. Timezone is now a
+// user-level preference, not a per-runtime one.
+func TestUpdateAgentRuntime_IgnoresTimezoneField(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
runtimeID, runtimeOwnerID, _ := runtimeVisibilityFixture(t)
- ctx := context.Background()
- // Snapshot the timezone before the request so we can assert it didn't
- // move. The fixture inserts the runtime with the table default (UTC),
- // but we read instead of hard-coding so future fixture changes don't
- // silently make the test pass for the wrong reason.
- var beforeTZ string
- if err := testPool.QueryRow(ctx,
- `SELECT timezone FROM agent_runtime WHERE id = $1`, runtimeID,
- ).Scan(&beforeTZ); err != nil {
- t.Fatalf("snapshot timezone: %v", err)
+ w := httptest.NewRecorder()
+ // NOTE: visibility is "public" (not "workspace"): the runtime visibility
+ // enum is private|public — "workspace" would 400 before any mutation,
+ // which would not exercise the "visibility still applied" assertion.
+ req := newRequestAs(runtimeOwnerID, http.MethodPatch, "/api/runtimes/"+runtimeID, map[string]any{
+ "timezone": "Asia/Tokyo",
+ "visibility": "public",
+ })
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.UpdateAgentRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("PATCH with stray timezone: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // The response must carry no `timezone` key — runtimes have no such field.
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if _, present := raw["timezone"]; present {
+ t.Errorf("response unexpectedly contains a timezone key: %s", w.Body.String())
+ }
+
+ // `visibility` was still applied.
+ var resp AgentRuntimeResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Visibility != "public" {
+ t.Errorf("visibility patch: got %q, want public", resp.Visibility)
}
+}
+
+// TestUpdateAgentRuntime_InvalidVisibilityReturns400 verifies that an invalid
+// visibility value is rejected with 400 before any mutation runs.
+func TestUpdateAgentRuntime_InvalidVisibilityReturns400(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID, runtimeOwnerID, _ := runtimeVisibilityFixture(t)
w := httptest.NewRecorder()
req := newRequestAs(runtimeOwnerID, http.MethodPatch, "/api/runtimes/"+runtimeID, map[string]any{
- "timezone": "Asia/Tokyo",
"visibility": "everyone",
})
req = withURLParam(req, "runtimeId", runtimeID)
@@ -340,16 +364,6 @@ func TestUpdateAgentRuntime_InvalidVisibilityDoesNotMutateTimezone(t *testing.T)
if w.Code != http.StatusBadRequest {
t.Fatalf("PATCH with invalid visibility: expected 400, got %d: %s", w.Code, w.Body.String())
}
-
- var afterTZ string
- if err := testPool.QueryRow(ctx,
- `SELECT timezone FROM agent_runtime WHERE id = $1`, runtimeID,
- ).Scan(&afterTZ); err != nil {
- t.Fatalf("re-read timezone: %v", err)
- }
- if afterTZ != beforeTZ {
- t.Fatalf("400 on visibility must not mutate timezone: before=%q after=%q", beforeTZ, afterTZ)
- }
}
// TestUpdateAgentRuntime_VisibilityToggle covers the PATCH endpoint:
diff --git a/server/internal/handler/usage_test.go b/server/internal/handler/usage_test.go
deleted file mode 100644
index 6b96f96cd6..0000000000
--- a/server/internal/handler/usage_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package handler
-
-import (
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-)
-
-// 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 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")
- }
- ctx := context.Background()
-
- var runtimeID, agentID string
- if err := testPool.QueryRow(ctx, `
- SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1
- `, testWorkspaceID).Scan(&runtimeID); err != nil {
- t.Fatalf("fetch runtime: %v", err)
- }
- 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, 'workspace usage test', $2, 'member')
- RETURNING id
- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
- t.Fatalf("create issue: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)
- })
-
- now := time.Now().UTC()
- today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
- yesterdayLate := today.Add(-2 * time.Minute)
- todayEarly := today.Add(5 * time.Minute)
- yesterdayMorning := today.Add(-19 * time.Hour)
-
- insertTaskWithUsage := func(enqueueAt, usageAt time.Time, inputTokens int64) {
- 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, enqueueAt).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)
- VALUES ($1, 'claude', 'claude-3-5-sonnet', $2, 0, $3)
- `, taskID, inputTokens, usageAt); err != nil {
- t.Fatalf("insert task_usage: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
- })
- }
-
- insertTaskWithUsage(yesterdayLate, todayEarly, 1000) // cross-midnight
- insertTaskWithUsage(yesterdayMorning, yesterdayMorning, 2000) // full-day yesterday
-
- // /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=2", nil)
- testHandler.GetWorkspaceUsageByDay(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("GetWorkspaceUsageByDay: expected 200, got %d: %s", w.Code, w.Body.String())
- }
-
- type dailyRow struct {
- Date string `json:"date"`
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- }
- var dailyResp []dailyRow
- if err := json.NewDecoder(w.Body).Decode(&dailyResp); err != nil {
- t.Fatalf("decode daily: %v", err)
- }
- byDate := make(map[string]int64)
- for _, r := range dailyResp {
- byDate[r.Date] += r.TotalInputTokens
- }
- todayKey := today.Format("2006-01-02")
- yesterdayKey := today.Add(-24 * time.Hour).Format("2006-01-02")
- if byDate[todayKey] < 1000 {
- t.Errorf("daily: today bucket expected >=1000 input tokens (cross-midnight task), got %d (full map: %v)", byDate[todayKey], byDate)
- }
- if byDate[yesterdayKey] < 2000 {
- t.Errorf("daily: yesterday bucket expected >=2000 input tokens (yesterday morning task), got %d (full map: %v)", byDate[yesterdayKey], byDate)
- }
-
- // /api/usage/summary — aggregate across the full window. Both rows must
- // 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=2", nil)
- testHandler.GetWorkspaceUsageSummary(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("GetWorkspaceUsageSummary: expected 200, got %d: %s", w.Code, w.Body.String())
- }
- type summaryRow struct {
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- TaskCount int32 `json:"task_count"`
- }
- var summaryResp []summaryRow
- if err := json.NewDecoder(w.Body).Decode(&summaryResp); err != nil {
- t.Fatalf("decode summary: %v", err)
- }
- var totalInput int64
- var totalTasks int32
- for _, r := range summaryResp {
- if r.Model == "claude-3-5-sonnet" {
- totalInput += r.TotalInputTokens
- totalTasks += r.TaskCount
- }
- }
- if totalInput < 3000 {
- t.Errorf("summary: claude-3-5-sonnet input tokens expected >=3000 (1000 + 2000), got %d (full resp: %v)", totalInput, summaryResp)
- }
- if totalTasks < 2 {
- t.Errorf("summary: claude-3-5-sonnet task_count expected >=2, got %d (full resp: %v)", totalTasks, summaryResp)
- }
-}
diff --git a/server/internal/handler/user_timezone_test.go b/server/internal/handler/user_timezone_test.go
new file mode 100644
index 0000000000..22e0160dc1
--- /dev/null
+++ b/server/internal/handler/user_timezone_test.go
@@ -0,0 +1,149 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+)
+
+func newTimezoneTestUser(t *testing.T, email string) string {
+ t.Helper()
+ ctx := context.Background()
+
+ var userID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "Timezone Test", email,
+ ).Scan(&userID); err != nil {
+ t.Fatalf("insert test user: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, userID)
+ })
+ return userID
+}
+
+func TestUpdateMeAcceptsTimezone(t *testing.T) {
+ userID := newTimezoneTestUser(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ req := newPatchMeRequest(userID, `{"timezone":"Asia/Shanghai"}`)
+ testHandler.UpdateMe(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stored *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT timezone FROM "user" WHERE id = $1`, userID,
+ ).Scan(&stored); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+ if stored == nil || *stored != "Asia/Shanghai" {
+ t.Fatalf("expected timezone=Asia/Shanghai, got %v", stored)
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if got, _ := resp["timezone"].(string); got != "Asia/Shanghai" {
+ t.Fatalf("expected response timezone=Asia/Shanghai, got %v", resp["timezone"])
+ }
+}
+
+func TestUpdateMeRejectsInvalidTimezone(t *testing.T) {
+ userID := newTimezoneTestUser(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ req := newPatchMeRequest(userID, `{"timezone":"Not/A/Real/Zone"}`)
+ testHandler.UpdateMe(w, req)
+
+ if w.Code != 400 {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stored *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT timezone FROM "user" WHERE id = $1`, userID,
+ ).Scan(&stored); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+ if stored != nil {
+ t.Fatalf("expected timezone unchanged (NULL), got %v", *stored)
+ }
+}
+
+// COALESCE semantics — omitting timezone must NOT clear an existing value.
+func TestUpdateMePreservesTimezoneWhenNotProvided(t *testing.T) {
+ userID := newTimezoneTestUser(t, "[email protected]")
+
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE "user" SET timezone = 'America/Los_Angeles' WHERE id = $1`, userID,
+ ); err != nil {
+ t.Fatalf("preset timezone: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newPatchMeRequest(userID, `{"name":"Updated Name"}`)
+ testHandler.UpdateMe(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stored *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT timezone FROM "user" WHERE id = $1`, userID,
+ ).Scan(&stored); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+ if stored == nil || *stored != "America/Los_Angeles" {
+ t.Fatalf("expected timezone preserved, got %v", stored)
+ }
+}
+
+// Explicit clear: `"timezone": ""` should NULL the column so the frontend
+// falls back to the browser-detected tz again. Without the CASE branch in
+// the UPDATE query this would either be a no-op (COALESCE) or a validation
+// error.
+func TestUpdateMeClearsTimezoneOnEmptyString(t *testing.T) {
+ userID := newTimezoneTestUser(t, "[email protected]")
+
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE "user" SET timezone = 'Asia/Shanghai' WHERE id = $1`, userID,
+ ); err != nil {
+ t.Fatalf("preset timezone: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newPatchMeRequest(userID, `{"timezone":""}`)
+ testHandler.UpdateMe(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var stored *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT timezone FROM "user" WHERE id = $1`, userID,
+ ).Scan(&stored); err != nil {
+ t.Fatalf("lookup user: %v", err)
+ }
+ if stored != nil {
+ t.Fatalf("expected timezone cleared to NULL, got %v", *stored)
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ // JSON null marshals from *string nil — confirm the response reflects
+ // the cleared state, so the frontend can switch its picker back to
+ // "(browser)" without a refetch.
+ if resp["timezone"] != nil {
+ t.Fatalf("expected response timezone=null, got %v", resp["timezone"])
+ }
+}
diff --git a/server/migrations/100_user_timezone.down.sql b/server/migrations/100_user_timezone.down.sql
new file mode 100644
index 0000000000..584ca4cedc
--- /dev/null
+++ b/server/migrations/100_user_timezone.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "user"
+ DROP COLUMN IF EXISTS timezone;
diff --git a/server/migrations/100_user_timezone.up.sql b/server/migrations/100_user_timezone.up.sql
new file mode 100644
index 0000000000..5226c7cdbb
--- /dev/null
+++ b/server/migrations/100_user_timezone.up.sql
@@ -0,0 +1,32 @@
+-- Per-user IANA timezone for *viewing* reports — the third leg of the
+-- Operational / Scheduling / Viewing trio (see docs/timezone-architecture-rfc.md).
+--
+-- Distinct from:
+-- * agent_runtime.timezone (Operational): where a runtime physically runs.
+-- That column is dropped later in this migration set — the hour-of-day
+-- activity heatmap now uses the viewer's tz instead.
+-- * autopilot_trigger.timezone (Scheduling): the tz the user had in mind
+-- when authoring a "run at 9am" rule.
+--
+-- This column answers: when this user looks at a dashboard, which calendar
+-- day should "today" be? Two members of the same workspace sitting in
+-- different regions each see their own "today" rendered from the same
+-- underlying UTC data.
+--
+-- NULL means "fall back to the browser-detected tz at render time". New
+-- users land on NULL, so there is no required onboarding step; the
+-- frontend resolves it transparently. A user who explicitly picks an
+-- IANA name in Preferences pins the value here so it survives across
+-- devices and sessions.
+--
+-- This column never affects how data is materialised — all rollups stay
+-- in UTC. It is read-only from the rollup pipeline's perspective and is
+-- only consumed at query time to drive `DATE(bucket_hour AT TIME ZONE @tz)`.
+ALTER TABLE "user"
+ ADD COLUMN timezone TEXT NULL;
+
+COMMENT ON COLUMN "user".timezone IS
+ 'User-preferred IANA timezone for report rendering (Viewing tz). '
+ 'NULL means "use the browser-detected tz at render time". Affects '
+ 'dashboards, charts, and any "today" label shown to this user. Does '
+ 'not affect data materialisation — all rollups remain in UTC.';
diff --git a/server/migrations/101_task_usage_hourly_schema.down.sql b/server/migrations/101_task_usage_hourly_schema.down.sql
new file mode 100644
index 0000000000..882a887707
--- /dev/null
+++ b/server/migrations/101_task_usage_hourly_schema.down.sql
@@ -0,0 +1,3 @@
+DROP TABLE IF EXISTS task_usage_hourly_dirty;
+DROP TABLE IF EXISTS task_usage_hourly_rollup_state;
+DROP TABLE IF EXISTS task_usage_hourly;
diff --git a/server/migrations/101_task_usage_hourly_schema.up.sql b/server/migrations/101_task_usage_hourly_schema.up.sql
new file mode 100644
index 0000000000..04f3cb9b20
--- /dev/null
+++ b/server/migrations/101_task_usage_hourly_schema.up.sql
@@ -0,0 +1,133 @@
+-- Hourly rollup table for `task_usage`, materialised in **UTC**. Replaces
+-- both per-runtime `task_usage_daily` (073, 082) and per-workspace
+-- `task_usage_dashboard_daily` (084) as the single source of truth for
+-- all token-usage reports. See docs/timezone-architecture-rfc.md §4.
+--
+-- WHY HOURLY + UTC:
+-- The two existing rollups materialise on a `DATE` bucket — one in the
+-- runtime's IANA tz, the other in UTC — which forces every report to
+-- either accept the materialised tz or scan raw `task_usage`. Hourly
+-- UTC buckets are tz-neutral: any viewer-side tz can be applied at
+-- query time via `DATE(bucket_hour AT TIME ZONE @tz)` without losing
+-- precision and without crossing midnight in the wrong direction.
+--
+-- WHY ONE TABLE INSTEAD OF TWO:
+-- The two existing rollups share the same source rows and the same
+-- invalidation surface (atq, task_usage, issue.project_id); maintaining
+-- them separately is duplicative. The unified PK carries runtime_id,
+-- agent_id, AND project_id, so:
+-- * Runtime-detail views filter on runtime_id (covered by
+-- idx_..._runtime_time).
+-- * Workspace-dashboard views filter on workspace_id + group by
+-- agent_id / project_id (covered by the three workspace indexes).
+-- * The hour-of-day heatmap groups by EXTRACT(HOUR FROM ... AT TIME
+-- ZONE <viewer's tz>) over the same rows — no separate aggregate.
+--
+-- WHY PROVIDER+MODEL IN THE PK:
+-- Per-model breakdowns are a primary read dimension (cost per model,
+-- trend per model). Keeping them in the PK keeps the rollup pre-grouped
+-- along the same axis the UI uses.
+--
+-- WHY `UNIQUE NULLS NOT DISTINCT`:
+-- `project_id` is nullable — tasks linked to issues without a project,
+-- and the quick-create path's "no issue yet" state, both produce
+-- no-project usage. PG15's `UNIQUE NULLS NOT DISTINCT` lets ON CONFLICT
+-- upsert the no-project bucket the same way it handles a concrete
+-- project. (Same pattern as 084.)
+CREATE TABLE task_usage_hourly (
+ bucket_hour TIMESTAMPTZ NOT NULL, -- UTC, truncated to hour boundary
+ workspace_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ project_id UUID, -- nullable; see above
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ input_tokens BIGINT NOT NULL DEFAULT 0,
+ output_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,
+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,
+ task_count BIGINT NOT NULL DEFAULT 0,
+ event_count BIGINT NOT NULL DEFAULT 0,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_task_usage_hourly_key
+ UNIQUE NULLS NOT DISTINCT
+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
+);
+
+-- Workspace-wide trend (no other filter): /{slug}/dashboard. The leading
+-- workspace_id matches every dashboard query; bucket_hour DESC avoids an
+-- extra sort when the report walks "last 7/30/90 days" backwards.
+CREATE INDEX idx_task_usage_hourly_workspace_time
+ ON task_usage_hourly (workspace_id, bucket_hour DESC);
+
+-- Runtime detail page — trend + hour-of-day heatmap on a single runtime.
+-- The heatmap groups by `EXTRACT(HOUR FROM bucket_hour AT TIME ZONE
+-- <viewer's tz>)` over this range, so we want the rows pre-clustered
+-- by runtime.
+CREATE INDEX idx_task_usage_hourly_runtime_time
+ ON task_usage_hourly (runtime_id, bucket_hour DESC);
+
+-- Workspace dashboard "by agent" panel.
+CREATE INDEX idx_task_usage_hourly_workspace_agent_time
+ ON task_usage_hourly (workspace_id, agent_id, bucket_hour DESC);
+
+-- Workspace dashboard "by project" panel. Partial because no-project
+-- buckets aggregate into a separate bucket and the panel filters them
+-- out; this keeps the index small.
+CREATE INDEX idx_task_usage_hourly_workspace_project_time
+ ON task_usage_hourly (workspace_id, project_id, bucket_hour DESC)
+ WHERE project_id IS NOT NULL;
+
+-- Single-row state table tracking the rollup worker's watermark. Same
+-- shape as 073's `task_usage_rollup_state` and 084's
+-- `task_usage_dashboard_rollup_state` — a SMALLINT(1) PK is the easiest
+-- way to enforce "exactly one row" without a CHECK trigger.
+CREATE TABLE task_usage_hourly_rollup_state (
+ id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
+ watermark_at TIMESTAMPTZ NOT NULL DEFAULT '1970-01-01 00:00:00+00',
+ last_run_started_at TIMESTAMPTZ,
+ last_run_finished_at TIMESTAMPTZ,
+ last_run_rows BIGINT NOT NULL DEFAULT 0,
+ last_error TEXT
+);
+INSERT INTO task_usage_hourly_rollup_state (id) VALUES (1) ON CONFLICT DO NOTHING;
+
+-- Dirty queue for invalidations the `updated_at` watermark cannot see:
+-- * DELETE on `task_usage` (no row left for the watermark to catch).
+-- * Cascade DELETE through `agent_task_queue` (task_usage rows gone).
+-- * UPDATE of `issue.project_id` — moves the bucket to a new key,
+-- OLD bucket needs to shrink, NEW bucket needs to appear.
+-- * UPDATE of `agent_task_queue.runtime_id` / `agent_task_queue.issue_id`
+-- — same re-attribution problem on different dimensions.
+--
+-- bucket_hour is computed in UTC at trigger time, so dirty keys match
+-- the rollup table byte-for-byte and the window function can UNION the
+-- queue into `dirty_keys` without translation.
+--
+-- TTL: rows in this queue MUST be pruned (see prune_task_usage_hourly_dirty
+-- in the rollup-pipeline migration). Without TTL, dense workloads grow the queue
+-- unboundedly — every retouched
+-- bucket leaves a row behind. The window function deletes rows whose
+-- enqueued_at < p_to as part of each tick, which keeps the steady state
+-- bounded; the explicit prune is a belt-and-braces guarantee for rows
+-- that somehow escape the window (e.g. crash mid-tick).
+CREATE TABLE task_usage_hourly_dirty (
+ bucket_hour TIMESTAMPTZ NOT NULL,
+ workspace_id UUID NOT NULL,
+ runtime_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ project_id UUID,
+ provider TEXT NOT NULL,
+ model TEXT NOT NULL,
+ enqueued_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_task_usage_hourly_dirty_key
+ UNIQUE NULLS NOT DISTINCT
+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)
+);
+
+-- The window function drains rows with enqueued_at < p_to; the prune
+-- helper (prune_task_usage_hourly_dirty) deletes rows
+-- whose enqueued_at falls outside the retention horizon. Both scans
+-- use this index.
+CREATE INDEX idx_task_usage_hourly_dirty_enqueued_at
+ ON task_usage_hourly_dirty (enqueued_at);
diff --git a/server/migrations/102_task_usage_hourly_pipeline.down.sql b/server/migrations/102_task_usage_hourly_pipeline.down.sql
new file mode 100644
index 0000000000..a2171879ae
--- /dev/null
+++ b/server/migrations/102_task_usage_hourly_pipeline.down.sql
@@ -0,0 +1,31 @@
+-- Unschedule the cron job first — the operator playbook in the up
+-- migration registers it, so a rollback must clear it before the
+-- function it calls is dropped, or the still-registered job ticks into
+-- a `function does not exist` error. Guarded so rollback still succeeds
+-- where pg_cron is absent or the job was never registered (same pattern
+-- as migration 103).
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_cron') THEN
+ PERFORM cron.unschedule('rollup_task_usage_hourly')
+ FROM cron.job WHERE jobname = 'rollup_task_usage_hourly';
+ END IF;
+END
+$$;
+
+DROP TRIGGER IF EXISTS trg_tu_dirty_hourly ON task_usage;
+DROP TRIGGER IF EXISTS trg_issue_project_dirty_hourly ON issue;
+DROP TRIGGER IF EXISTS trg_issue_delete_dirty_hourly ON issue;
+DROP TRIGGER IF EXISTS trg_atq_dirty_hourly ON agent_task_queue;
+
+DROP FUNCTION IF EXISTS task_usage_hourly_rollup_lag_seconds();
+DROP FUNCTION IF EXISTS rollup_task_usage_hourly();
+DROP FUNCTION IF EXISTS prune_task_usage_hourly_dirty(INTERVAL);
+DROP FUNCTION IF EXISTS rollup_task_usage_hourly_window(TIMESTAMPTZ, TIMESTAMPTZ);
+
+DROP FUNCTION IF EXISTS enqueue_task_usage_hourly_dirty_for_tu();
+DROP FUNCTION IF EXISTS enqueue_task_usage_hourly_dirty_for_issue_project();
+DROP FUNCTION IF EXISTS enqueue_task_usage_hourly_dirty_for_issue_delete();
+DROP FUNCTION IF EXISTS enqueue_task_usage_hourly_dirty_for_atq();
+
+DROP FUNCTION IF EXISTS task_usage_hour_bucket(TIMESTAMPTZ);
diff --git a/server/migrations/102_task_usage_hourly_pipeline.up.sql b/server/migrations/102_task_usage_hourly_pipeline.up.sql
new file mode 100644
index 0000000000..fc08c5e447
--- /dev/null
+++ b/server/migrations/102_task_usage_hourly_pipeline.up.sql
@@ -0,0 +1,524 @@
+-- Rollup window + triggers + cron entry for `task_usage_hourly`. Same
+-- shape as 077 (per-runtime daily) and 084 (dashboard daily), the
+-- differences are:
+-- * bucket grain is HOUR, not DATE.
+-- * bucket boundary is always UTC — regardless of any runtime tz —
+-- because viewer-side tz is applied at query time.
+-- * a single PK covers runtime + agent + project + provider + model,
+-- so both prior pipelines collapse into this one.
+--
+-- IDEMPOTENCY CONTRACT (same as 073/084):
+-- For every dirty key, this function REPLACES the corresponding
+-- hourly row with the SUM of *all* task_usage rows for that key. It
+-- does NOT delta. Re-running an overlapping window yields the same
+-- final state, which is what makes "cron + offline backfill" safe to
+-- run concurrently.
+--
+-- The window function returns the number of (upserted + deleted-empty)
+-- rows. Empty buckets that recomputed to zero (because their source
+-- rows were deleted or re-attributed) get removed in the same
+-- transaction — same `deleted_empty` CTE pattern as 084.
+
+-- Helper: canonical UTC hour boundary. Centralised so triggers and the
+-- recompute CTE compute the same expression byte-for-byte; a drift here
+-- splits the bucket key between writers and the rollup table and the
+-- bucket never converges.
+--
+-- The two `AT TIME ZONE 'UTC'` are not redundant: the first casts
+-- timestamptz -> timestamp (UTC wall clock) so date_trunc is independent
+-- of the session timezone; the second casts back to timestamptz. Do not
+-- collapse to a bare date_trunc — that would inherit the session tz.
+CREATE OR REPLACE FUNCTION task_usage_hour_bucket(ts TIMESTAMPTZ)
+RETURNS TIMESTAMPTZ
+LANGUAGE sql
+IMMUTABLE
+AS $$
+ SELECT (date_trunc('hour', ts AT TIME ZONE 'UTC')) AT TIME ZONE 'UTC';
+$$;
+
+-- Trigger 1: agent_task_queue BEFORE UPDATE OF runtime_id / issue_id OR DELETE.
+--
+-- Runtime reassignment moves usage between runtime buckets; issue
+-- reassignment moves it between (project_id) buckets. Both need
+-- OLD and NEW keys enqueued. DELETE only enqueues OLD.
+--
+-- The atq trigger fires while OLD.* is still resolvable. For DELETE
+-- cascades coming from `issue` DELETE, the issue row is gone by the
+-- time this trigger sees the atq row, so `LEFT JOIN issue` resolves
+-- project_id = NULL. The companion issue-DELETE trigger below covers
+-- that case while issue is still readable.
+CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_atq()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ IF OLD.runtime_id IS DISTINCT FROM NEW.runtime_id
+ OR OLD.issue_id IS DISTINCT FROM NEW.issue_id THEN
+ -- OLD side. NULL runtime_id rows are not aggregated (no
+ -- runtime → no bucket); skip those.
+ IF OLD.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ a.workspace_id,
+ OLD.runtime_id,
+ OLD.agent_id,
+ i_old.project_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ LEFT JOIN issue i_old ON i_old.id = OLD.issue_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+
+ IF NEW.runtime_id IS NOT NULL THEN
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ a.workspace_id,
+ NEW.runtime_id,
+ NEW.agent_id,
+ i_new.project_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = NEW.agent_id
+ LEFT JOIN issue i_new ON i_new.id = NEW.issue_id
+ WHERE tu.task_id = NEW.id
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_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_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ a.workspace_id,
+ OLD.runtime_id,
+ OLD.agent_id,
+ i.project_id,
+ tu.provider,
+ tu.model
+ FROM task_usage tu
+ JOIN agent a ON a.id = OLD.agent_id
+ LEFT JOIN issue i ON i.id = OLD.issue_id
+ WHERE tu.task_id = OLD.id
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ RETURN OLD;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+
+-- INVARIANT: agent_task_queue.agent_id is immutable once a row is inserted.
+-- If a future feature makes agent_id mutable (e.g. reassign / rebind), it
+-- MUST be added to this trigger's `OF` column list, otherwise dirty
+-- buckets for the old agent_id will not be enqueued and historical
+-- aggregates will silently rot.
+CREATE TRIGGER trg_atq_dirty_hourly
+BEFORE UPDATE OF runtime_id, issue_id OR DELETE ON agent_task_queue
+FOR EACH ROW EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_atq();
+
+-- Trigger 2: issue BEFORE DELETE — see the analogous trigger in 084 for
+-- the full motivation. By the time the atq cascade fires, the issue
+-- row is gone, so we capture project_id here while it is still readable.
+CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ OLD.workspace_id,
+ atq.runtime_id,
+ atq.agent_id,
+ OLD.project_id,
+ tu.provider,
+ tu.model
+ FROM agent_task_queue atq
+ JOIN task_usage tu ON tu.task_id = atq.id
+ WHERE atq.issue_id = OLD.id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER trg_issue_delete_dirty_hourly
+BEFORE DELETE ON issue
+FOR EACH ROW EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete();
+
+-- Trigger 3: issue BEFORE UPDATE OF project_id — re-attribute every
+-- bucket touched by tasks under this issue. Same logic as 084's
+-- analogous trigger.
+CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_project()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF OLD.project_id IS DISTINCT FROM NEW.project_id THEN
+ -- OLD project buckets.
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ NEW.workspace_id,
+ atq.runtime_id,
+ atq.agent_id,
+ OLD.project_id,
+ tu.provider,
+ tu.model
+ FROM agent_task_queue atq
+ JOIN task_usage tu ON tu.task_id = atq.id
+ WHERE atq.issue_id = NEW.id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+
+ -- NEW project buckets.
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT DISTINCT
+ task_usage_hour_bucket(tu.created_at),
+ NEW.workspace_id,
+ atq.runtime_id,
+ atq.agent_id,
+ NEW.project_id,
+ tu.provider,
+ tu.model
+ FROM agent_task_queue atq
+ JOIN task_usage tu ON tu.task_id = atq.id
+ WHERE atq.issue_id = NEW.id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER trg_issue_project_dirty_hourly
+BEFORE UPDATE OF project_id ON issue
+FOR EACH ROW EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_project();
+
+-- Trigger 4: task_usage BEFORE DELETE — rare in practice (no direct
+-- callers today) but keeps the rollup convergent if one is added.
+-- INSERT/UPDATE are covered by the watermark window.
+CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_tu()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ INSERT INTO task_usage_hourly_dirty (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ )
+ SELECT
+ task_usage_hour_bucket(OLD.created_at),
+ a.workspace_id,
+ atq.runtime_id,
+ atq.agent_id,
+ i.project_id,
+ OLD.provider,
+ OLD.model
+ FROM agent_task_queue atq
+ JOIN agent a ON a.id = atq.agent_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ WHERE atq.id = OLD.task_id
+ AND atq.runtime_id IS NOT NULL
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE
+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER trg_tu_dirty_hourly
+BEFORE DELETE ON task_usage
+FOR EACH ROW EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_tu();
+
+-- Window function. Mirrors 077/084's structure:
+-- 1. Discover dirty keys from the updated_at watermark + the queue.
+-- 2. Recompute each from raw via the atq + agent + issue join.
+-- 3. Upsert; delete buckets that recomputed to nothing.
+-- 4. Drain the queue rows whose enqueued_at < p_to.
+--
+-- The recompute LEFT JOINs `issue`, so tasks with no issue resolve to
+-- project_id = NULL and merge cleanly with the corresponding dirty key
+-- via `IS NOT DISTINCT FROM`.
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly_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
+ task_usage_hour_bucket(tu.created_at) AS bucket_hour,
+ a.workspace_id AS workspace_id,
+ atq.runtime_id AS runtime_id,
+ atq.agent_id AS agent_id,
+ i.project_id AS project_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
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ WHERE atq.runtime_id IS NOT NULL
+ AND (
+ (tu.updated_at >= p_from AND tu.updated_at < p_to)
+ -- Legacy updated_at-NULL rows; partial index from 078.
+ OR (tu.updated_at IS NULL
+ AND tu.created_at >= p_from
+ AND tu.created_at < p_to)
+ )
+ ),
+ dirty_from_queue AS (
+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model
+ FROM task_usage_hourly_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_hour,
+ dk.workspace_id,
+ dk.runtime_id,
+ dk.agent_id,
+ dk.project_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(DISTINCT tu.task_id)::bigint AS task_count,
+ COUNT(*)::bigint AS event_count
+ FROM dirty_keys dk
+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id
+ AND atq.agent_id = dk.agent_id
+ JOIN agent a ON a.id = atq.agent_id
+ AND a.workspace_id = dk.workspace_id
+ LEFT JOIN issue i ON i.id = atq.issue_id
+ JOIN task_usage tu ON tu.task_id = atq.id
+ AND tu.provider = dk.provider
+ AND tu.model = dk.model
+ AND task_usage_hour_bucket(tu.created_at) = dk.bucket_hour
+ WHERE (i.project_id IS NOT DISTINCT FROM dk.project_id)
+ GROUP BY 1, 2, 3, 4, 5, 6, 7
+ ),
+ upserted AS (
+ INSERT INTO task_usage_hourly AS d (
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ task_count, event_count
+ )
+ SELECT
+ bucket_hour, workspace_id, runtime_id, agent_id,
+ project_id, provider, model,
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
+ task_count, event_count
+ FROM recomputed
+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key 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,
+ task_count = EXCLUDED.task_count,
+ event_count = EXCLUDED.event_count,
+ updated_at = now()
+ RETURNING 1
+ ),
+ deleted_empty AS (
+ DELETE FROM task_usage_hourly d
+ USING dirty_keys dk
+ WHERE d.bucket_hour = dk.bucket_hour
+ AND d.workspace_id = dk.workspace_id
+ AND d.runtime_id = dk.runtime_id
+ AND d.agent_id = dk.agent_id
+ AND d.project_id IS NOT DISTINCT FROM dk.project_id
+ AND d.provider = dk.provider
+ AND d.model = dk.model
+ AND NOT EXISTS (
+ SELECT 1 FROM recomputed r
+ WHERE r.bucket_hour = dk.bucket_hour
+ AND r.workspace_id = dk.workspace_id
+ AND r.runtime_id = dk.runtime_id
+ AND r.agent_id = dk.agent_id
+ AND r.project_id IS NOT DISTINCT FROM dk.project_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_hourly_dirty WHERE enqueued_at < p_to;
+
+ RETURN v_rows;
+END;
+$$;
+
+-- Dirty-queue TTL. The window function above already deletes drained
+-- rows on every tick (`DELETE FROM task_usage_hourly_dirty WHERE
+-- enqueued_at < p_to`), which bounds the queue in steady state. This
+-- explicit prune is the belt-and-braces guarantee for rows that escape
+-- a tick — a crash mid-tick, or the worker paused during an incident /
+-- migration freeze. Without it the dirty queue grows unbounded: the
+-- hourly grain multiplies the retouched-bucket surface ~24x over the
+-- legacy daily rollups, and every retouched bucket leaves a row behind.
+--
+-- 7-day retention is generous on purpose — the only way a row survives
+-- a tick is operator action (worker paused), and a week is long enough
+-- that an on-call rotation will notice. Longer, and the queue size
+-- starts to dominate the cost of the very draining it enables. The cron
+-- entry below folds the prune in, so operators need no second job.
+CREATE OR REPLACE FUNCTION prune_task_usage_hourly_dirty(
+ p_retention INTERVAL DEFAULT INTERVAL '7 days'
+)
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_rows BIGINT;
+BEGIN
+ DELETE FROM task_usage_hourly_dirty
+ WHERE enqueued_at < now() - p_retention;
+ GET DIAGNOSTICS v_rows = ROW_COUNT;
+ RETURN v_rows;
+END;
+$$;
+
+-- Cron entry. Uses its own advisory lock id 4246 so a tick serialises
+-- only against other ticks of this same pipeline.
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly()
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_lock_ok BOOLEAN;
+ v_from TIMESTAMPTZ;
+ v_to TIMESTAMPTZ;
+ v_rows BIGINT := 0;
+BEGIN
+ SELECT pg_try_advisory_lock(4246) INTO v_lock_ok;
+ IF NOT v_lock_ok THEN
+ RETURN 0;
+ END IF;
+
+ BEGIN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_started_at = now(),
+ last_error = NULL
+ WHERE id = 1
+ RETURNING watermark_at INTO v_from;
+
+ -- Cap each tick at a one-day window. In steady state v_from is
+ -- recent, so LEAST picks `now() - 5 min` and nothing changes. But
+ -- if the worker was paused (incident, migration freeze) the
+ -- watermark can fall far behind; without the cap a single catch-up
+ -- tick would recompute a multi-week window in one statement while
+ -- holding lock 4246, blocking every other tick. Capped, catch-up
+ -- advances in bounded one-day steps over successive ticks.
+ v_to := LEAST(now() - INTERVAL '5 minutes', v_from + INTERVAL '1 day');
+
+ IF v_from < v_to THEN
+ v_rows := rollup_task_usage_hourly_window(v_from, v_to);
+
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = v_to,
+ last_run_finished_at = now(),
+ last_run_rows = v_rows
+ WHERE id = 1;
+ ELSE
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_finished_at = now(),
+ last_run_rows = 0
+ WHERE id = 1;
+ END IF;
+
+ PERFORM pg_advisory_unlock(4246);
+ EXCEPTION WHEN OTHERS THEN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_error = SQLERRM,
+ last_run_finished_at = now()
+ WHERE id = 1;
+ PERFORM pg_advisory_unlock(4246);
+ RAISE;
+ END;
+
+ -- TTL prune. Runs AFTER the advisory lock is released: on a large
+ -- stale backlog the prune can be slow, and holding lock 4246 through
+ -- it would serialise every concurrent cron tick. It is a plain
+ -- bounded DELETE — idempotent and safe to run unlocked.
+ PERFORM prune_task_usage_hourly_dirty();
+ RETURN v_rows;
+END;
+$$;
+
+-- Health-check helper — same shape as 076 / 084 lag helpers.
+CREATE OR REPLACE FUNCTION task_usage_hourly_rollup_lag_seconds()
+RETURNS DOUBLE PRECISION
+LANGUAGE sql
+STABLE
+AS $$
+ SELECT EXTRACT(EPOCH FROM (now() - last_run_finished_at))
+ FROM task_usage_hourly_rollup_state
+ WHERE id = 1;
+$$;
+
+-- Cron registration is intentionally deferred to the operator playbook,
+-- matching 076 / 084. Rollout sequence:
+-- 1) Apply the hourly-pipeline migrations (the task_usage_hourly schema
+-- and this pipeline). The legacy daily rollups keep running untouched.
+-- 2) Run `go run ./cmd/backfill_task_usage_hourly` to seed history.
+-- 3) As superuser, schedule the cron job:
+-- SELECT cron.schedule(
+-- 'rollup_task_usage_hourly',
+-- '*/5 * * * *',
+-- $$SELECT rollup_task_usage_hourly()$$
+-- );
+-- 4) Once `task_usage_hourly` is verified against the legacy daily
+-- rollups, apply the migration that drops the legacy pipelines.
diff --git a/server/migrations/103_drop_legacy_daily_rollups.down.sql b/server/migrations/103_drop_legacy_daily_rollups.down.sql
new file mode 100644
index 0000000000..702855a792
--- /dev/null
+++ b/server/migrations/103_drop_legacy_daily_rollups.down.sql
@@ -0,0 +1,7 @@
+-- Intentionally empty: there is no automatic way to reconstruct the
+-- legacy daily rollups from a `task_usage_hourly` snapshot AND restore
+-- their bucket_date semantics (one materialised in runtime tz per
+-- migration 082, the other in UTC per migration 084) without
+-- re-deciding which tz to use. If a deployment truly needs to roll
+-- back, the operator should restore from a pre-drop backup; this is
+-- not the place to encode that judgement call.
diff --git a/server/migrations/103_drop_legacy_daily_rollups.up.sql b/server/migrations/103_drop_legacy_daily_rollups.up.sql
new file mode 100644
index 0000000000..ad41579e14
--- /dev/null
+++ b/server/migrations/103_drop_legacy_daily_rollups.up.sql
@@ -0,0 +1,75 @@
+-- Drop the two legacy daily rollup pipelines now that `task_usage_hourly`
+-- is the only read path (see docs/timezone-architecture-rfc.md §6,
+-- Phase 3). Forward-only: there is no down migration that would put the
+-- data back, since by the time this ships:
+--
+-- * The hourly rollup has been live and writing every bucket since
+-- the hourly-pipeline migration.
+-- * No handler reads from `task_usage_daily` or
+-- `task_usage_dashboard_daily`. The runtime PATCH path that used
+-- to delete/insert into `task_usage_daily` on tz change has been
+-- replaced by a single UPDATE.
+-- * The `cmd/backfill_task_usage_daily` and
+-- `cmd/backfill_task_usage_dashboard_daily` commands have been
+-- removed. The remaining `cmd/backfill_task_usage_hourly` is the
+-- only seed path going forward.
+--
+-- The two pg_cron entries are unscheduled below before their functions
+-- are dropped, so a still-registered job cannot tick into a
+-- `function does not exist` error. The cron.unschedule calls are wrapped
+-- so the migration still succeeds on instances without pg_cron at all
+-- (same guard pattern as migration 076).
+
+-- ---------------------------------------------------------------------------
+-- Unschedule the legacy pg_cron jobs first (no-op when pg_cron is absent
+-- or the job was never registered).
+-- ---------------------------------------------------------------------------
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_cron') THEN
+ PERFORM cron.unschedule('rollup_task_usage_daily')
+ FROM cron.job WHERE jobname = 'rollup_task_usage_daily';
+ PERFORM cron.unschedule('rollup_task_usage_dashboard_daily')
+ FROM cron.job WHERE jobname = 'rollup_task_usage_dashboard_daily';
+ END IF;
+END
+$$;
+
+-- ---------------------------------------------------------------------------
+-- task_usage_dashboard_daily pipeline (migration 084).
+-- ---------------------------------------------------------------------------
+
+DROP TRIGGER IF EXISTS trg_issue_project_dirty_dashboard ON issue;
+DROP TRIGGER IF EXISTS trg_tu_dirty_dashboard ON task_usage;
+DROP TRIGGER IF EXISTS trg_issue_delete_dirty_dashboard ON issue;
+DROP TRIGGER IF EXISTS trg_atq_dirty_dashboard ON agent_task_queue;
+
+DROP FUNCTION IF EXISTS task_usage_dashboard_rollup_lag_seconds();
+DROP FUNCTION IF EXISTS rollup_task_usage_dashboard_daily();
+DROP FUNCTION IF EXISTS rollup_task_usage_dashboard_daily_window(TIMESTAMPTZ, TIMESTAMPTZ);
+DROP FUNCTION IF EXISTS enqueue_task_usage_dashboard_dirty_for_issue_project();
+DROP FUNCTION IF EXISTS enqueue_task_usage_dashboard_dirty_for_issue_delete();
+DROP FUNCTION IF EXISTS enqueue_task_usage_dashboard_dirty_for_tu();
+DROP FUNCTION IF EXISTS enqueue_task_usage_dashboard_dirty_for_atq();
+
+DROP TABLE IF EXISTS task_usage_dashboard_dirty;
+DROP TABLE IF EXISTS task_usage_dashboard_rollup_state;
+DROP TABLE IF EXISTS task_usage_dashboard_daily;
+
+-- ---------------------------------------------------------------------------
+-- task_usage_daily pipeline (migrations 073 / 077 / 082).
+-- ---------------------------------------------------------------------------
+
+DROP TRIGGER IF EXISTS trg_tu_dirty_rollup ON task_usage;
+DROP TRIGGER IF EXISTS trg_atq_dirty_rollup ON agent_task_queue;
+
+DROP FUNCTION IF EXISTS task_usage_rollup_lag_seconds();
+DROP FUNCTION IF EXISTS rollup_task_usage_daily();
+DROP FUNCTION IF EXISTS rollup_task_usage_daily_window(TIMESTAMPTZ, TIMESTAMPTZ);
+DROP FUNCTION IF EXISTS enqueue_task_usage_daily_dirty_for_tu();
+DROP FUNCTION IF EXISTS enqueue_task_usage_daily_dirty_for_atq();
+
+DROP TABLE IF EXISTS task_usage_daily_dirty;
+DROP TABLE IF EXISTS task_usage_rollup_state;
+DROP TABLE IF EXISTS task_usage_daily;
diff --git a/server/migrations/104_drop_runtime_timezone.down.sql b/server/migrations/104_drop_runtime_timezone.down.sql
new file mode 100644
index 0000000000..add807f177
--- /dev/null
+++ b/server/migrations/104_drop_runtime_timezone.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_runtime ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC';
diff --git a/server/migrations/104_drop_runtime_timezone.up.sql b/server/migrations/104_drop_runtime_timezone.up.sql
new file mode 100644
index 0000000000..5f232b90fe
--- /dev/null
+++ b/server/migrations/104_drop_runtime_timezone.up.sql
@@ -0,0 +1,6 @@
+-- Drop agent_runtime.timezone (Operational tz). The timezone architecture
+-- collapsed from 3 layers to 2: Scheduling (autopilot_trigger.timezone) and
+-- Viewing (user.timezone). The runtime's physical tz had exactly one
+-- consumer -- the hour-of-day heatmap -- which now renders in the viewer's
+-- tz like every other report. See docs/timezone-architecture-rfc.md.
+ALTER TABLE agent_runtime DROP COLUMN timezone;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 80446f52fc..fedfe39f72 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -59,9 +59,7 @@ 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"`
- Visibility string `json:"visibility"`
+ Visibility string `json:"visibility"`
}
type AgentSkill struct {
@@ -520,34 +518,13 @@ type TaskUsage struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
-type TaskUsageDaily struct {
- BucketDate pgtype.Date `json:"bucket_date"`
+type TaskUsageHourly struct {
+ BucketHour pgtype.Timestamptz `json:"bucket_hour"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
RuntimeID pgtype.UUID `json:"runtime_id"`
- Provider string `json:"provider"`
- Model string `json:"model"`
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadTokens int64 `json:"cache_read_tokens"`
- CacheWriteTokens int64 `json:"cache_write_tokens"`
- EventCount int64 `json:"event_count"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
-}
-
-type TaskUsageDailyDirty struct {
- BucketDate pgtype.Date `json:"bucket_date"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- Provider string `json:"provider"`
- Model string `json:"model"`
- EnqueuedAt pgtype.Timestamptz `json:"enqueued_at"`
-}
-
-type TaskUsageDashboardDaily struct {
- BucketDate pgtype.Date `json:"bucket_date"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
AgentID pgtype.UUID `json:"agent_id"`
ProjectID pgtype.UUID `json:"project_id"`
+ Provider string `json:"provider"`
Model string `json:"model"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
@@ -558,25 +535,18 @@ type TaskUsageDashboardDaily struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
-type TaskUsageDashboardDirty struct {
- BucketDate pgtype.Date `json:"bucket_date"`
+type TaskUsageHourlyDirty struct {
+ BucketHour pgtype.Timestamptz `json:"bucket_hour"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
AgentID pgtype.UUID `json:"agent_id"`
ProjectID pgtype.UUID `json:"project_id"`
+ Provider string `json:"provider"`
Model string `json:"model"`
EnqueuedAt pgtype.Timestamptz `json:"enqueued_at"`
}
-type TaskUsageDashboardRollupState struct {
- ID int16 `json:"id"`
- WatermarkAt pgtype.Timestamptz `json:"watermark_at"`
- LastRunStartedAt pgtype.Timestamptz `json:"last_run_started_at"`
- LastRunFinishedAt pgtype.Timestamptz `json:"last_run_finished_at"`
- LastRunRows int64 `json:"last_run_rows"`
- LastError pgtype.Text `json:"last_error"`
-}
-
-type TaskUsageRollupState struct {
+type TaskUsageHourlyRollupState struct {
ID int16 `json:"id"`
WatermarkAt pgtype.Timestamptz `json:"watermark_at"`
LastRunStartedAt pgtype.Timestamptz `json:"last_run_started_at"`
@@ -599,6 +569,8 @@ type User struct {
StarterContentState pgtype.Text `json:"starter_content_state"`
Language pgtype.Text `json:"language"`
ProfileDescription string `json:"profile_description"`
+ // User-preferred IANA timezone for report rendering (Viewing tz). NULL means "use the browser-detected tz at render time". Affects dashboards, charts, and any "today" label shown to this user. Does not affect data materialisation — all rollups remain in UTC.
+ Timezone pgtype.Text `json:"timezone"`
}
type VerificationCode struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index a9bacdb9bc..cbd79efb2a 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -149,36 +149,6 @@ 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',
@@ -239,7 +209,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, timezone, visibility 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, visibility FROM agent_runtime
WHERE workspace_id = $1
AND provider = $2
AND LOWER(daemon_id) = LOWER($3)
@@ -290,7 +260,6 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
); err != nil {
return nil, err
@@ -351,7 +320,7 @@ func (q *Queries) ForceOfflineRuntimesByIDs(ctx context.Context, runtimeIds []pg
}
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, timezone, visibility 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, visibility FROM agent_runtime
WHERE id = $1
`
@@ -373,14 +342,13 @@ func (q *Queries) GetAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRun
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
)
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, timezone, visibility 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, visibility FROM agent_runtime
WHERE id = $1 AND workspace_id = $2
`
@@ -407,59 +375,13 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
)
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, timezone, visibility 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, visibility FROM agent_runtime
WHERE workspace_id = $1
ORDER BY created_at ASC
`
@@ -488,7 +410,6 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
); err != nil {
return nil, err
@@ -502,7 +423,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, timezone, visibility 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, visibility FROM agent_runtime
WHERE workspace_id = $1 AND owner_id = $2
ORDER BY created_at ASC
`
@@ -536,7 +457,6 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
); err != nil {
return nil, err
@@ -576,23 +496,11 @@ func (q *Queries) ListArchivedAgentIDsByRuntime(ctx context.Context, runtimeID p
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, timezone, visibility
+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, visibility
`
// Used on the offline→online transition (and on first heartbeat after
@@ -616,7 +524,6 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (A
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
)
return i, err
@@ -866,48 +773,11 @@ 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, visibility
-`
-
-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,
- &i.Visibility,
- )
- return i, err
-}
-
const updateAgentRuntimeVisibility = `-- name: UpdateAgentRuntimeVisibility :one
UPDATE agent_runtime
SET visibility = $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, visibility
+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, visibility
`
type UpdateAgentRuntimeVisibilityParams struct {
@@ -937,7 +807,6 @@ func (q *Queries) UpdateAgentRuntimeVisibility(ctx context.Context, arg UpdateAg
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
)
return i, err
@@ -954,9 +823,8 @@ INSERT INTO agent_runtime (
device_info,
metadata,
owner_id,
- timezone,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
ON CONFLICT (workspace_id, daemon_id, provider)
DO UPDATE SET
name = EXCLUDED.name,
@@ -967,7 +835,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, timezone, visibility, (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, visibility, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeParams struct {
@@ -980,7 +848,6 @@ 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 {
@@ -998,7 +865,6 @@ 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"`
Visibility string `json:"visibility"`
Inserted bool `json:"inserted"`
}
@@ -1006,12 +872,6 @@ type UpsertAgentRuntimeRow struct {
// (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,
@@ -1023,7 +883,6 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
arg.DeviceInfo,
arg.Metadata,
arg.OwnerID,
- arg.Timezone,
)
var i UpsertAgentRuntimeRow
err := row.Scan(
@@ -1041,7 +900,6 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
- &i.Timezone,
&i.Visibility,
&i.Inserted,
)
diff --git a/server/pkg/db/generated/runtime_usage.sql.go b/server/pkg/db/generated/runtime_usage.sql.go
index 483a73cc39..4f0ac95d88 100644
--- a/server/pkg/db/generated/runtime_usage.sql.go
+++ b/server/pkg/db/generated/runtime_usage.sql.go
@@ -30,8 +30,8 @@ type GetRuntimeTaskHourlyActivityRow struct {
Count int32 `json:"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
+// Hour-of-day distribution for queue starts. Bucketed in the viewer's
+// 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)
@@ -92,8 +92,8 @@ type GetRuntimeUsageByHourRow struct {
// (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.
+// Hours are extracted in the viewer's tz via @tz so afternoon
+// work bucketed at UTC 06:00 lands in 14:00 for a UTC+8 viewer.
func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsageByHourParams) ([]GetRuntimeUsageByHourRow, error) {
rows, err := q.db.Query(ctx, getRuntimeUsageByHour, arg.RuntimeID, arg.Tz, arg.Since)
if err != nil {
@@ -124,19 +124,18 @@ func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsage
const listRuntimeUsage = `-- name: ListRuntimeUsage :many
SELECT
- DATE(tu.created_at AT TIME ZONE $2::text) AS date,
- 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
-FROM task_usage tu
-JOIN agent_task_queue atq ON atq.id = tu.task_id
-WHERE atq.runtime_id = $1
- 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
+ DATE(bucket_hour AT TIME ZONE $2::text) AS date,
+ provider,
+ model,
+ SUM(input_tokens)::bigint AS input_tokens,
+ SUM(output_tokens)::bigint AS output_tokens,
+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(cache_write_tokens)::bigint AS cache_write_tokens
+FROM task_usage_hourly
+WHERE runtime_id = $1
+ AND bucket_hour >= $3::timestamptz
+GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), provider, model
+ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, provider, model
`
type ListRuntimeUsageParams struct {
@@ -155,13 +154,14 @@ type ListRuntimeUsageRow struct {
CacheWriteTokens int64 `json:"cache_write_tokens"`
}
-// 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).
+// Reads from the UTC-bucketed `task_usage_hourly` rollup table,
+// aggregated to per-(date, provider, model) under the
+// caller-supplied @tz. Powers the trend chart on the runtime detail
+// page and the per-row cost cell on the runtimes list.
+//
+// @tz is required, even if the caller intends "UTC", so the bucket
+// cast is unambiguous — `bucket_hour` is UTC and the caller picks the
+// calendar boundary per request.
func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsageParams) ([]ListRuntimeUsageRow, error) {
rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Tz, arg.Since)
if err != nil {
@@ -258,82 +258,3 @@ func (q *Queries) ListRuntimeUsageByAgent(ctx context.Context, arg ListRuntimeUs
}
return items, nil
}
-
-const listRuntimeUsageDaily = `-- name: ListRuntimeUsageDaily :many
-SELECT
- bucket_date AS date,
- provider,
- model,
- SUM(input_tokens)::bigint AS input_tokens,
- SUM(output_tokens)::bigint AS output_tokens,
- SUM(cache_read_tokens)::bigint AS cache_read_tokens,
- SUM(cache_write_tokens)::bigint AS cache_write_tokens
-FROM task_usage_daily
-WHERE runtime_id = $1
- 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"`
-}
-
-type ListRuntimeUsageDailyRow struct {
- Date pgtype.Date `json:"date"`
- Provider string `json:"provider"`
- Model string `json:"model"`
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadTokens int64 `json:"cache_read_tokens"`
- CacheWriteTokens int64 `json:"cache_write_tokens"`
-}
-
-// Reads from the `task_usage_daily` rollup table maintained by
-// rollup_task_usage_daily() (scheduled every 5 min via pg_cron, or any
-// equivalent external scheduler that calls the function). Same shape as
-// ListRuntimeUsage above. Today's bucket may lag the raw table by up to
-// ~10 min (5 min cron period + 5 min rollup safety lag); intentional.
-//
-// Only used when USAGE_DAILY_ROLLUP_ENABLED is true AND deploy has
-// 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.Tz, arg.Since)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ListRuntimeUsageDailyRow{}
- for rows.Next() {
- var i ListRuntimeUsageDailyRow
- if err := rows.Scan(
- &i.Date,
- &i.Provider,
- &i.Model,
- &i.InputTokens,
- &i.OutputTokens,
- &i.CacheReadTokens,
- &i.CacheWriteTokens,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.go
index 0a5b508ff3..13717a5fd3 100644
--- a/server/pkg/db/generated/task_usage.sql.go
+++ b/server/pkg/db/generated/task_usage.sql.go
@@ -81,131 +81,6 @@ func (q *Queries) GetTaskUsage(ctx context.Context, taskID pgtype.UUID) ([]TaskU
return items, nil
}
-const getWorkspaceUsageByDay = `-- name: GetWorkspaceUsageByDay :many
-SELECT
- DATE(tu.created_at) AS date,
- tu.model,
- SUM(tu.input_tokens)::bigint AS total_input_tokens,
- SUM(tu.output_tokens)::bigint AS total_output_tokens,
- SUM(tu.cache_read_tokens)::bigint AS total_cache_read_tokens,
- SUM(tu.cache_write_tokens)::bigint AS total_cache_write_tokens,
- COUNT(DISTINCT tu.task_id)::int AS task_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
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
-GROUP BY DATE(tu.created_at), tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.model
-`
-
-type GetWorkspaceUsageByDayParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Since pgtype.Timestamptz `json:"since"`
-}
-
-type GetWorkspaceUsageByDayRow struct {
- Date pgtype.Date `json:"date"`
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- TotalOutputTokens int64 `json:"total_output_tokens"`
- TotalCacheReadTokens int64 `json:"total_cache_read_tokens"`
- TotalCacheWriteTokens int64 `json:"total_cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
-}
-
-// Bucket by tu.created_at (usage report time, ~= task completion time), not
-// atq.created_at (task enqueue time), so tasks that queue one day and execute
-// the next are attributed to the day tokens were actually produced. The since
-// cutoff is truncated to start-of-day so `days=N` yields full calendar days.
-func (q *Queries) GetWorkspaceUsageByDay(ctx context.Context, arg GetWorkspaceUsageByDayParams) ([]GetWorkspaceUsageByDayRow, error) {
- rows, err := q.db.Query(ctx, getWorkspaceUsageByDay, arg.WorkspaceID, arg.Since)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []GetWorkspaceUsageByDayRow{}
- for rows.Next() {
- var i GetWorkspaceUsageByDayRow
- if err := rows.Scan(
- &i.Date,
- &i.Model,
- &i.TotalInputTokens,
- &i.TotalOutputTokens,
- &i.TotalCacheReadTokens,
- &i.TotalCacheWriteTokens,
- &i.TaskCount,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
-const getWorkspaceUsageSummary = `-- name: GetWorkspaceUsageSummary :many
-SELECT
- tu.model,
- SUM(tu.input_tokens)::bigint AS total_input_tokens,
- SUM(tu.output_tokens)::bigint AS total_output_tokens,
- SUM(tu.cache_read_tokens)::bigint AS total_cache_read_tokens,
- SUM(tu.cache_write_tokens)::bigint AS total_cache_write_tokens,
- COUNT(DISTINCT tu.task_id)::int AS task_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
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
-GROUP BY tu.model
-ORDER BY (SUM(tu.input_tokens) + SUM(tu.output_tokens)) DESC
-`
-
-type GetWorkspaceUsageSummaryParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Since pgtype.Timestamptz `json:"since"`
-}
-
-type GetWorkspaceUsageSummaryRow struct {
- Model string `json:"model"`
- TotalInputTokens int64 `json:"total_input_tokens"`
- TotalOutputTokens int64 `json:"total_output_tokens"`
- TotalCacheReadTokens int64 `json:"total_cache_read_tokens"`
- TotalCacheWriteTokens int64 `json:"total_cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
-}
-
-// Filter by tu.created_at (usage report time), aligned to start-of-day, so
-// `days=N` is interpreted as N full calendar days like the other usage queries.
-func (q *Queries) GetWorkspaceUsageSummary(ctx context.Context, arg GetWorkspaceUsageSummaryParams) ([]GetWorkspaceUsageSummaryRow, error) {
- rows, err := q.db.Query(ctx, getWorkspaceUsageSummary, arg.WorkspaceID, arg.Since)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []GetWorkspaceUsageSummaryRow{}
- for rows.Next() {
- var i GetWorkspaceUsageSummaryRow
- if err := rows.Scan(
- &i.Model,
- &i.TotalInputTokens,
- &i.TotalOutputTokens,
- &i.TotalCacheReadTokens,
- &i.TotalCacheWriteTokens,
- &i.TaskCount,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const listDashboardAgentRunTime = `-- name: ListDashboardAgentRunTime :many
SELECT
atq.agent_id,
@@ -222,7 +97,7 @@ WHERE a.workspace_id = $1
AND atq.status IN ('completed', 'failed')
AND atq.started_at IS NOT NULL
AND atq.completed_at IS NOT NULL
- AND atq.completed_at >= DATE_TRUNC('day', $2::timestamptz)
+ AND atq.completed_at >= $2::timestamptz
AND ($3::uuid IS NULL OR i.project_id = $3)
GROUP BY atq.agent_id
ORDER BY total_seconds DESC
@@ -246,6 +121,10 @@ type ListDashboardAgentRunTimeRow struct {
// with both started_at and completed_at populated — queued/running tasks have
// no finite duration. Anchored on completed_at so the window matches the
// token cost window (which is anchored on tu.created_at, ~= completion time).
+//
+// No date bucketing, so no @tz — but @since is the viewer's local
+// start-of-day-(N) so the "last N days" window lines up with the per-agent
+// cost card; passed straight through without re-truncation.
func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboardAgentRunTimeParams) ([]ListDashboardAgentRunTimeRow, error) {
rows, err := q.db.Query(ctx, listDashboardAgentRunTime, arg.WorkspaceID, arg.Since, arg.ProjectID)
if err != nil {
@@ -273,7 +152,7 @@ func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboa
const listDashboardRunTimeDaily = `-- name: ListDashboardRunTimeDaily :many
SELECT
- DATE(atq.completed_at) AS date,
+ DATE(atq.completed_at AT TIME ZONE $2::text) AS date,
COALESCE(
SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,
0
@@ -287,14 +166,15 @@ WHERE a.workspace_id = $1
AND atq.status IN ('completed', 'failed')
AND atq.started_at IS NOT NULL
AND atq.completed_at IS NOT NULL
- AND atq.completed_at >= DATE_TRUNC('day', $2::timestamptz)
- AND ($3::uuid IS NULL OR i.project_id = $3)
-GROUP BY DATE(atq.completed_at)
-ORDER BY DATE(atq.completed_at) DESC
+ AND atq.completed_at >= $3::timestamptz
+ AND ($4::uuid IS NULL OR i.project_id = $4)
+GROUP BY DATE(atq.completed_at AT TIME ZONE $2::text)
+ORDER BY DATE(atq.completed_at AT TIME ZONE $2::text) DESC
`
type ListDashboardRunTimeDailyParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Tz string `json:"tz"`
Since pgtype.Timestamptz `json:"since"`
ProjectID pgtype.UUID `json:"project_id"`
}
@@ -309,12 +189,22 @@ type ListDashboardRunTimeDailyRow struct {
// Daily per-date run time + task counts for the workspace, optionally
// scoped to a single project. Powers the workspace dashboard's "Time"
// and "Tasks" metrics on the same toggle as Tokens / Cost. Bucketed by
-// completed_at (terminal time) — same anchor as ListDashboardAgentRunTime
-// so the day boundaries line up with the per-agent run-time card. Only
-// terminal tasks (completed or failed) with both started_at and
-// completed_at populated contribute.
+// completed_at (terminal time) sliced into calendar days under the
+// caller-supplied @tz — same Viewing-tz treatment as ListDashboardUsageDaily
+// so the Time / Tasks tabs cut their day boundary identically to the
+// Cost / Tokens tabs (a viewer east of UTC would otherwise see the four
+// tabs disagree on a "1d" window). Only terminal tasks (completed or
+// failed) with both started_at and completed_at populated contribute.
+//
+// @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)
+// — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.
func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboardRunTimeDailyParams) ([]ListDashboardRunTimeDailyRow, error) {
- rows, err := q.db.Query(ctx, listDashboardRunTimeDaily, arg.WorkspaceID, arg.Since, arg.ProjectID)
+ rows, err := q.db.Query(ctx, listDashboardRunTimeDaily,
+ arg.WorkspaceID,
+ arg.Tz,
+ arg.Since,
+ arg.ProjectID,
+ )
if err != nil {
return nil, err
}
@@ -339,74 +229,6 @@ func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboa
}
const listDashboardUsageByAgent = `-- name: ListDashboardUsageByAgent :many
-SELECT
- atq.agent_id,
- 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(DISTINCT tu.task_id)::int AS task_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
-LEFT JOIN issue i ON i.id = atq.issue_id
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
- AND ($3::uuid IS NULL OR i.project_id = $3)
-GROUP BY atq.agent_id, tu.model
-ORDER BY atq.agent_id, tu.model
-`
-
-type ListDashboardUsageByAgentParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Since pgtype.Timestamptz `json:"since"`
- ProjectID pgtype.UUID `json:"project_id"`
-}
-
-type ListDashboardUsageByAgentRow struct {
- AgentID pgtype.UUID `json:"agent_id"`
- Model string `json:"model"`
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadTokens int64 `json:"cache_read_tokens"`
- CacheWriteTokens int64 `json:"cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
-}
-
-// Per-(agent, model) token aggregates for the workspace, optionally scoped
-// to a single project. Model dimension is preserved so the client can
-// compute cost from its per-model pricing table; the client folds rows by
-// agent for the "by agent" list on the dashboard.
-func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboardUsageByAgentParams) ([]ListDashboardUsageByAgentRow, error) {
- rows, err := q.db.Query(ctx, listDashboardUsageByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ListDashboardUsageByAgentRow{}
- for rows.Next() {
- var i ListDashboardUsageByAgentRow
- if err := rows.Scan(
- &i.AgentID,
- &i.Model,
- &i.InputTokens,
- &i.OutputTokens,
- &i.CacheReadTokens,
- &i.CacheWriteTokens,
- &i.TaskCount,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
-const listDashboardUsageByAgentRollup = `-- name: ListDashboardUsageByAgentRollup :many
SELECT
agent_id,
model,
@@ -415,21 +237,21 @@ SELECT
SUM(cache_read_tokens)::bigint AS cache_read_tokens,
SUM(cache_write_tokens)::bigint AS cache_write_tokens,
SUM(task_count)::int AS task_count
-FROM task_usage_dashboard_daily
+FROM task_usage_hourly
WHERE workspace_id = $1
- AND bucket_date >= DATE_TRUNC('day', $2::timestamptz)::date
+ AND bucket_hour >= $2::timestamptz
AND ($3::uuid IS NULL OR project_id = $3)
GROUP BY agent_id, model
ORDER BY agent_id, model
`
-type ListDashboardUsageByAgentRollupParams struct {
+type ListDashboardUsageByAgentParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
Since pgtype.Timestamptz `json:"since"`
ProjectID pgtype.UUID `json:"project_id"`
}
-type ListDashboardUsageByAgentRollupRow struct {
+type ListDashboardUsageByAgentRow struct {
AgentID pgtype.UUID `json:"agent_id"`
Model string `json:"model"`
InputTokens int64 `json:"input_tokens"`
@@ -439,21 +261,27 @@ type ListDashboardUsageByAgentRollupRow struct {
TaskCount int32 `json:"task_count"`
}
-// Per-(agent, model) token rollup from `task_usage_dashboard_daily`.
-// task_count here is the SUM of per-bucket distinct counts; one task that
-// spans multiple days lands in multiple buckets, so this can over-count
-// by date. The frontend prefers `ListDashboardAgentRunTime`'s per-agent
-// distinct figure for the user-facing "tasks" column, so this value is
-// informational only.
-func (q *Queries) ListDashboardUsageByAgentRollup(ctx context.Context, arg ListDashboardUsageByAgentRollupParams) ([]ListDashboardUsageByAgentRollupRow, error) {
- rows, err := q.db.Query(ctx, listDashboardUsageByAgentRollup, arg.WorkspaceID, arg.Since, arg.ProjectID)
+// Per-(agent, model) token aggregates from `task_usage_hourly`. No
+// date grouping in the result, so this query takes no `@tz` — the
+// @since cutoff is a raw timestamptz the Go layer has already computed
+// in the viewer's tz. Model dimension is preserved so the client can
+// compute cost from its per-model pricing table; the client folds rows
+// by agent for the "by agent" list on the dashboard.
+//
+// task_count is summed across hourly buckets — one task that spans
+// multiple hours lands in multiple buckets, so this over-counts by
+// hour the same way the daily version over-counted by day. The
+// frontend prefers `ListDashboardAgentRunTime` for the user-facing
+// "tasks" column, so this stays informational only.
+func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboardUsageByAgentParams) ([]ListDashboardUsageByAgentRow, error) {
+ rows, err := q.db.Query(ctx, listDashboardUsageByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []ListDashboardUsageByAgentRollupRow{}
+ items := []ListDashboardUsageByAgentRow{}
for rows.Next() {
- var i ListDashboardUsageByAgentRollupRow
+ var i ListDashboardUsageByAgentRow
if err := rows.Scan(
&i.AgentID,
&i.Model,
@@ -475,98 +303,29 @@ func (q *Queries) ListDashboardUsageByAgentRollup(ctx context.Context, arg ListD
const listDashboardUsageDaily = `-- name: ListDashboardUsageDaily :many
SELECT
- DATE(tu.created_at) AS date,
- 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(DISTINCT tu.task_id)::int AS task_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
-LEFT JOIN issue i ON i.id = atq.issue_id
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
- AND ($3::uuid IS NULL OR i.project_id = $3)
-GROUP BY DATE(tu.created_at), tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.model
-`
-
-type ListDashboardUsageDailyParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Since pgtype.Timestamptz `json:"since"`
- ProjectID pgtype.UUID `json:"project_id"`
-}
-
-type ListDashboardUsageDailyRow struct {
- Date pgtype.Date `json:"date"`
- Model string `json:"model"`
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadTokens int64 `json:"cache_read_tokens"`
- CacheWriteTokens int64 `json:"cache_write_tokens"`
- TaskCount int32 `json:"task_count"`
-}
-
-// Daily per-(date, model) token aggregates for the workspace, optionally
-// scoped to a single project via sqlc.narg('project_id'). Bucketed by
-// tu.created_at (token-production time) to match GetWorkspaceUsageByDay,
-// so a task that queues one day and finishes the next is attributed to
-// the day the tokens actually landed. Powers the workspace dashboard's
-// daily cost chart.
-func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardUsageDailyParams) ([]ListDashboardUsageDailyRow, error) {
- rows, err := q.db.Query(ctx, listDashboardUsageDaily, arg.WorkspaceID, arg.Since, arg.ProjectID)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ListDashboardUsageDailyRow{}
- for rows.Next() {
- var i ListDashboardUsageDailyRow
- if err := rows.Scan(
- &i.Date,
- &i.Model,
- &i.InputTokens,
- &i.OutputTokens,
- &i.CacheReadTokens,
- &i.CacheWriteTokens,
- &i.TaskCount,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
-const listDashboardUsageDailyRollup = `-- name: ListDashboardUsageDailyRollup :many
-SELECT
- bucket_date AS date,
+ DATE(bucket_hour AT TIME ZONE $2::text) AS date,
model,
SUM(input_tokens)::bigint AS input_tokens,
SUM(output_tokens)::bigint AS output_tokens,
SUM(cache_read_tokens)::bigint AS cache_read_tokens,
SUM(cache_write_tokens)::bigint AS cache_write_tokens,
SUM(task_count)::int AS task_count
-FROM task_usage_dashboard_daily
+FROM task_usage_hourly
WHERE workspace_id = $1
- AND bucket_date >= DATE_TRUNC('day', $2::timestamptz)::date
- AND ($3::uuid IS NULL OR project_id = $3)
-GROUP BY bucket_date, model
-ORDER BY bucket_date DESC, model
+ AND bucket_hour >= $3::timestamptz
+ AND ($4::uuid IS NULL OR project_id = $4)
+GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), model
+ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, model
`
-type ListDashboardUsageDailyRollupParams struct {
+type ListDashboardUsageDailyParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Tz string `json:"tz"`
Since pgtype.Timestamptz `json:"since"`
ProjectID pgtype.UUID `json:"project_id"`
}
-type ListDashboardUsageDailyRollupRow struct {
+type ListDashboardUsageDailyRow struct {
Date pgtype.Date `json:"date"`
Model string `json:"model"`
InputTokens int64 `json:"input_tokens"`
@@ -576,20 +335,34 @@ type ListDashboardUsageDailyRollupRow struct {
TaskCount int32 `json:"task_count"`
}
-// Daily token rollup, served from `task_usage_dashboard_daily` (migration
-// 084). Same wire shape as ListDashboardUsageDaily so the handler can
-// swap them on the `UseDailyRollupForDashboard` flag with no other
-// changes. The rollup is up to ~10 min stale (5 min cron + 5 min lag),
-// which is fine for a dashboard read path.
-func (q *Queries) ListDashboardUsageDailyRollup(ctx context.Context, arg ListDashboardUsageDailyRollupParams) ([]ListDashboardUsageDailyRollupRow, error) {
- rows, err := q.db.Query(ctx, listDashboardUsageDailyRollup, arg.WorkspaceID, arg.Since, arg.ProjectID)
+// Daily per-(date, model) token aggregates for the workspace, served
+// from the UTC-bucketed `task_usage_hourly` table and
+// sliced to calendar days under the caller-supplied @tz. Optionally
+// scoped to a single project via sqlc.narg('project_id'). Powers the
+// workspace dashboard's daily cost chart.
+// The viewer's tz is applied here at query time, so a viewer in
+// Asia/Shanghai gets their "today" cut at +08 and one in
+// America/Los_Angeles gets theirs at -08 against the same UTC rows.
+//
+// @since is already the viewer's local start-of-day-(N) as a UTC
+// instant (computed by parseSinceParamInTZ). It must NOT be re-truncated
+// with DATE_TRUNC here — DATE_TRUNC operates in the session tz and would
+// snap the cutoff back to UTC midnight, dragging in an extra partial
+// local day for any non-UTC viewer.
+func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardUsageDailyParams) ([]ListDashboardUsageDailyRow, error) {
+ rows, err := q.db.Query(ctx, listDashboardUsageDaily,
+ arg.WorkspaceID,
+ arg.Tz,
+ arg.Since,
+ arg.ProjectID,
+ )
if err != nil {
return nil, err
}
defer rows.Close()
- items := []ListDashboardUsageDailyRollupRow{}
+ items := []ListDashboardUsageDailyRow{}
for rows.Next() {
- var i ListDashboardUsageDailyRollupRow
+ var i ListDashboardUsageDailyRow
if err := rows.Scan(
&i.Date,
&i.Model,
@@ -631,8 +404,8 @@ type UpsertTaskUsageParams struct {
CacheWriteTokens int64 `json:"cache_write_tokens"`
}
-// Bumps `updated_at` on INSERT and on conflict so the daily-rollup worker
-// (migration 073) detects the row as dirty and re-aggregates its bucket.
+// Bumps `updated_at` on INSERT and on conflict so the hourly-rollup worker
+// detects the row as dirty and re-aggregates its bucket.
// Without the conflict-side bump, a correction to historical token counts
// would never propagate to the rollup.
func (q *Queries) UpsertTaskUsage(ctx context.Context, arg UpsertTaskUsageParams) error {
diff --git a/server/pkg/db/generated/user.sql.go b/server/pkg/db/generated/user.sql.go
index e73937b2a5..1b1ad331c5 100644
--- a/server/pkg/db/generated/user.sql.go
+++ b/server/pkg/db/generated/user.sql.go
@@ -14,7 +14,7 @@ import (
const createUser = `-- name: CreateUser :one
INSERT INTO "user" (name, email, avatar_url)
VALUES ($1, $2, $3)
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
type CreateUserParams struct {
@@ -40,12 +40,13 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
const getUser = `-- name: GetUser :one
-SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description FROM "user"
+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone FROM "user"
WHERE id = $1
`
@@ -66,12 +67,13 @@ func (q *Queries) GetUser(ctx context.Context, id pgtype.UUID) (User, error) {
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
const getUserByEmail = `-- name: GetUserByEmail :one
-SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description FROM "user"
+SELECT id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone FROM "user"
WHERE email = $1
`
@@ -92,6 +94,7 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
@@ -102,7 +105,7 @@ UPDATE "user" SET
cloud_waitlist_reason = $3,
updated_at = now()
WHERE id = $1
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
type JoinCloudWaitlistParams struct {
@@ -131,6 +134,7 @@ func (q *Queries) JoinCloudWaitlist(ctx context.Context, arg JoinCloudWaitlistPa
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
@@ -140,7 +144,7 @@ UPDATE "user" SET
onboarded_at = COALESCE(onboarded_at, now()),
updated_at = now()
WHERE id = $1
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
func (q *Queries) MarkUserOnboarded(ctx context.Context, id pgtype.UUID) (User, error) {
@@ -160,6 +164,7 @@ func (q *Queries) MarkUserOnboarded(ctx context.Context, id pgtype.UUID) (User,
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
@@ -169,7 +174,7 @@ UPDATE "user" SET
onboarding_questionnaire = COALESCE($1, onboarding_questionnaire),
updated_at = now()
WHERE id = $2
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
type PatchUserOnboardingParams struct {
@@ -194,6 +199,7 @@ func (q *Queries) PatchUserOnboarding(ctx context.Context, arg PatchUserOnboardi
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
@@ -203,7 +209,7 @@ UPDATE "user" SET
starter_content_state = $2,
updated_at = now()
WHERE id = $1
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
type SetStarterContentStateParams struct {
@@ -233,6 +239,7 @@ func (q *Queries) SetStarterContentState(ctx context.Context, arg SetStarterCont
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
@@ -243,9 +250,14 @@ UPDATE "user" SET
avatar_url = COALESCE($3, avatar_url),
language = COALESCE($4, language),
profile_description = COALESCE($5, profile_description),
+ timezone = CASE
+ WHEN $6::text IS NULL THEN timezone
+ WHEN $6::text = '' THEN NULL
+ ELSE $6::text
+ END,
updated_at = now()
WHERE id = $1
-RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description
+RETURNING id, name, email, avatar_url, created_at, updated_at, onboarded_at, onboarding_questionnaire, cloud_waitlist_email, cloud_waitlist_reason, starter_content_state, language, profile_description, timezone
`
type UpdateUserParams struct {
@@ -254,8 +266,21 @@ type UpdateUserParams struct {
AvatarUrl pgtype.Text `json:"avatar_url"`
Language pgtype.Text `json:"language"`
ProfileDescription pgtype.Text `json:"profile_description"`
+ Timezone pgtype.Text `json:"timezone"`
}
+// Patches the user-controlled profile fields. Each parameter follows
+// COALESCE-on-NULL semantics so the handler can omit any field it
+// doesn't intend to write.
+//
+// `timezone` (Viewing-tz preference) participates in
+// the same shape but uses sqlc.narg + a sentinel-string convention:
+// the handler passes the empty string "" to mean "clear back to NULL"
+// (browser-detected fallback), an IANA name like "Asia/Shanghai" to
+// pin a value, and `sqlc.narg('timezone') IS NULL` (no value at all)
+// to leave the existing column untouched. Folding it into UpdateUser
+// rather than carrying a dedicated UpdateUserTimezone keeps the
+// profile-patch shape uniform between Preferences fields.
func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, error) {
row := q.db.QueryRow(ctx, updateUser,
arg.ID,
@@ -263,6 +288,7 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, e
arg.AvatarUrl,
arg.Language,
arg.ProfileDescription,
+ arg.Timezone,
)
var i User
err := row.Scan(
@@ -279,6 +305,7 @@ func (q *Queries) UpdateUser(ctx context.Context, arg UpdateUserParams) (User, e
&i.StarterContentState,
&i.Language,
&i.ProfileDescription,
+ &i.Timezone,
)
return i, err
}
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index a174e16685..8096706779 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -15,12 +15,6 @@ 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,
@@ -31,9 +25,8 @@ INSERT INTO agent_runtime (
device_info,
metadata,
owner_id,
- timezone,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, @timezone, now())
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
ON CONFLICT (workspace_id, daemon_id, provider)
DO UPDATE SET
name = EXCLUDED.name,
@@ -46,19 +39,6 @@ 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: UpdateAgentRuntimeVisibility :one
-- Toggles a runtime between 'private' (only owner can bind agents) and
-- 'public' (any workspace member can). Default for new rows is 'private'
@@ -69,53 +49,6 @@ SET visibility = @visibility, 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
diff --git a/server/pkg/db/queries/runtime_usage.sql b/server/pkg/db/queries/runtime_usage.sql
index 95437602d8..70d81c37cc 100644
--- a/server/pkg/db/queries/runtime_usage.sql
+++ b/server/pkg/db/queries/runtime_usage.sql
@@ -1,63 +1,29 @@
-- name: ListRuntimeUsage :many
--- 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 AT TIME ZONE @tz::text) AS date,
- 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
-FROM task_usage tu
-JOIN agent_task_queue atq ON atq.id = tu.task_id
-WHERE atq.runtime_id = $1
- 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
--- rollup_task_usage_daily() (scheduled every 5 min via pg_cron, or any
--- equivalent external scheduler that calls the function). Same shape as
--- ListRuntimeUsage above. Today's bucket may lag the raw table by up to
--- ~10 min (5 min cron period + 5 min rollup safety lag); intentional.
---
--- Only used when USAGE_DAILY_ROLLUP_ENABLED is true AND deploy has
--- 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.
+-- Reads from the UTC-bucketed `task_usage_hourly` rollup table,
+-- aggregated to per-(date, provider, model) under the
+-- caller-supplied @tz. Powers the trend chart on the runtime detail
+-- page and the per-row cost cell on the runtimes list.
--
--- 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.
+-- @tz is required, even if the caller intends "UTC", so the bucket
+-- cast is unambiguous — `bucket_hour` is UTC and the caller picks the
+-- calendar boundary per request.
SELECT
- bucket_date AS date,
+ DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) AS date,
provider,
model,
- SUM(input_tokens)::bigint AS input_tokens,
- SUM(output_tokens)::bigint AS output_tokens,
- SUM(cache_read_tokens)::bigint AS cache_read_tokens,
- SUM(cache_write_tokens)::bigint AS cache_write_tokens
-FROM task_usage_daily
+ SUM(input_tokens)::bigint AS input_tokens,
+ SUM(output_tokens)::bigint AS output_tokens,
+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(cache_write_tokens)::bigint AS cache_write_tokens
+FROM task_usage_hourly
WHERE runtime_id = $1
- 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;
+ AND bucket_hour >= sqlc.arg('since')::timestamptz
+GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), provider, model
+ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, provider, model;
-- name: GetRuntimeTaskHourlyActivity :many
--- Hour-of-day distribution for queue starts. Bucketed in the runtime's
--- local tz so "this runtime is busy in the afternoon" actually means
+-- Hour-of-day distribution for queue starts. Bucketed in the viewer's
+-- 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
@@ -98,8 +64,8 @@ ORDER BY atq.agent_id, tu.model;
-- (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.
+-- Hours are extracted in the viewer's tz via @tz so afternoon
+-- work bucketed at UTC 06:00 lands in 14:00 for a UTC+8 viewer.
SELECT
EXTRACT(HOUR FROM tu.created_at AT TIME ZONE @tz::text)::int AS hour,
tu.model,
diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sql
index c63207ad8d..43c6d1e6e7 100644
--- a/server/pkg/db/queries/task_usage.sql
+++ b/server/pkg/db/queries/task_usage.sql
@@ -1,6 +1,6 @@
-- name: UpsertTaskUsage :exec
--- Bumps `updated_at` on INSERT and on conflict so the daily-rollup worker
--- (migration 073) detects the row as dirty and re-aggregates its bucket.
+-- Bumps `updated_at` on INSERT and on conflict so the hourly-rollup worker
+-- detects the row as dirty and re-aggregates its bucket.
-- Without the conflict-side bump, a correction to historical token counts
-- would never propagate to the rollup.
INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, updated_at)
@@ -18,45 +18,6 @@ SELECT * FROM task_usage
WHERE task_id = $1
ORDER BY model;
--- name: GetWorkspaceUsageByDay :many
--- Bucket by tu.created_at (usage report time, ~= task completion time), not
--- atq.created_at (task enqueue time), so tasks that queue one day and execute
--- the next are attributed to the day tokens were actually produced. The since
--- cutoff is truncated to start-of-day so `days=N` yields full calendar days.
-SELECT
- DATE(tu.created_at) AS date,
- tu.model,
- SUM(tu.input_tokens)::bigint AS total_input_tokens,
- SUM(tu.output_tokens)::bigint AS total_output_tokens,
- SUM(tu.cache_read_tokens)::bigint AS total_cache_read_tokens,
- SUM(tu.cache_write_tokens)::bigint AS total_cache_write_tokens,
- COUNT(DISTINCT tu.task_id)::int AS task_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
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
-GROUP BY DATE(tu.created_at), tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.model;
-
--- name: GetWorkspaceUsageSummary :many
--- Filter by tu.created_at (usage report time), aligned to start-of-day, so
--- `days=N` is interpreted as N full calendar days like the other usage queries.
-SELECT
- tu.model,
- SUM(tu.input_tokens)::bigint AS total_input_tokens,
- SUM(tu.output_tokens)::bigint AS total_output_tokens,
- SUM(tu.cache_read_tokens)::bigint AS total_cache_read_tokens,
- SUM(tu.cache_write_tokens)::bigint AS total_cache_write_tokens,
- COUNT(DISTINCT tu.task_id)::int AS task_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
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
-GROUP BY tu.model
-ORDER BY (SUM(tu.input_tokens) + SUM(tu.output_tokens)) DESC;
-
-- name: GetIssueUsageSummary :one
SELECT
COALESCE(SUM(tu.input_tokens), 0)::bigint AS total_input_tokens,
@@ -69,81 +30,48 @@ JOIN agent_task_queue atq ON atq.id = tu.task_id
WHERE atq.issue_id = $1;
-- name: ListDashboardUsageDaily :many
--- Daily per-(date, model) token aggregates for the workspace, optionally
--- scoped to a single project via sqlc.narg('project_id'). Bucketed by
--- tu.created_at (token-production time) to match GetWorkspaceUsageByDay,
--- so a task that queues one day and finishes the next is attributed to
--- the day the tokens actually landed. Powers the workspace dashboard's
--- daily cost chart.
+-- Daily per-(date, model) token aggregates for the workspace, served
+-- from the UTC-bucketed `task_usage_hourly` table and
+-- sliced to calendar days under the caller-supplied @tz. Optionally
+-- scoped to a single project via sqlc.narg('project_id'). Powers the
+-- workspace dashboard's daily cost chart.
+-- The viewer's tz is applied here at query time, so a viewer in
+-- Asia/Shanghai gets their "today" cut at +08 and one in
+-- America/Los_Angeles gets theirs at -08 against the same UTC rows.
+--
+-- @since is already the viewer's local start-of-day-(N) as a UTC
+-- instant (computed by parseSinceParamInTZ). It must NOT be re-truncated
+-- with DATE_TRUNC here — DATE_TRUNC operates in the session tz and would
+-- snap the cutoff back to UTC midnight, dragging in an extra partial
+-- local day for any non-UTC viewer.
SELECT
- DATE(tu.created_at) AS date,
- 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(DISTINCT tu.task_id)::int AS task_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
-LEFT JOIN issue i ON i.id = atq.issue_id
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
- AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-GROUP BY DATE(tu.created_at), tu.model
-ORDER BY DATE(tu.created_at) DESC, tu.model;
-
--- name: ListDashboardUsageByAgent :many
--- Per-(agent, model) token aggregates for the workspace, optionally scoped
--- to a single project. Model dimension is preserved so the client can
--- compute cost from its per-model pricing table; the client folds rows by
--- agent for the "by agent" list on the dashboard.
-SELECT
- atq.agent_id,
- 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(DISTINCT tu.task_id)::int AS task_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
-LEFT JOIN issue i ON i.id = atq.issue_id
-WHERE a.workspace_id = $1
- AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
- AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-GROUP BY atq.agent_id, tu.model
-ORDER BY atq.agent_id, tu.model;
-
--- name: ListDashboardUsageDailyRollup :many
--- Daily token rollup, served from `task_usage_dashboard_daily` (migration
--- 084). Same wire shape as ListDashboardUsageDaily so the handler can
--- swap them on the `UseDailyRollupForDashboard` flag with no other
--- changes. The rollup is up to ~10 min stale (5 min cron + 5 min lag),
--- which is fine for a dashboard read path.
-SELECT
- bucket_date AS date,
+ DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) AS date,
model,
SUM(input_tokens)::bigint AS input_tokens,
SUM(output_tokens)::bigint AS output_tokens,
SUM(cache_read_tokens)::bigint AS cache_read_tokens,
SUM(cache_write_tokens)::bigint AS cache_write_tokens,
SUM(task_count)::int AS task_count
-FROM task_usage_dashboard_daily
+FROM task_usage_hourly
WHERE workspace_id = $1
- AND bucket_date >= DATE_TRUNC('day', @since::timestamptz)::date
+ AND bucket_hour >= sqlc.arg('since')::timestamptz
AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))
-GROUP BY bucket_date, model
-ORDER BY bucket_date DESC, model;
+GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), model
+ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, model;
--- name: ListDashboardUsageByAgentRollup :many
--- Per-(agent, model) token rollup from `task_usage_dashboard_daily`.
--- task_count here is the SUM of per-bucket distinct counts; one task that
--- spans multiple days lands in multiple buckets, so this can over-count
--- by date. The frontend prefers `ListDashboardAgentRunTime`'s per-agent
--- distinct figure for the user-facing "tasks" column, so this value is
--- informational only.
+-- name: ListDashboardUsageByAgent :many
+-- Per-(agent, model) token aggregates from `task_usage_hourly`. No
+-- date grouping in the result, so this query takes no `@tz` — the
+-- @since cutoff is a raw timestamptz the Go layer has already computed
+-- in the viewer's tz. Model dimension is preserved so the client can
+-- compute cost from its per-model pricing table; the client folds rows
+-- by agent for the "by agent" list on the dashboard.
+--
+-- task_count is summed across hourly buckets — one task that spans
+-- multiple hours lands in multiple buckets, so this over-counts by
+-- hour the same way the daily version over-counted by day. The
+-- frontend prefers `ListDashboardAgentRunTime` for the user-facing
+-- "tasks" column, so this stays informational only.
SELECT
agent_id,
model,
@@ -152,9 +80,9 @@ SELECT
SUM(cache_read_tokens)::bigint AS cache_read_tokens,
SUM(cache_write_tokens)::bigint AS cache_write_tokens,
SUM(task_count)::int AS task_count
-FROM task_usage_dashboard_daily
+FROM task_usage_hourly
WHERE workspace_id = $1
- AND bucket_date >= DATE_TRUNC('day', @since::timestamptz)::date
+ AND bucket_hour >= @since::timestamptz
AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))
GROUP BY agent_id, model
ORDER BY agent_id, model;
@@ -163,12 +91,17 @@ ORDER BY agent_id, model;
-- Daily per-date run time + task counts for the workspace, optionally
-- scoped to a single project. Powers the workspace dashboard's "Time"
-- and "Tasks" metrics on the same toggle as Tokens / Cost. Bucketed by
--- completed_at (terminal time) — same anchor as ListDashboardAgentRunTime
--- so the day boundaries line up with the per-agent run-time card. Only
--- terminal tasks (completed or failed) with both started_at and
--- completed_at populated contribute.
+-- completed_at (terminal time) sliced into calendar days under the
+-- caller-supplied @tz — same Viewing-tz treatment as ListDashboardUsageDaily
+-- so the Time / Tasks tabs cut their day boundary identically to the
+-- Cost / Tokens tabs (a viewer east of UTC would otherwise see the four
+-- tabs disagree on a "1d" window). Only terminal tasks (completed or
+-- failed) with both started_at and completed_at populated contribute.
+--
+-- @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)
+-- — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.
SELECT
- DATE(atq.completed_at) AS date,
+ DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) AS date,
COALESCE(
SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,
0
@@ -182,10 +115,10 @@ WHERE a.workspace_id = $1
AND atq.status IN ('completed', 'failed')
AND atq.started_at IS NOT NULL
AND atq.completed_at IS NOT NULL
- AND atq.completed_at >= DATE_TRUNC('day', @since::timestamptz)
+ AND atq.completed_at >= sqlc.arg('since')::timestamptz
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-GROUP BY DATE(atq.completed_at)
-ORDER BY DATE(atq.completed_at) DESC;
+GROUP BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text)
+ORDER BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) DESC;
-- name: ListDashboardAgentRunTime :many
-- Per-agent total task run time and task count for the workspace, optionally
@@ -193,6 +126,10 @@ ORDER BY DATE(atq.completed_at) DESC;
-- with both started_at and completed_at populated — queued/running tasks have
-- no finite duration. Anchored on completed_at so the window matches the
-- token cost window (which is anchored on tu.created_at, ~= completion time).
+--
+-- No date bucketing, so no @tz — but @since is the viewer's local
+-- start-of-day-(N) so the "last N days" window lines up with the per-agent
+-- cost card; passed straight through without re-truncation.
SELECT
atq.agent_id,
COALESCE(
@@ -208,7 +145,7 @@ WHERE a.workspace_id = $1
AND atq.status IN ('completed', 'failed')
AND atq.started_at IS NOT NULL
AND atq.completed_at IS NOT NULL
- AND atq.completed_at >= DATE_TRUNC('day', @since::timestamptz)
+ AND atq.completed_at >= @since::timestamptz
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
GROUP BY atq.agent_id
ORDER BY total_seconds DESC;
diff --git a/server/pkg/db/queries/user.sql b/server/pkg/db/queries/user.sql
index 16cd366bff..3a4771b9b1 100644
--- a/server/pkg/db/queries/user.sql
+++ b/server/pkg/db/queries/user.sql
@@ -12,11 +12,28 @@ VALUES ($1, $2, $3)
RETURNING *;
-- name: UpdateUser :one
+-- Patches the user-controlled profile fields. Each parameter follows
+-- COALESCE-on-NULL semantics so the handler can omit any field it
+-- doesn't intend to write.
+--
+-- `timezone` (Viewing-tz preference) participates in
+-- the same shape but uses sqlc.narg + a sentinel-string convention:
+-- the handler passes the empty string "" to mean "clear back to NULL"
+-- (browser-detected fallback), an IANA name like "Asia/Shanghai" to
+-- pin a value, and `sqlc.narg('timezone') IS NULL` (no value at all)
+-- to leave the existing column untouched. Folding it into UpdateUser
+-- rather than carrying a dedicated UpdateUserTimezone keeps the
+-- profile-patch shape uniform between Preferences fields.
UPDATE "user" SET
name = COALESCE($2, name),
avatar_url = COALESCE($3, avatar_url),
language = COALESCE($4, language),
profile_description = COALESCE(sqlc.narg('profile_description'), profile_description),
+ timezone = CASE
+ WHEN sqlc.narg('timezone')::text IS NULL THEN timezone
+ WHEN sqlc.narg('timezone')::text = '' THEN NULL
+ ELSE sqlc.narg('timezone')::text
+ END,
updated_at = now()
WHERE id = $1
RETURNING *;