Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: plan-limited dashboard history range (MUL-9490) (#11032)
Multica Eve03dfb8f59b7b
diff --git a/.env.example b/.env.exampleindex 15839005d8..76f077e549 100644--- a/.env.example+++ b/.env.example@@ -224,6 +224,11 @@ MULTICA_FEATURE_FLAGS_FILE=# and search through the server again:# FF_LOCAL_SEARCH_INDEX=off+# The 365-day range on the Analytics page is on by default. Turning it off+# hides the range if year-long dashboard queries are too slow for this+# database; shorter ranges are unaffected:+# FF_DASHBOARD_HISTORY_365D=off+# Docs (MUL-8370) stays off until it launches: its API answers 403, Web and# Desktop hide its entry points, and agent briefs leave out `multica doc`.# Turn it on for a deployment that is testing it:diff --git a/apps/docs/content/docs/analytics.fr.mdx b/apps/docs/content/docs/analytics.fr.mdxindex b00e54c567..fd8dbf4fec 100644--- a/apps/docs/content/docs/analytics.fr.mdx+++ b/apps/docs/content/docs/analytics.fr.mdx@@ -12,7 +12,7 @@ La page **Statistiques** de la barre latérale regroupe la consommation des agenLa page a deux onglets, **Consommation** et **Erreurs**, qui partagent les deux filtres en haut à droite :-- **Période** : `1d`, `7d`, `30d` (par défaut), `90d`, `180d`. `1d` signifie aujourd'hui, à partir de minuit dans votre fuseau horaire, et non les dernières 24 heures.+- **Période** : `1d`, `7d`, `30d` (par défaut), `90d`, `180d`, `365d`. `1d` signifie aujourd'hui, à partir de minuit dans votre fuseau horaire, et non les dernières 24 heures. Sur Multica Cloud, votre forfait détermine jusqu'où vous pouvez remonter ; les périodes au-delà sont verrouillées dans le menu, et passer à un forfait supérieur affiche les données plus anciennes, qui sont toujours conservées.- **Projet** : **Tous les projets** par défaut. Avec un projet sélectionné, seules les exécutions des tâches de ce projet comptent ; celles qui n'appartiennent à aucune tâche, comme les exécutions de chat, sont exclues.Les jours sont découpés selon votre fuseau horaire : celui choisi dans **Paramètres → Préférences → Fuseau horaire**, ou celui du navigateur si vous n'en avez pas choisi. L'en-tête affiche ce fuseau et l'heure de la dernière mise à jour. Le serveur agrège les chiffres toutes les 5 minutes et une page ouverte se rafraîchit au même rythme ; une exécution qui vient de se terminer peut donc mettre quelques minutes à apparaître. Le bouton d'actualisation récupère tout de suite les derniers chiffres.@@ -32,7 +32,7 @@ Quatre chiffres en haut :Le temps d'exécution et le nombre d'exécutions ne comptent que les exécutions réellement démarrées (terminées, en échec ou annulées en cours de route) ; une exécution annulée alors qu'elle attendait encore dans la file n'est pas comptée.-La carte de tendance affiche Tokens, Coût, Temps ou Exécutions sur un même axe temporel, en **Quotidien** ou **Hebdomadaire**. `30d` et `90d` proposent les deux ; `1d` et `7d` sont uniquement quotidiens, `180d` uniquement hebdomadaire. Les semaines commencent le lundi, et la semaine en cours, pas encore terminée, est dessinée plus pâle ; au survol, la barre est marquée comme partielle avec le nombre de jours écoulés sur 7.+La carte de tendance affiche Tokens, Coût, Temps ou Exécutions sur un même axe temporel, en **Quotidien** ou **Hebdomadaire**. `30d` et `90d` proposent les deux ; `1d` et `7d` sont uniquement quotidiens, `180d` et `365d` uniquement hebdomadaires. Les semaines commencent le lundi, et la semaine en cours, pas encore terminée, est dessinée plus pâle ; au survol, la barre est marquée comme partielle avec le nombre de jours écoulés sur 7. Quand la période de votre forfait commence au milieu de la première semaine, cette semaine est marquée partielle de la même façon.Le **Classement** liste les tokens, le coût, le temps et les exécutions de chaque agent, triés selon l'une de ces quatre valeurs. Il affiche les 10 premiers ; **Tout afficher** montre le reste. Deux lignes peuvent regrouper plusieurs agents :diff --git a/apps/docs/content/docs/analytics.ja.mdx b/apps/docs/content/docs/analytics.ja.mdxindex da887e4b11..1e7bbff6cc 100644--- a/apps/docs/content/docs/analytics.ja.mdx+++ b/apps/docs/content/docs/analytics.ja.mdx@@ -12,7 +12,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";ページは**使用量**と**エラー**の 2 つのタブに分かれ、右上の 2 つのフィルターを共有します。-- **期間**: `1d`、`7d`、`30d`(既定)、`90d`、`180d`。`1d` はあなたのタイムゾーンの 0 時からの「今日」で、直近 24 時間ではありません。+- **期間**: `1d`、`7d`、`30d`(既定)、`90d`、`180d`、`365d`。`1d` はあなたのタイムゾーンの 0 時からの「今日」で、直近 24 時間ではありません。Multica Cloud では、どこまで遡って表示できるかはプランで決まります。プランを超える期間はメニューでロックされ、アップグレードするとそれ以前のデータも表示できます。データは削除されません。- **プロジェクト**: 既定は**すべてのプロジェクト**です。プロジェクトを選ぶと、そのプロジェクトのタスクで動いた実行だけを集計します。チャットなど、どのタスクにも属さない実行は含まれません。日付の区切りはあなたのタイムゾーンに従います。**設定 → 環境設定 → タイムゾーン**で設定した値を使い、未設定ならブラウザーのタイムゾーンを使います。ヘッダーには使用中のタイムゾーンとデータの更新時刻が表示されます。数値はサーバーが 5 分ごとに集計し、開いているページも同じ間隔で再読み込みするため、終わったばかりの実行が表示されるまで数分かかることがあります。すぐに見たいときは更新ボタンを押します。@@ -32,7 +32,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";実行時間と実行の数に入るのは、実際に動き始めた実行(完了、失敗、途中でキャンセル)だけです。待機中にキャンセルされた実行は含まれません。-推移カードでは、トークン・コスト・時間・実行の 4 つの指標を同じ時間軸で切り替え、**日別**と**週別**の単位を選べます。`30d` と `90d` はどちらも選べ、`1d` と `7d` は日別のみ、`180d` は週別のみです。週は月曜始まりで、まだ終わっていない今週は薄い色で描かれ、ホバーすると 7 日中何日経過したかが表示されます。+推移カードでは、トークン・コスト・時間・実行の 4 つの指標を同じ時間軸で切り替え、**日別**と**週別**の単位を選べます。`30d` と `90d` はどちらも選べ、`1d` と `7d` は日別のみ、`180d` と `365d` は週別のみです。週は月曜始まりで、まだ終わっていない今週は薄い色で描かれ、ホバーすると 7 日中何日経過したかが表示されます。プランの期間が最初の週の途中から始まる場合、その週も同じく一部として表示されます。**リーダーボード**はエージェントごとのトークン・コスト・時間・実行を並べ、どの項目でも並べ替えられます。上位 10 件を表示し、残りは**すべて表示**で開きます。複数のエージェントをまとめた行が出ることがあります。diff --git a/apps/docs/content/docs/analytics.ko.mdx b/apps/docs/content/docs/analytics.ko.mdxindex d352c142ec..c53c3b99af 100644--- a/apps/docs/content/docs/analytics.ko.mdx+++ b/apps/docs/content/docs/analytics.ko.mdx@@ -12,7 +12,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";페이지는 **사용량**과 **오류** 두 탭으로 나뉘고, 오른쪽 위의 필터 두 개를 함께 씁니다.-- **기간**: `1d`, `7d`, `30d`(기본값), `90d`, `180d`. `1d`는 내 시간대의 자정부터 시작하는 오늘이며, 최근 24시간이 아닙니다.+- **기간**: `1d`, `7d`, `30d`(기본값), `90d`, `180d`, `365d`. `1d`는 내 시간대의 자정부터 시작하는 오늘이며, 최근 24시간이 아닙니다. Multica Cloud에서는 얼마나 이전까지 볼 수 있는지 요금제가 정합니다. 요금제를 넘는 기간은 메뉴에서 잠기며, 업그레이드하면 이전 데이터도 볼 수 있습니다. 데이터는 삭제되지 않습니다.- **프로젝트**: 기본값은 **모든 프로젝트**입니다. 프로젝트를 고르면 그 프로젝트에 속한 태스크의 실행만 집계하고, 채팅처럼 어느 태스크에도 속하지 않는 실행은 빠집니다.날짜는 내 시간대 기준으로 나뉩니다. **설정 → 환경설정 → 시간대**에서 고른 값을 쓰고, 설정하지 않았으면 브라우저 시간대를 씁니다. 헤더에 현재 시간대와 데이터 업데이트 시각이 표시됩니다. 서버는 5분마다 수치를 집계하고 열려 있는 페이지도 같은 간격으로 새로고침하므로, 방금 끝난 실행은 몇 분 뒤에 나타날 수 있습니다. 바로 확인하려면 새로고침 버튼을 누르세요.@@ -32,7 +32,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";실행 시간과 실행 수에는 실제로 실행을 시작한 실행(완료, 실패, 도중 취소)만 들어갑니다. 대기 중에 취소된 실행은 빠집니다.-추이 카드는 토큰, 비용, 시간, 실행 네 가지 지표를 같은 시간 축에서 바꿔 가며 보여 주고, **일별**과 **주별** 단위를 고를 수 있습니다. `30d`와 `90d`는 둘 다 고를 수 있고, `1d`와 `7d`는 일별만, `180d`는 주별만 됩니다. 주는 월요일부터 시작하며, 아직 끝나지 않은 이번 주는 옅은 색으로 그려지고 마우스를 올리면 7일 중 며칠이 지났는지 표시됩니다.+추이 카드는 토큰, 비용, 시간, 실행 네 가지 지표를 같은 시간 축에서 바꿔 가며 보여 주고, **일별**과 **주별** 단위를 고를 수 있습니다. `30d`와 `90d`는 둘 다 고를 수 있고, `1d`와 `7d`는 일별만, `180d`와 `365d`는 주별만 됩니다. 주는 월요일부터 시작하며, 아직 끝나지 않은 이번 주는 옅은 색으로 그려지고 마우스를 올리면 7일 중 며칠이 지났는지 표시됩니다. 요금제 기간이 첫 주 중간부터 시작하면 그 주도 같은 방식으로 부분 주로 표시됩니다.**리더보드**는 에이전트별 토큰, 비용, 시간, 실행을 보여 주며 이 중 어느 항목으로든 정렬할 수 있습니다. 상위 10개를 보여 주고 나머지는 **전체 보기**로 펼칩니다. 여러 에이전트를 묶은 행이 나올 수 있습니다.diff --git a/apps/docs/content/docs/analytics.mdx b/apps/docs/content/docs/analytics.mdxindex c27420495f..0c83af43c9 100644--- a/apps/docs/content/docs/analytics.mdx+++ b/apps/docs/content/docs/analytics.mdx@@ -12,7 +12,7 @@ The **Analytics** page in the sidebar rolls up agent usage across the whole workThe page has two tabs, **Usage** and **Errors**, which share the two filters at the top right:-- **Time range**: `1d`, `7d`, `30d` (default), `90d`, `180d`. `1d` means today, starting at midnight in your time zone, not the last 24 hours.+- **Time range**: `1d`, `7d`, `30d` (default), `90d`, `180d`, `365d`. `1d` means today, starting at midnight in your time zone, not the last 24 hours. On Multica Cloud, your plan sets how far back you can look; ranges beyond it are locked in the menu, and upgrading shows the earlier data, which is always kept.- **Project**: **All projects** by default. With a project selected, only runs on that project's issues count; runs that belong to no issue, such as chat runs, drop out.Days are cut in your time zone: the one set under **Settings → Preferences → Time zone**, or the browser's if you have not set one. The header shows that time zone and when the data was last updated. The server rolls the figures up every 5 minutes and an open page refreshes on the same interval, so a run that just finished can take a few minutes to appear; the refresh button pulls the latest figures immediately.@@ -32,7 +32,7 @@ Four figures sit at the top:Run time and Runs count only runs that actually started executing (completed, failed, or cancelled mid-run); a run cancelled while still queued is left out.-The trend card plots Tokens, Cost, Time, or Runs on one time axis, at a **Daily** or **Weekly** grain. `30d` and `90d` offer both; `1d` and `7d` are daily only, `180d` weekly only. Weeks start on Monday, and the current, unfinished week is drawn lighter; hovering it marks the bar as partial and says how many of its 7 days have passed.+The trend card plots Tokens, Cost, Time, or Runs on one time axis, at a **Daily** or **Weekly** grain. `30d` and `90d` offer both; `1d` and `7d` are daily only, `180d` and `365d` weekly only. Weeks start on Monday, and the current, unfinished week is drawn lighter; hovering it marks the bar as partial and says how many of its 7 days have passed. When your plan's range starts partway through the first week, that week is marked partial the same way.The **Leaderboard** lists each agent's tokens, cost, run time, and runs, ranked by whichever of the four you pick. It shows the top 10; **Show all** reveals the rest. Two rows can stand for more than one agent:diff --git a/apps/docs/content/docs/analytics.zh-Hant.mdx b/apps/docs/content/docs/analytics.zh-Hant.mdxindex 8a5dd6817d..e439e20e6f 100644--- a/apps/docs/content/docs/analytics.zh-Hant.mdx+++ b/apps/docs/content/docs/analytics.zh-Hant.mdx@@ -12,7 +12,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";頁面分**用量**和**錯誤**兩個頁籤,共用右上角的兩個篩選:-- **時間範圍**:`1d`、`7d`、`30d`(預設)、`90d`、`180d`。`1d` 指今天,從你所在時區的 0 點算起,不是最近 24 小時。+- **時間範圍**:`1d`、`7d`、`30d`(預設)、`90d`、`180d`、`365d`。`1d` 指今天,從你所在時區的 0 點算起,不是最近 24 小時。在 Multica Cloud 上,能查看多久的資料由方案決定;超出方案的範圍在選單裡上鎖,升級後就能看到更早的資料,資料一直保留。- **專案**:預設**全部專案**。選定專案後,只統計這個專案下任務的執行;對話等不屬於任何任務的執行不計入。日期按你的時區切分:先用**設定 → 偏好設定 → 時區**裡的設定,沒設定時用瀏覽器時區。頁頭顯示當前時區和資料更新時間。統計資料由伺服器每 5 分鐘彙總一次,頁面開著時也按這個間隔重新整理,剛結束的執行可能要過幾分鐘才出現;想馬上看可以點重新整理按鈕。@@ -32,7 +32,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";耗時和執行數只算真正開始執行過的執行(已完成、失敗或中途取消),排隊時就被取消的不算。-趨勢卡片在同一條時間軸上切換 Token、費用、耗時、執行數四種指標,**按天**和**按周**兩種粒度。`30d` 和 `90d` 兩種都能選;`1d`、`7d` 只能按天,`180d` 只能按周。按周時每週從週一開始,還沒過完的本週顏色較淺,懸停會標出"未滿 · 已過 N / 7 天"。+趨勢卡片在同一條時間軸上切換 Token、費用、耗時、執行數四種指標,**按天**和**按周**兩種粒度。`30d` 和 `90d` 兩種都能選;`1d`、`7d` 只能按天,`180d`、`365d` 只能按周。按周時每週從週一開始,還沒過完的本週顏色較淺,懸停會標出"未滿 · 已過 N / 7 天"。方案範圍從第一週中間開始時,這一週也按未滿標出。**排行榜**按 AI 代理列出 Token、費用、耗時和執行數,可以按其中任意一項排序,預設顯示前 10 個,點**展開全部**看其餘的。排行榜裡可能有兩行彙總:diff --git a/apps/docs/content/docs/analytics.zh.mdx b/apps/docs/content/docs/analytics.zh.mdxindex cb9cfc1152..329326353f 100644--- a/apps/docs/content/docs/analytics.zh.mdx+++ b/apps/docs/content/docs/analytics.zh.mdx@@ -12,7 +12,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";页面分**用量**和**错误**两个页签,共用右上角的两个筛选:-- **时间范围**:`1d`、`7d`、`30d`(默认)、`90d`、`180d`。`1d` 指今天,从你所在时区的 0 点算起,不是最近 24 小时。+- **时间范围**:`1d`、`7d`、`30d`(默认)、`90d`、`180d`、`365d`。`1d` 指今天,从你所在时区的 0 点算起,不是最近 24 小时。在 Multica Cloud 上,能查看多久的数据由套餐决定;超出套餐的范围在菜单里上锁,升级后就能看到更早的数据,数据一直保留。- **项目**:默认**全部项目**。选定项目后,只统计这个项目下任务的运行;对话等不属于任何任务的运行不计入。日期按你的时区切分:先用**设置 → 偏好设置 → 时区**里的设置,没设置时用浏览器时区。页头显示当前时区和数据更新时间。统计数据由服务器每 5 分钟汇总一次,页面开着时也按这个间隔刷新,刚结束的运行可能要过几分钟才出现;想马上看可以点刷新按钮。@@ -32,7 +32,7 @@ import { UsageDemo } from "@/components/demos/usage-demo";耗时和运行数只算真正开始执行过的运行(已完成、失败或中途取消),排队时就被取消的不算。-趋势卡片在同一条时间轴上切换 Token、费用、耗时、运行数四种指标,**按天**和**按周**两种粒度。`30d` 和 `90d` 两种都能选;`1d`、`7d` 只能按天,`180d` 只能按周。按周时每周从周一开始,还没过完的本周颜色较浅,悬停会标出"未满 · 已过 N / 7 天"。+趋势卡片在同一条时间轴上切换 Token、费用、耗时、运行数四种指标,**按天**和**按周**两种粒度。`30d` 和 `90d` 两种都能选;`1d`、`7d` 只能按天,`180d`、`365d` 只能按周。按周时每周从周一开始,还没过完的本周颜色较浅,悬停会标出"未满 · 已过 N / 7 天"。套餐范围从第一周中间开始时,这一周也按未满标出。**排行榜**按智能体列出 Token、费用、耗时和运行数,可以按其中任意一项排序,默认显示前 10 个,点**展开全部**看其余的。排行榜里可能有两行汇总:diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 012ae1c249..1ef92892c6 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -682,6 +682,23 @@ export interface LoginResponse {user: User;}+/** Response header carrying the plan's enforced dashboard history limit. */+export const DASHBOARD_HISTORY_LIMIT_HEADER = "X-Dashboard-History-Limit-Days";++/** A positive whole number of days, or null for absent or malformed. */+export function parseDashboardHistoryLimit(value: string | null): number | null {+ if (value === null || !/^\d+$/.test(value.trim())) return null;+ const days = Number(value.trim());+ return Number.isSafeInteger(days) && days > 0 ? days : null;+}++export interface DashboardRequestParams {+ days?: number;+ project_id?: string | null;+ tz?: string;+ onHistoryLimit?: (limitDays: number | null) => void;+}+function parseSearchIndexResponse<T>(raw: unknown, schema: ZodType, endpoint: string): T {const parsed = parseWithFallback<T | null>(raw, schema, null, { endpoint });if (parsed === null) throw new Error(`Malformed response from ${endpoint}`);@@ -2698,7 +2715,7 @@ export class ApiClient {return parseWithFallback<WorkspaceFeatures>(raw,WorkspaceFeaturesSchema,- { features: {} },+ { features: {}, limits: { dashboardHistoryDays: null } },{ endpoint: "GET /api/workspaces/:id/features" },);}@@ -3170,110 +3187,86 @@ export class ApiClient {);}- // Workspace dashboard — three independent rollups for `/{slug}/dashboard`.- // Each accepts an optional `project_id` to narrow the scope to one project.- // Cost is computed client-side from the model pricing table (same contract- // as the per-runtime endpoints above).-- async getDashboardUsageDaily(- params: { days?: number; project_id?: string | null; tz?: string },- ): Promise<DashboardUsageDaily[]> {+ // Workspace dashboard — six rollups for `/{slug}/usage`. Each accepts an+ // optional `project_id` to narrow the scope to one project and `tz` to cut+ // its day boundary in the viewer's calendar. Cost is computed client-side+ // from the model pricing table (same contract as the per-runtime endpoints+ // above).+ //+ // `onHistoryLimit` receives the plan's enforced history limit the response+ // was served under (X-Dashboard-History-Limit-Days), or null for none, so a+ // page open across a plan change notices it (MUL-9490).+ private async fetchDashboardRows<T>(+ path: string,+ params: DashboardRequestParams,+ schema: ZodType,+ endpoint: string,+ ): Promise<T[]> {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,+ const res = await this.fetchRaw(`${path}?${search}`, {+ extraHeaders: { "Content-Type": "application/json" },+ });+ params.onHistoryLimit?.(+ parseDashboardHistoryLimit(res.headers.get(DASHBOARD_HISTORY_LIMIT_HEADER)),+ );+ const raw: unknown = await res.json();+ return parseWithFallback<T[]>(raw, schema, [], { endpoint });+ }++ async getDashboardUsageDaily(params: DashboardRequestParams): Promise<DashboardUsageDaily[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/usage/daily",+ params,DashboardUsageDailyListSchema,- [],- { endpoint: "GET /api/dashboard/usage/daily" },+ "GET /api/dashboard/usage/daily",);}- async getDashboardUsageByAgent(- 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,+ async getDashboardUsageByAgent(params: DashboardRequestParams): Promise<DashboardUsageByAgent[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/usage/by-agent",+ params,DashboardUsageByAgentListSchema,- [],- { endpoint: "GET /api/dashboard/usage/by-agent" },+ "GET /api/dashboard/usage/by-agent",);}- async getDashboardAgentRunTime(- 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,+ async getDashboardAgentRunTime(params: DashboardRequestParams): Promise<DashboardAgentRunTime[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/agent-runtime",+ params,DashboardAgentRunTimeListSchema,- [],- { endpoint: "GET /api/dashboard/agent-runtime" },+ "GET /api/dashboard/agent-runtime",);}- async getDashboardRunTimeDaily(- 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,+ async getDashboardRunTimeDaily(params: DashboardRequestParams): Promise<DashboardRunTimeDaily[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/runtime/daily",+ params,DashboardRunTimeDailyListSchema,- [],- { endpoint: "GET /api/dashboard/runtime/daily" },+ "GET /api/dashboard/runtime/daily",);}- async getDashboardFailuresDaily(- params: { days?: number; project_id?: string | null; tz?: string },- ): Promise<DashboardFailureDaily[]> {- 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 the Errors chart- // shares an x-axis with the other four metrics.- if (params.tz) search.set("tz", params.tz);- const raw = await this.fetch<unknown>(`/api/dashboard/failures/daily?${search}`);- return parseWithFallback<DashboardFailureDaily[]>(- raw,+ async getDashboardFailuresDaily(params: DashboardRequestParams): Promise<DashboardFailureDaily[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/failures/daily",+ params,DashboardFailureDailyListSchema,- [],- { endpoint: "GET /api/dashboard/failures/daily" },+ "GET /api/dashboard/failures/daily",);}- async getDashboardFailuresByAgent(- params: { days?: number; project_id?: string | null; tz?: string },- ): Promise<DashboardFailureByAgent[]> {- 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/failures/by-agent?${search}`);- return parseWithFallback<DashboardFailureByAgent[]>(- raw,+ async getDashboardFailuresByAgent(params: DashboardRequestParams): Promise<DashboardFailureByAgent[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/failures/by-agent",+ params,DashboardFailureByAgentListSchema,- [],- { endpoint: "GET /api/dashboard/failures/by-agent" },+ "GET /api/dashboard/failures/by-agent",);}diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 7f2bc80302..b6942ed102 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -2284,3 +2284,145 @@ describe("workspace subscription contract", () => {);});});++describe("dashboard history limit (MUL-9490)", () => {+ const planPrices = (monthAmount: number, yearAmount: number) => ({+ month: { currency: "usd", unit_amount: monthAmount, interval: "month", interval_count: 1 },+ year: { currency: "usd", unit_amount: yearAmount, interval: "year", interval_count: 1 },+ });+ const prices = { pro: planPrices(1500, 14400), business: planPrices(3000, 28800) };++ it("reads plan limits from prices, and drops them alone when malformed", async () => {+ const client = new ApiClient("https://api.example.test");+ stubFetchJson({+ ...prices,+ plan_limits: {+ free: { dashboard_history_days: 30 },+ pro: { dashboard_history_days: 90 },+ business: { dashboard_history_days: 365 },+ },+ });+ expect((await client.getWorkspaceSubscriptionPrices())?.planLimits).toEqual({+ free: { dashboardHistoryDays: 30 },+ pro: { dashboardHistoryDays: 90 },+ business: { dashboardHistoryDays: 365 },+ });++ // An older Cloud sends none; the prices themselves stay usable.+ stubFetchJson(prices);+ const older = await client.getWorkspaceSubscriptionPrices();+ expect(older?.pro.month.unitAmount).toBe(1500);+ expect(older?.planLimits).toBeNull();++ // A malformed block, or a missing plan, reads as no plan limits.+ for (const planLimits of [+ "30",+ { free: { dashboard_history_days: 30 }, pro: { dashboard_history_days: 90 } },+ ]) {+ stubFetchJson({ ...prices, plan_limits: planLimits });+ const parsed = await client.getWorkspaceSubscriptionPrices();+ expect(parsed?.business.month.unitAmount).toBe(3000);+ expect(parsed?.planLimits).toBeNull();+ }++ // A malformed day count is unknown for that plan only.+ stubFetchJson({+ ...prices,+ plan_limits: {+ free: { dashboard_history_days: "30" },+ pro: { dashboard_history_days: 0 },+ business: { dashboard_history_days: 365 },+ },+ });+ expect((await client.getWorkspaceSubscriptionPrices())?.planLimits).toEqual({+ free: { dashboardHistoryDays: null },+ pro: { dashboardHistoryDays: null },+ business: { dashboardHistoryDays: 365 },+ });+ });++ it("reads the features limit and treats a missing or malformed one as none", async () => {+ const client = new ApiClient("https://api.example.test");+ const ws = "11111111-1111-1111-1111-111111111111";+ stubFetchJson({ features: {}, limits: { dashboard_history_days: 30 } });+ expect((await client.getWorkspaceFeatures(ws)).limits).toEqual({ dashboardHistoryDays: 30 });++ for (const body of [+ { features: {} },+ { features: {}, limits: null },+ { features: {}, limits: { dashboard_history_days: null } },+ { features: {}, limits: { dashboard_history_days: "30" } },+ { features: {}, limits: { dashboard_history_days: -1 } },+ { features: {}, limits: [] },+ ]) {+ stubFetchJson(body);+ expect((await client.getWorkspaceFeatures(ws)).limits).toEqual({ dashboardHistoryDays: null });+ }+ });++ it("reads the entitlement's history range when Cloud sends it", async () => {+ const client = new ApiClient("https://api.example.test");+ const summary = (limits: Record<string, unknown>) => ({+ entitlement: {+ workspace_id: "11111111-1111-1111-1111-111111111111",+ plan: "free",+ status: "active",+ seats: 1,+ limits: { autopilot_runs: { mode: "limited", limit: 200 }, ...limits },+ current_period_end: null,+ snapshot_expires_at: null,+ version: 1,+ },+ billing_interval: null,+ human_members: 1,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: false,+ available_actions: { checkout: true, portal: false, purchase_seats: false },+ });+ stubFetchJson(summary({ dashboard_history_days: { mode: "limited", limit: 30 } }));+ expect((await client.getWorkspaceSubscriptionSummary())?.entitlement.limits.dashboardHistoryDays).toEqual({+ mode: "limited",+ limit: 30,+ });+ stubFetchJson(summary({}));+ const older = await client.getWorkspaceSubscriptionSummary();+ expect(older?.entitlement.limits.autopilotRuns).toEqual({ mode: "limited", limit: 200 });+ expect(older?.entitlement.limits.dashboardHistoryDays).toBeNull();+ stubFetchJson(summary({ dashboard_history_days: { mode: "limited", limit: "30" } }));+ expect((await client.getWorkspaceSubscriptionSummary())?.entitlement.limits.dashboardHistoryDays).toBeNull();+ });++ it("reports the limit header every dashboard endpoint was served under", async () => {+ const client = new ApiClient("https://api.example.test");+ const calls = [+ client.getDashboardUsageDaily.bind(client),+ client.getDashboardUsageByAgent.bind(client),+ client.getDashboardAgentRunTime.bind(client),+ client.getDashboardRunTimeDaily.bind(client),+ client.getDashboardFailuresDaily.bind(client),+ client.getDashboardFailuresByAgent.bind(client),+ ];+ for (const call of calls) {+ for (const [header, want] of [+ ["30", 30],+ [null, null],+ ["", null],+ ["abc", null],+ ["0", null],+ ["-5", null],+ ] as const) {+ const headers: Record<string, string> = { "Content-Type": "application/json" };+ if (header !== null) headers["X-Dashboard-History-Limit-Days"] = header;+ const fetchMock = vi.fn().mockResolvedValue(new Response("[]", { status: 200, headers }));+ vi.stubGlobal("fetch", fetchMock);+ const seen: (number | null)[] = [];+ const rows = await call({ days: 371, tz: "UTC", onHistoryLimit: (v) => seen.push(v) });+ expect(rows).toEqual([]);+ expect(seen).toEqual([want]);+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain("days=371");+ }+ }+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 215cbf94be..1592f6c580 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -44,6 +44,7 @@ import type {WorkspaceSubscriptionPrice,WorkspaceSubscriptionPlanPrices,WorkspaceSubscriptionPrices,+ WorkspacePlanLimits,CreateWorkspaceAutopilotAddonCheckoutResponse,WorkspaceAutopilotAddonCheckout,WorkspaceAutopilotAddonPrice,@@ -3644,6 +3645,9 @@ export const WorkspaceSubscriptionEntitlementsSchema = z// Optional: a Cloud without the storage limit omits it, and a// malformed one must not fail the whole snapshot.storage_bytes: WorkspaceEntitlementLimitSchema.nullable().optional().catch(null),+ // Newer than autopilot_runs: an older Cloud omits it, and a malformed+ // one only hides its own row.+ dashboard_history_days: WorkspaceEntitlementLimitSchema.nullable().catch(null).default(null),}).loose(),current_period_end: z.string().nullable().optional(),@@ -3660,6 +3664,7 @@ export const WorkspaceSubscriptionEntitlementsSchema = zlimits: {autopilotRuns: value.limits.autopilot_runs,storageBytes: value.limits.storage_bytes ?? null,+ dashboardHistoryDays: value.limits.dashboard_history_days,},currentPeriodEnd: value.current_period_end ?? null,snapshotExpiresAt: value.snapshot_expires_at ?? null,@@ -3924,6 +3929,36 @@ const WorkspaceAutopilotAddonPriceSchema = z// Every paid plan must be priced: a response missing one plan reads as "prices// unavailable" as a whole rather than offering one plan without the other.+// A day count from a newer or malformed Cloud reads as unknown, never as a+// number: the plan labels it feeds are hints, and a wrong one would point a+// user at the wrong plan.+const PlanDaysSchema = z.number().int().positive().nullable().catch(null).default(null);++const WorkspacePlanLimitSchema = z+ .object({ dashboard_history_days: PlanDaysSchema })+ .loose()+ .transform((value) => ({ dashboardHistoryDays: value.dashboard_history_days }));++// Plan limits are optional: an older Cloud does not send them, and a malformed+// block reads as absent rather than failing the prices themselves.+const WorkspacePlanLimitsSchema = z+ .object({+ free: WorkspacePlanLimitSchema,+ pro: WorkspacePlanLimitSchema,+ business: WorkspacePlanLimitSchema,+ })+ .loose()+ .transform(+ (value): WorkspacePlanLimits => ({+ free: value.free,+ pro: value.pro,+ business: value.business,+ }),+ )+ .nullable()+ .catch(null)+ .default(null);+export const WorkspaceSubscriptionPricesSchema = z.object({pro: WorkspaceSubscriptionPlanPricesSchema,@@ -3931,6 +3966,7 @@ export const WorkspaceSubscriptionPricesSchema = zautopilot_addon: WorkspaceAutopilotAddonPriceSchema.nullable().optional().catch(null),+ plan_limits: WorkspacePlanLimitsSchema,}).loose().transform(@@ -3938,6 +3974,7 @@ export const WorkspaceSubscriptionPricesSchema = zpro: value.pro,business: value.business,autopilotAddon: value.autopilot_addon ?? null,+ planLimits: value.plan_limits,}),);@@ -3986,14 +4023,25 @@ const WorkspaceFeatureStateSchema = z.transform((value): WorkspaceFeatureState => value.state).catch("available" as const);+// A limit that is missing (an older server) or malformed reads as none: the+// server still cuts every dashboard response to the enforced range.+const WorkspaceFeatureLimitsSchema = z+ .object({ dashboard_history_days: PlanDaysSchema })+ .loose()+ .transform((value) => ({ dashboardHistoryDays: value.dashboard_history_days }))+ .catch({ dashboardHistoryDays: null })+ .default({ dashboardHistoryDays: null });+export const WorkspaceFeaturesSchema = z.object({features: z.record(z.string(), WorkspaceFeatureStateSchema).catch({}),+ limits: WorkspaceFeatureLimitsSchema,}).loose().transform((value): WorkspaceFeatures => ({features: value.features as WorkspaceFeatures["features"],+ limits: value.limits,}),);diff --git a/packages/core/billing/paid-features.test.tsx b/packages/core/billing/paid-features.test.tsxindex 9935933ab9..0e0f1767e1 100644--- a/packages/core/billing/paid-features.test.tsx+++ b/packages/core/billing/paid-features.test.tsx@@ -32,6 +32,8 @@ afterEach(() => {vi.restoreAllMocks();});+const NO_LIMITS = { dashboardHistoryDays: null };+describe("resolvePaidFeatureAccess", () => {it("maps the server state and the resource's own configuration to a UI state", () => {expect(resolvePaidFeatureAccess("available", false)).toBe("available");@@ -43,7 +45,7 @@ describe("resolvePaidFeatureAccess", () => {describe("usePaidFeatureAccess", () => {it("is read-only for a resource that already uses a locked feature, and never blocks reductions", async () => {- const { wrapper } = setup(async () => ({ features: { private_projects: "locked" } }));+ const { wrapper } = setup(async () => ({ features: { private_projects: "locked" }, limits: NO_LIMITS }));const { result } = renderHook(() => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: true }),{ wrapper },@@ -55,6 +57,7 @@ describe("usePaidFeatureAccess", () => {it("keys the read by workspace", async () => {const { api, wrapper } = setup(async (wsId) => ({features: { private_projects: wsId === "ws-locked" ? "locked" : "available" },+ limits: NO_LIMITS,}));const locked = renderHook(() => usePaidFeatureAccess("ws-locked", "private_projects", { hasExistingConfig: false }),@@ -92,7 +95,7 @@ describe("usePaidFeatureAccess", () => {});it("treats a feature the server did not report as available", async () => {- const { wrapper } = setup(async () => ({ features: {} }));+ const { wrapper } = setup(async () => ({ features: {}, limits: NO_LIMITS }));const { result } = renderHook(() => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: true }),{ wrapper },@@ -134,10 +137,11 @@ describe("WorkspaceFeaturesSchema", () => {}),).toEqual({features: { private_projects: "locked", future_feature: "available", broken: "available" },+ limits: NO_LIMITS,});- expect(WorkspaceFeaturesSchema.parse({ features: [] })).toEqual({ features: {} });- expect(WorkspaceFeaturesSchema.parse({ features: null })).toEqual({ features: {} });- expect(WorkspaceFeaturesSchema.parse({})).toEqual({ features: {} });+ expect(WorkspaceFeaturesSchema.parse({ features: [] })).toEqual({ features: {}, limits: NO_LIMITS });+ expect(WorkspaceFeaturesSchema.parse({ features: null })).toEqual({ features: {}, limits: NO_LIMITS });+ expect(WorkspaceFeaturesSchema.parse({})).toEqual({ features: {}, limits: NO_LIMITS });});it("reads the Business access and app features, and one malformed entry does not drop the others", () => {@@ -155,6 +159,7 @@ describe("WorkspaceFeaturesSchema", () => {runtime_member_sharing: "available",team_app_accounts: "locked",},+ limits: NO_LIMITS,});expect(WorkspaceFeaturesSchema.parse({@@ -172,6 +177,7 @@ describe("WorkspaceFeaturesSchema", () => {team_app_accounts: "locked",private_projects: "available",},+ limits: NO_LIMITS,});});});@@ -180,7 +186,7 @@ describe("usePaidFeatureAccess for the Business access and app features", () =>it.each(["agent_invocation_members", "runtime_member_sharing", "team_app_accounts"] as const)("resolves %s independently of the other features",async (feature) => {- const { wrapper } = setup(async () => ({ features: { [feature]: "locked", private_projects: "available" } }));+ const { wrapper } = setup(async () => ({ features: { [feature]: "locked", private_projects: "available" }, limits: NO_LIMITS }));const existing = renderHook(() => usePaidFeatureAccess("ws-1", feature, { hasExistingConfig: true }), { wrapper });const fresh = renderHook(() => usePaidFeatureAccess("ws-1", feature, { hasExistingConfig: false }), { wrapper });const other = renderHook(() => usePaidFeatureAccess("ws-1", "private_projects", { hasExistingConfig: false }), { wrapper });diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.tsindex 35c78eff6b..5ed380c9d7 100644--- a/packages/core/billing/workspace-subscription-mutations.ts+++ b/packages/core/billing/workspace-subscription-mutations.ts@@ -8,6 +8,7 @@ import type {PreviewWorkspaceSeatPurchaseRequest,PurchaseWorkspaceSeatsRequest,} from "../types";+import { workspaceFeatureKeys } from "./paid-features";import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";import { autopilotKeys } from "../autopilots/queries";@@ -66,7 +67,8 @@ export function usePreviewWorkspacePlanChange() {/*** Cloud persists the new plan before answering, so refreshing the whole* workspace subscription scope (summary and anything keyed under it) shows the- * switched plan without waiting for Stripe's webhook.+ * switched plan without waiting for Stripe's webhook. The paid features and+ * plan limits change with it.*/export function useChangeWorkspacePlan(wsId: string) {const queryClient = useQueryClient();@@ -77,6 +79,9 @@ export function useChangeWorkspacePlan(wsId: string) {void queryClient.invalidateQueries({queryKey: workspaceSubscriptionKeys.all(wsId),});+ void queryClient.invalidateQueries({+ queryKey: workspaceFeatureKeys.all(wsId),+ });},});}diff --git a/packages/core/dashboard/history-limit.test.tsx b/packages/core/dashboard/history-limit.test.tsxnew file mode 100644index 0000000000..35a3613b8a--- /dev/null+++ b/packages/core/dashboard/history-limit.test.tsx@@ -0,0 +1,225 @@+/**+ * @vitest-environment jsdom+ */+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { setApiInstance } from "../api";+import type { ApiClient, DashboardRequestParams } from "../api/client";+import type { WorkspaceFeatures } from "../types";+import {+ minHistoryLimit,+ resolveDashboardHistoryLimit,+ useDashboardHistoryLimit,+} from "./history-limit";+import { dashboardUsageByAgentOptions } from "./queries";++const features = (days: number | null): WorkspaceFeatures => ({+ features: {},+ limits: { dashboardHistoryDays: days },+});++/**+ * A server whose plan can change between reads: features and every dashboard+ * response report the same current limit, like one Multica instance would.+ */+function setup(initialLimit: number | null) {+ let limit = initialLimit;+ const api = {+ getWorkspaceFeatures: vi.fn(async () => features(limit)),+ getDashboardUsageByAgent: vi.fn(async (params: DashboardRequestParams) => {+ params.onHistoryLimit?.(limit);+ return [];+ }),+ };+ setApiInstance(api as unknown as ApiClient);+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ return {+ api,+ qc,+ wrapper,+ setPlanLimit: (next: number | null) => {+ limit = next;+ },+ };+}++/** The page's wiring: the dashboard query is made under the resolved limit. */+function useDashboard(wsId: string) {+ const history = useDashboardHistoryLimit(wsId);+ const query = useQuery(+ dashboardUsageByAgentOptions(wsId, 30, null, "UTC", history.ready ? history.maxDays : undefined),+ );+ return { history, query };+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe("resolveDashboardHistoryLimit", () => {+ it("lets a dashboard response newer than the features read tighten the limit", () => {+ expect(minHistoryLimit(null, 30)).toBe(30);+ expect(minHistoryLimit(90, null)).toBe(90);+ expect(minHistoryLimit(90, 30)).toBe(30);+ expect(resolveDashboardHistoryLimit(90, 100, undefined)).toBe(90);+ expect(resolveDashboardHistoryLimit(90, 100, { limitDays: 30, observedAt: 200 })).toBe(30);+ expect(resolveDashboardHistoryLimit(null, 100, { limitDays: 30, observedAt: 200 })).toBe(30);+ // An upgrade seen first in a response never widens before features agree.+ expect(resolveDashboardHistoryLimit(30, 100, { limitDays: null, observedAt: 200 })).toBe(30);+ // A features read newer than the observation decides alone.+ expect(resolveDashboardHistoryLimit(null, 300, { limitDays: 30, observedAt: 200 })).toBeNull();+ });+});++describe("useDashboardHistoryLimit", () => {+ it("does not query the dashboard until the limit is known", async () => {+ const { api, wrapper } = setup(30);+ let resolveFeatures: (value: WorkspaceFeatures) => void = () => {};+ api.getWorkspaceFeatures.mockImplementationOnce(+ () => new Promise<WorkspaceFeatures>((resolve) => (resolveFeatures = resolve)),+ );+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ expect(result.current.history.ready).toBe(false);+ expect(api.getDashboardUsageByAgent).not.toHaveBeenCalled();++ act(() => resolveFeatures(features(30)));+ await waitFor(() => expect(api.getDashboardUsageByAgent).toHaveBeenCalledTimes(1));+ expect(result.current.history).toEqual({ ready: true, maxDays: 30 });+ });++ it("still loads the dashboard when the features read fails", async () => {+ const { api, wrapper } = setup(null);+ api.getWorkspaceFeatures.mockRejectedValueOnce(new Error("offline"));+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(api.getDashboardUsageByAgent).toHaveBeenCalledTimes(1));+ expect(result.current.history).toEqual({ ready: true, maxDays: null });+ });++ it("notices a trial ending while the page stays open", async () => {+ const { api, qc, wrapper, setPlanLimit } = setup(null);+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));+ expect(result.current.history.maxDays).toBeNull();+ const featureReads = api.getWorkspaceFeatures.mock.calls.length;++ // The trial ends; the features read is still cached. The next periodic+ // dashboard refetch is served under the new limit.+ setPlanLimit(30);+ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));++ await waitFor(() => expect(result.current.history.maxDays).toBe(30));+ await waitFor(() =>+ expect(api.getWorkspaceFeatures.mock.calls.length).toBeGreaterThan(featureReads),+ );+ // The query moved to the new limit's key and settled there.+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));+ const lastCall = api.getDashboardUsageByAgent.mock.calls.length;+ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));+ expect(api.getDashboardUsageByAgent.mock.calls.length).toBe(lastCall + 1);+ expect(result.current.history.maxDays).toBe(30);+ });++ it("lifts the limit only once the features read confirms an upgrade", async () => {+ const { api, qc, wrapper, setPlanLimit } = setup(30);+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));+ expect(result.current.history.maxDays).toBe(30);++ // An upgrade paid elsewhere. Hold the features refresh to see the+ // in-between state.+ setPlanLimit(null);+ let releaseFeatures: () => void = () => {};+ api.getWorkspaceFeatures.mockImplementationOnce(+ () =>+ new Promise<WorkspaceFeatures>((resolve) => {+ releaseFeatures = () => resolve(features(null));+ }),+ );+ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));+ expect(result.current.history.maxDays).toBe(30);++ act(() => releaseFeatures());+ await waitFor(() => expect(result.current.history.maxDays).toBeNull());+ });++ it("observe → enforce: a features read that turns the limit on re-keys the dashboard", async () => {+ const { api, qc, wrapper, setPlanLimit } = setup(null);+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));+ const before = api.getDashboardUsageByAgent.mock.calls.length;++ setPlanLimit(90);+ await act(() => qc.invalidateQueries({ queryKey: ["workspace-features", "ws-1"] }));++ await waitFor(() => expect(result.current.history.maxDays).toBe(90));+ await waitFor(() => expect(api.getDashboardUsageByAgent.mock.calls.length).toBe(before + 1));+ // Not a placeholder from the unlimited key.+ expect(result.current.query.isPlaceholderData).toBe(false);+ });++ it("keeps the strictest limit seen until the features read confirms it", async () => {+ // Pro: 90 days. The plan drops to Free, but replicas disagree for a while:+ // a response under the new policy (30) arrives, then a late one served+ // under the old, unlimited policy.+ const { api, qc, wrapper } = setup(90);+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));+ expect(result.current.history.maxDays).toBe(90);++ const servedQueue: (number | null)[] = [30, null];+ api.getDashboardUsageByAgent.mockImplementation(async (params: DashboardRequestParams) => {+ params.onHistoryLimit?.(servedQueue.length > 0 ? servedQueue.shift()! : 30);+ return [];+ });+ // Hold the features refresh so only dashboard responses speak.+ let releaseFeatures: () => void = () => {};+ api.getWorkspaceFeatures.mockImplementation(+ () =>+ new Promise<WorkspaceFeatures>((resolve) => {+ releaseFeatures = () => resolve(features(30));+ }),+ );++ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));+ await waitFor(() => expect(result.current.history.maxDays).toBe(30));+ // The late unlimited response, now under the 30-day key.+ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));+ expect(result.current.history.maxDays).toBe(30);++ act(() => releaseFeatures());+ await waitFor(() => expect(result.current.history.maxDays).toBe(30));+ });++ it("never caches rows cut to a stricter limit under the looser key", async () => {+ const { api, qc, wrapper, setPlanLimit } = setup(90);+ const { result } = renderHook(() => useDashboard("ws-1"), { wrapper });+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true));++ // The 90-day query is refetched after the downgrade and served cut to 30.+ setPlanLimit(30);+ api.getDashboardUsageByAgent.mockImplementation(async (params: DashboardRequestParams) => {+ params.onHistoryLimit?.(30);+ return [{ sentinel: "cut-to-30" }] as never;+ });+ await act(() => qc.refetchQueries({ queryKey: ["dashboard", "ws-1"], type: "active" }));+ await waitFor(() => expect(result.current.history.maxDays).toBe(30));+ const ninetyKey = dashboardUsageByAgentOptions("ws-1", 30, null, "UTC", 90).queryKey;+ expect(qc.getQueryData(ninetyKey)).not.toEqual([{ sentinel: "cut-to-30" }]);++ // Upgrading back must fetch the 90-day key again, not reuse the cut rows.+ setPlanLimit(90);+ api.getDashboardUsageByAgent.mockImplementation(async (params: DashboardRequestParams) => {+ params.onHistoryLimit?.(90);+ return [{ sentinel: "full-90" }] as never;+ });+ await act(() => qc.invalidateQueries({ queryKey: ["workspace-features", "ws-1"] }));+ await waitFor(() => expect(result.current.history.maxDays).toBe(90));+ await waitFor(() => expect(result.current.query.data).toEqual([{ sentinel: "full-90" }]));+ });+});diff --git a/packages/core/dashboard/history-limit.ts b/packages/core/dashboard/history-limit.tsnew file mode 100644index 0000000000..ca2a398ae0--- /dev/null+++ b/packages/core/dashboard/history-limit.ts@@ -0,0 +1,127 @@+import { skipToken, useQuery, type QueryClient } from "@tanstack/react-query";+import { workspaceFeatureKeys, workspaceFeaturesOptions } from "../billing/paid-features";++/**+ * Dashboard history limit (MUL-9490).+ *+ * The plan caps how many calendar days back the dashboard can read. The+ * server cuts every dashboard response to it and reports it in a response+ * header; GET /features reports it ahead of time so the range menu can lock+ * what the plan does not cover. Both are null unless the limit is enforced, so+ * an observed rollout changes nothing users see.+ *+ * The features read is cached, so a plan that changes while the page is open+ * (a trial ending, a downgrade, an upgrade elsewhere) first shows up in a+ * dashboard response. That response's limit is recorded here and the features+ * read is refreshed; until the refresh lands the smaller of the two applies,+ * so the page never labels a range the server is already cutting short.+ */++export const dashboardHistoryObservedKey = (wsId: string) =>+ ["dashboard-history-observed", wsId] as const;++/** The limit a dashboard response was last served under, and when. */+export interface ObservedDashboardHistoryLimit {+ limitDays: number | null;+ observedAt: number;+}++/**+ * A dashboard response was served under a stricter limit than its query was+ * made under. Its rows cover less than the query's key promises, so the query+ * fails instead of caching them; the page has already moved to the stricter+ * limit's key by then.+ */+export class DashboardHistoryLimitTightenedError extends Error {+ constructor(+ readonly requestedUnder: number | null,+ readonly served: number,+ ) {+ super(`dashboard history limit tightened from ${requestedUnder ?? "none"} to ${served} days`);+ this.name = "DashboardHistoryLimitTightenedError";+ }+}++export function isDashboardHistoryLimitTightened(error: unknown): boolean {+ return error instanceof DashboardHistoryLimitTightenedError;+}++/** Whether `a` allows fewer days than `b`, where null means no limit. */+export function isStricterHistoryLimit(a: number | null, b: number | null): boolean {+ if (a === null) return false;+ return b === null || a < b;+}++/**+ * Called with the limit each dashboard response was served under.+ * `requestedUnder` is the limit the query was made under; any difference means+ * the client's view of the plan is out of date.+ *+ * Until a features read newer than the first such response confirms the plan,+ * later responses can only tighten what was observed, never loosen it: a+ * response served under the old, looser policy can still arrive after one+ * served under the new one, and must not reopen ranges the plan no longer+ * covers.+ */+export function reportDashboardHistoryLimit(+ client: QueryClient,+ wsId: string,+ requestedUnder: number | null,+ served: number | null,+): void {+ if (served === requestedUnder) return;+ const key = dashboardHistoryObservedKey(wsId);+ const previous = client.getQueryData<ObservedDashboardHistoryLimit>(key);+ const featuresUpdatedAt =+ client.getQueryState(workspaceFeatureKeys.all(wsId))?.dataUpdatedAt ?? 0;+ const pending = previous !== undefined && previous.observedAt > featuresUpdatedAt;+ client.setQueryData<ObservedDashboardHistoryLimit>(key, {+ limitDays: pending ? minHistoryLimit(previous.limitDays, served) : served,+ observedAt: Date.now(),+ });+ void client.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });+}++/** The tighter of two limits, where null means none. */+export function minHistoryLimit(a: number | null, b: number | null): number | null {+ if (a === null) return b;+ if (b === null) return a;+ return Math.min(a, b);+}++/**+ * The limit to apply: the features read, tightened by a dashboard response+ * that arrived after it. Once the features read is newer than the+ * observation, it alone decides, so an upgrade lifts the limit again.+ */+export function resolveDashboardHistoryLimit(+ featureLimit: number | null,+ featuresUpdatedAt: number,+ observed: ObservedDashboardHistoryLimit | undefined,+): number | null {+ if (!observed || observed.observedAt <= featuresUpdatedAt) return featureLimit;+ return minHistoryLimit(featureLimit, observed.limitDays);+}++export interface DashboardHistoryLimitState {+ /** False until the features read has answered, successfully or not. */+ ready: boolean;+ /** The enforced limit in days, or null for none. */+ maxDays: number | null;+}++export function useDashboardHistoryLimit(wsId: string): DashboardHistoryLimitState {+ const features = useQuery(workspaceFeaturesOptions(wsId));+ const observed = useQuery<ObservedDashboardHistoryLimit>({+ queryKey: dashboardHistoryObservedKey(wsId),+ queryFn: skipToken,+ staleTime: Infinity,+ });+ const featureLimit = features.data?.limits?.dashboardHistoryDays ?? null;+ return {+ // A failed read counts as answered: the server still cuts every response,+ // and a dashboard that waited on it would never load.+ ready: !features.isPending,+ maxDays: resolveDashboardHistoryLimit(featureLimit, features.dataUpdatedAt, observed.data),+ };+}diff --git a/packages/core/dashboard/index.ts b/packages/core/dashboard/index.tsindex a9646e3da5..956c8b825a 100644--- a/packages/core/dashboard/index.ts+++ b/packages/core/dashboard/index.ts@@ -1,2 +1,3 @@export * from "./queries";export * from "./failure-class";+export * from "./history-limit";diff --git a/packages/core/dashboard/queries.test.ts b/packages/core/dashboard/queries.test.tsindex 5b8ff56a9d..75e37ea310 100644--- a/packages/core/dashboard/queries.test.ts+++ b/packages/core/dashboard/queries.test.ts@@ -45,8 +45,8 @@ describe("dashboard range placeholders", () => {"keeps the previous %s result when only the day range changes",(buildOptions) => {const previous = [{ sentinel: "30d" }];- const previousOptions = buildOptions("ws-1", 30, null, "UTC");- const nextOptions = buildOptions("ws-1", 7, null, "UTC");+ const previousOptions = buildOptions("ws-1", 30, null, "UTC", null);+ const nextOptions = buildOptions("ws-1", 7, null, "UTC", null);expect(resolvePlaceholder(nextOptions, previous, previousOptions.queryKey),@@ -54,13 +54,14 @@ describe("dashboard range placeholders", () => {},);- it("does not carry placeholder data across workspace, project, or timezone scopes", () => {+ it("does not carry placeholder data across workspace, project, timezone, or history-limit scopes", () => {const previous = [{ sentinel: "previous-scope" }];const nextOptions = dashboardUsageDailyOptions("ws-1",7,"project-1","Asia/Shanghai",+ null,);const previousScopes = [dashboardUsageDailyOptions(@@ -68,9 +69,12 @@ describe("dashboard range placeholders", () => {30,"project-1","Asia/Shanghai",+ null,),- dashboardUsageDailyOptions("ws-1", 30, "project-2", "Asia/Shanghai"),- dashboardUsageDailyOptions("ws-1", 30, "project-1", "UTC"),+ dashboardUsageDailyOptions("ws-1", 30, "project-2", "Asia/Shanghai", null),+ dashboardUsageDailyOptions("ws-1", 30, "project-1", "UTC", null),+ // A tightened plan limit: the 90-day result is outside the new plan.+ dashboardUsageDailyOptions("ws-1", 30, "project-1", "Asia/Shanghai", 30),];for (const previousOptions of previousScopes) {@@ -81,8 +85,18 @@ describe("dashboard range placeholders", () => {});it("keeps the initial loading state honest when there is no previous query", () => {- const options = dashboardUsageDailyOptions("ws-1", 30, null, "UTC");+ const options = dashboardUsageDailyOptions("ws-1", 30, null, "UTC", null);expect(resolvePlaceholder(options, undefined, undefined)).toBeUndefined();});});++describe("dashboard history limit in queries", () => {+ it.each(optionBuilders)("waits for the limit and keys %s on it", (buildOptions) => {+ expect(buildOptions("ws-1", 30, null, "UTC", undefined).enabled).toBe(false);+ expect(buildOptions("ws-1", 30, null, "UTC", null).enabled).toBe(true);+ expect(buildOptions("ws-1", 30, null, "UTC", 30).queryKey).not.toEqual(+ buildOptions("ws-1", 30, null, "UTC", 90).queryKey,+ );+ });+});diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.tsindex ca06ede433..3ca35e3671 100644--- a/packages/core/dashboard/queries.ts+++ b/packages/core/dashboard/queries.ts@@ -1,5 +1,37 @@-import { keepPreviousData, queryOptions } from "@tanstack/react-query";+import { keepPreviousData, queryOptions, type QueryClient } from "@tanstack/react-query";import { api } from "../api";+import type { DashboardRequestParams } from "../api/client";+import {+ DashboardHistoryLimitTightenedError,+ isDashboardHistoryLimitTightened,+ isStricterHistoryLimit,+ reportDashboardHistoryLimit,+} from "./history-limit";++/**+ * The plan's history limit a dashboard query is made under: a day count, null+ * for none, or undefined while it is still loading. Every key carries it, so a+ * plan change is a new key: no cached result or placeholder from the old limit+ * is shown under the new one (MUL-9490).+ */+export type DashboardHistoryLimitParam = number | null | undefined;++type DashboardKeyPart =+ | "daily"+ | "by-agent"+ | "agent-runtime"+ | "runtime-daily"+ | "failures-daily"+ | "failures-by-agent";++const dashboardKey = (+ wsId: string,+ part: DashboardKeyPart,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit: DashboardHistoryLimitParam = null,+) => ["dashboard", wsId, part, days, projectId, tz, historyLimit ?? null] as const;export const dashboardKeys = {all: (wsId: string) => ["dashboard", wsId] as const,@@ -8,38 +40,43 @@ export const dashboardKeys = {days: number,projectId: string | null,tz: string,- ) => [...dashboardKeys.all(wsId), "daily", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "daily", days, projectId, tz, historyLimit),byAgent: (wsId: string,days: number,projectId: string | null,tz: string,- ) => [...dashboardKeys.all(wsId), "by-agent", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "by-agent", days, projectId, tz, historyLimit),agentRuntime: (wsId: string,days: number,projectId: string | null,tz: string,- ) => [...dashboardKeys.all(wsId), "agent-runtime", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "agent-runtime", days, projectId, tz, historyLimit),runTimeDaily: (wsId: string,days: number,projectId: string | null,tz: string,- ) => [...dashboardKeys.all(wsId), "runtime-daily", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "runtime-daily", days, projectId, tz, historyLimit),failuresDaily: (wsId: string,days: number,projectId: string | null,tz: string,- ) => [...dashboardKeys.all(wsId), "failures-daily", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "failures-daily", days, projectId, tz, historyLimit),failuresByAgent: (wsId: string,days: number,projectId: string | null,tz: string,- ) =>- [...dashboardKeys.all(wsId), "failures-by-agent", days, projectId, tz] as const,+ historyLimit?: DashboardHistoryLimitParam,+ ) => dashboardKey(wsId, "failures-by-agent", days, projectId, tz, historyLimit),};// The server materializes these rollups on a 5-minute cadence, so a mounted@@ -53,7 +90,8 @@ const REFETCH_INTERVAL = 5 * 60 * 1000;// Range changes should keep the previous result mounted so KPI cards and// charts transition in place instead of falling back to a full-page skeleton.// Scope changes are deliberately excluded: carrying data across workspaces,-// projects, report kinds, or timezones would briefly display the wrong data.+// projects, report kinds, timezones or history limits would briefly display+// the wrong data — under a tightened limit, a range the plan no longer covers.function isSameDashboardScope(previousKey: readonly unknown[] | undefined,nextKey: readonly unknown[],@@ -64,58 +102,101 @@ function isSameDashboardScope();}+type DashboardFetcher<T> = (params: DashboardRequestParams) => Promise<T[]>;+// `tz` participates in every dashboard key so a Preferences change// repoints the cache. Every series — token rollups and the// atq.completed_at-based run-time / failure series — slices its day boundary// in the viewer's tz, so all the dashboard tabs always agree.-export function dashboardUsageDailyOptions(+//+// A query waits until the history limit is known (`historyLimit` defined), so+// the first load is not fetched once under no limit and again under the real+// one. Each response reports the limit it was served under; one that differs+// from the limit this query was made under means the plan changed while the+// page was open, and reportDashboardHistoryLimit refreshes it. A response cut+// to a stricter limit than its key fails the query rather than caching rows+// that cover less than the key says.+function dashboardOptions<T>(+ part: DashboardKeyPart,+ fetcher: DashboardFetcher<T>,wsId: string,days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.daily(wsId, days, projectId, tz);+ const queryKey = dashboardKey(wsId, part, days, projectId, tz, historyLimit);return queryOptions({queryKey,- queryFn: () =>- api.getDashboardUsageDaily({+ queryFn: async ({ client }: { client: QueryClient }) => {+ const requestedUnder = historyLimit ?? null;+ let served: number | null | undefined;+ const rows = await fetcher({days,project_id: projectId ?? undefined,tz,- }),- enabled: !!wsId,+ onHistoryLimit: (limit) => {+ served = limit;+ },+ });+ if (served !== undefined) {+ reportDashboardHistoryLimit(client, wsId, requestedUnder, served);+ // Rows cut to a stricter limit than this key promises must not be+ // cached under it, or restoring the looser limit would show them.+ if (served !== null && isStricterHistoryLimit(served, requestedUnder)) {+ throw new DashboardHistoryLimitTightenedError(requestedUnder, served);+ }+ }+ return rows;+ },+ enabled: !!wsId && historyLimit !== undefined,+ // The app default retries once; a tightened limit is not transient, and+ // the page re-queries under the stricter key on its own.+ retry: (failureCount: number, error: Error) =>+ !isDashboardHistoryLimitTightened(error) && failureCount < 1,staleTime: STALE_TIME,refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>+ placeholderData: (previousData: T[] | undefined, previousQuery) =>isSameDashboardScope(previousQuery?.queryKey, queryKey)? keepPreviousData(previousData): undefined,});}+export function dashboardUsageDailyOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit: DashboardHistoryLimitParam,+) {+ return dashboardOptions(+ "daily",+ (params) => api.getDashboardUsageDaily(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );+}+export function dashboardUsageByAgentOptions(wsId: string,days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.byAgent(wsId, days, projectId, tz);- return queryOptions({- queryKey,- queryFn: () =>- api.getDashboardUsageByAgent({- days,- project_id: projectId ?? undefined,- tz,- }),- enabled: !!wsId,- staleTime: STALE_TIME,- refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>- isSameDashboardScope(previousQuery?.queryKey, queryKey)- ? keepPreviousData(previousData)- : undefined,- });+ return dashboardOptions(+ "by-agent",+ (params) => api.getDashboardUsageByAgent(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );}export function dashboardAgentRunTimeOptions(@@ -123,24 +204,17 @@ export function dashboardAgentRunTimeOptions(days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.agentRuntime(wsId, days, projectId, tz);- return queryOptions({- queryKey,- queryFn: () =>- api.getDashboardAgentRunTime({- days,- project_id: projectId ?? undefined,- tz,- }),- enabled: !!wsId,- staleTime: STALE_TIME,- refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>- isSameDashboardScope(previousQuery?.queryKey, queryKey)- ? keepPreviousData(previousData)- : undefined,- });+ return dashboardOptions(+ "agent-runtime",+ (params) => api.getDashboardAgentRunTime(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );}export function dashboardRunTimeDailyOptions(@@ -148,24 +222,17 @@ export function dashboardRunTimeDailyOptions(days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.runTimeDaily(wsId, days, projectId, tz);- return queryOptions({- queryKey,- queryFn: () =>- api.getDashboardRunTimeDaily({- days,- project_id: projectId ?? undefined,- tz,- }),- enabled: !!wsId,- staleTime: STALE_TIME,- refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>- isSameDashboardScope(previousQuery?.queryKey, queryKey)- ? keepPreviousData(previousData)- : undefined,- });+ return dashboardOptions(+ "runtime-daily",+ (params) => api.getDashboardRunTimeDaily(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );}export function dashboardFailuresDailyOptions(@@ -173,24 +240,17 @@ export function dashboardFailuresDailyOptions(days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.failuresDaily(wsId, days, projectId, tz);- return queryOptions({- queryKey,- queryFn: () =>- api.getDashboardFailuresDaily({- days,- project_id: projectId ?? undefined,- tz,- }),- enabled: !!wsId,- staleTime: STALE_TIME,- refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>- isSameDashboardScope(previousQuery?.queryKey, queryKey)- ? keepPreviousData(previousData)- : undefined,- });+ return dashboardOptions(+ "failures-daily",+ (params) => api.getDashboardFailuresDaily(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );}export function dashboardFailuresByAgentOptions(@@ -198,22 +258,15 @@ export function dashboardFailuresByAgentOptions(days: number,projectId: string | null,tz: string,+ historyLimit: DashboardHistoryLimitParam,) {- const queryKey = dashboardKeys.failuresByAgent(wsId, days, projectId, tz);- return queryOptions({- queryKey,- queryFn: () =>- api.getDashboardFailuresByAgent({- days,- project_id: projectId ?? undefined,- tz,- }),- enabled: !!wsId,- staleTime: STALE_TIME,- refetchInterval: REFETCH_INTERVAL,- placeholderData: (previousData, previousQuery) =>- isSameDashboardScope(previousQuery?.queryKey, queryKey)- ? keepPreviousData(previousData)- : undefined,- });+ return dashboardOptions(+ "failures-by-agent",+ (params) => api.getDashboardFailuresByAgent(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ );}diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.tsindex 8e970faa58..b43359e3d8 100644--- a/packages/core/feature-flags/index.ts+++ b/packages/core/feature-flags/index.ts@@ -20,6 +20,7 @@ export { ChainProvider } from "./chain-provider";export {BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,COMPOSIO_MCP_APPS_FLAG,+ DASHBOARD_HISTORY_365D_FLAG,DOCS_V1_FLAG,PLUGINS_V1_FLAG,WORKSPACE_GUESTS_FLAG,diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.tsindex 0f02e418f3..ad017bf3c9 100644--- a/packages/core/feature-flags/keys.ts+++ b/packages/core/feature-flags/keys.ts@@ -8,3 +8,7 @@ export const BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG =// guests (always on self-host; on Cloud once billing launches), and the plan// then decides through the "guests" paid feature.export const WORKSPACE_GUESTS_FLAG = "workspace_guests";+// The 365-day range on the workspace dashboard (MUL-9490). Servers that+// support it publish it on by default; a missing key reads as off, so the+// range is never offered to a server that predates it.+export const DASHBOARD_HISTORY_365D_FLAG = "dashboard_history_365d";diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 960f9f145a..59dd562c3a 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -219,6 +219,8 @@ export interface WorkspaceSubscriptionEntitlements {autopilotRuns: WorkspaceEntitlementLimit;/** Attachment storage in bytes (MUL-9489); absent from older Cloud. */storageBytes?: WorkspaceEntitlementLimit | null;+ /** Dashboard history range in days. Null when Cloud did not send it. */+ dashboardHistoryDays?: WorkspaceEntitlementLimit | null;};currentPeriodEnd: string | null;snapshotExpiresAt: string | null;@@ -342,8 +344,22 @@ export interface WorkspaceSubscriptionPrices {* on a cloud that predates add-ons.*/autopilotAddon: WorkspaceAutopilotAddonPrice | null;+ /**+ * Each plan's limits, from the same configuration Cloud enforces. Null when+ * Cloud did not send them (an older Cloud) or they could not be read.+ */+ planLimits?: WorkspacePlanLimits | null;+}++export type WorkspacePlanLimitPlan = "free" | WorkspaceSubscriptionPaidPlan;++export interface WorkspacePlanLimit {+ /** Calendar days the dashboard can read on this plan; null when unknown. */+ dashboardHistoryDays: number | null;}+export type WorkspacePlanLimits = Record<WorkspacePlanLimitPlan, WorkspacePlanLimit>;+/** Autopilot runs bought this month, valid until the month ends. */export interface WorkspaceAutopilotAddonSummary {purchasedRuns: number;@@ -526,6 +542,19 @@ export type WorkspaceFeatureState = "available" | "locked";export interface WorkspaceFeatures {features: Partial<Record<PaidFeature, WorkspaceFeatureState>>;+ /**+ * Numeric plan limits the server applies. The API client always fills it;+ * optional so hand-built values (tests, older caches) need not.+ */+ limits?: WorkspaceFeatureLimits;+}++export interface WorkspaceFeatureLimits {+ /**+ * How many calendar days back the dashboard can read (MUL-9490). Null when+ * nothing is enforced: off, observed, or self-hosted.+ */+ dashboardHistoryDays: number | null;}/**diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex b70cde9309..a21bc46fd1 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -415,6 +415,9 @@ export type {WorkspaceSubscriptionPrice,WorkspaceSubscriptionPlanPrices,WorkspaceSubscriptionPrices,+ WorkspacePlanLimitPlan,+ WorkspacePlanLimit,+ WorkspacePlanLimits,WorkspaceAutopilotAddonSummary,WorkspaceAutopilotAddonPrice,CreateWorkspaceAutopilotAddonCheckoutRequest,@@ -439,6 +442,7 @@ export type {PaidFeature,WorkspaceFeatureState,WorkspaceFeatures,+ WorkspaceFeatureLimits,MemberLimit,StorageUsage,} from "./billing";diff --git a/packages/views/dashboard/components/dashboard-filters.tsx b/packages/views/dashboard/components/dashboard-filters.tsxindex e39bce3d0a..4b34a4bebf 100644--- a/packages/views/dashboard/components/dashboard-filters.tsx+++ b/packages/views/dashboard/components/dashboard-filters.tsx@@ -1,6 +1,6 @@"use client";-import { CalendarDays, ChevronDown, FolderKanban } from "@multica/ui/icons";+import { CalendarDays, ChevronDown, FolderKanban, Lock } from "@multica/ui/icons";import { Button } from "@multica/ui/components/ui/button";import {DropdownMenu,@@ -8,10 +8,17 @@ import {DropdownMenuContent,DropdownMenuRadioGroup,DropdownMenuRadioItem,+ DropdownMenuSeparator,} from "@multica/ui/components/ui/dropdown-menu";import { ProjectIcon } from "../../projects/components/project-icon";import { useT } from "../../i18n";-import { ALL_PROJECTS, TIME_RANGES, type TimeRange } from "./dashboard-shared";+import {+ ALL_PROJECTS,+ TIME_RANGES,+ type TimeRange,+ type TimeRangeOption,+} from "./dashboard-shared";+import { isRangeAllowed, type UpgradePlan } from "../history-range";type DashboardProject = { id: string; title: string; icon: string | null };@@ -26,16 +33,30 @@ type DashboardProject = { id: string; title: string; icon: string | null };** No "clear" entry: the range is a required parameter of every query on the* page, so it has no empty value to return to.+ *+ * Under a plan's history limit (`maxDays`, MUL-9490) the longer ranges stay+ * listed but locked, each marked with the plan that covers it when that is+ * known, and the menu ends with a note and a way to the plans. Admins and+ * members see the same menu. `onViewPlans` is null where billing is off.*/export function TimeRangeFilter({days,onChange,+ maxDays = null,+ planForDays = () => null,+ onViewPlans = null,+ ranges = TIME_RANGES,}: {days: TimeRange;onChange: (days: TimeRange) => void;+ maxDays?: number | null;+ planForDays?: (days: TimeRange) => UpgradePlan | null;+ onViewPlans?: (() => void) | null;+ ranges?: readonly TimeRangeOption[];}) {const { t } = useT("usage");- const current = TIME_RANGES.find((r) => r.days === days) ?? TIME_RANGES[2];+ const current = ranges.find((r) => r.days === days) ?? TIME_RANGES[2];+ const hasLocked = ranges.some((r) => !isRangeAllowed(r.days, maxDays));return (<DropdownMenu>@@ -53,21 +74,54 @@ export function TimeRangeFilter({</Button>}/>- <DropdownMenuContent align="end" className="w-auto min-w-32">+ <DropdownMenuContent align="end" className={hasLocked ? "w-64" : "w-auto min-w-32"}><DropdownMenuRadioGroupvalue={String(days)}- onValueChange={(value) => onChange(Number(value) as TimeRange)}+ onValueChange={(value) => {+ const next = Number(value) as TimeRange;+ if (isRangeAllowed(next, maxDays)) onChange(next);+ }}>- {TIME_RANGES.map((range) => (- <DropdownMenuRadioItem- key={range.days}- value={String(range.days)}- className="tabular-nums"- >- {range.label}- </DropdownMenuRadioItem>- ))}+ {ranges.map((range) => {+ const allowed = isRangeAllowed(range.days, maxDays);+ const plan = allowed ? null : planForDays(range.days);+ return (+ <DropdownMenuRadioItem+ key={range.days}+ value={String(range.days)}+ disabled={!allowed}+ className="tabular-nums"+ >+ <span className="flex-1">{range.label}</span>+ {allowed ? null : (+ <span className="ml-3 flex shrink-0 items-center gap-1 text-caption text-muted-foreground">+ <Lock className="size-3" aria-hidden="true" />+ {plan ? (+ <span>{t(($) => $.history_limit.plan[plan])}</span>+ ) : (+ <span className="sr-only">{t(($) => $.history_limit.locked)}</span>+ )}+ </span>+ )}+ </DropdownMenuRadioItem>+ );+ })}</DropdownMenuRadioGroup>+ {hasLocked && maxDays !== null ? (+ <>+ <DropdownMenuSeparator />+ <div className="flex flex-col gap-2 px-2 py-1.5">+ <p className="text-caption text-muted-foreground">+ {t(($) => $.history_limit.note, { days: maxDays })}+ </p>+ {onViewPlans ? (+ <Button variant="outline" size="sm" className="w-full" onClick={onViewPlans}>+ {t(($) => $.history_limit.view_plans)}+ </Button>+ ) : null}+ </div>+ </>+ ) : null}</DropdownMenuContent></DropdownMenu>);diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsxindex c7dfa975d8..51e5f62a32 100644--- a/packages/views/dashboard/components/dashboard-page.test.tsx+++ b/packages/views/dashboard/components/dashboard-page.test.tsx@@ -29,6 +29,13 @@ const restrictedBucketRef = vi.hoisted(() => ({ current: false }));const runtimeMeteredCountRef = vi.hoisted(() => ({current: undefined as number | undefined,}));+// The plan's enforced dashboard history limit GET /features reports+// (MUL-9490). Null is no limit, the self-hosted and observed case.+const historyLimitRef = vi.hoisted(() => ({ current: null as number | null }));+// Plan limits from GET /prices, which label the locked ranges.+const planLimitsRef = vi.hoisted(() => ({+ current: null as null | Record<string, { dashboardHistoryDays: number | null }>,+}));// Kept out of the fixture ternary so the sentinel's shape reads at a glance.// Unlike the deleted-agents bucket this one carries real seconds / tasks: the@@ -75,6 +82,25 @@ vi.mock("@tanstack/react-query", async () => {useQueryClient: () => ({ invalidateQueries: vi.fn() }),useQuery: (opts: { queryKey: unknown[] }) => {queryKeys.push(opts.queryKey);+ if (opts.queryKey[0] === "workspace-features") {+ return {+ data: { features: {}, limits: { dashboardHistoryDays: historyLimitRef.current } },+ isPending: false,+ isSuccess: true,+ dataUpdatedAt: 1,+ };+ }+ if (opts.queryKey[0] === "dashboard-history-observed") {+ return { data: undefined, isPending: true };+ }+ if (opts.queryKey[0] === "workspace-subscriptions") {+ return {+ data: planLimitsRef.current+ ? { pro: {}, business: {}, planLimits: planLimitsRef.current }+ : undefined,+ isPending: false,+ };+ }if (dashboardDataRef.current) {// ["workspaces", wsId, "agents"] — needed so the Errors breakdown can// resolve agent-1 to a name and render its drill-down link.@@ -215,6 +241,13 @@ vi.mock("@tanstack/react-query", async () => {};});+const billingEnabledRef = vi.hoisted(() => ({ current: true }));+const yearRangeEnabledRef = vi.hoisted(() => ({ current: true }));+vi.mock("@multica/core/config", () => ({+ useFeatureEnabled: (key: string) =>+ key === "dashboard_history_365d" ? yearRangeEnabledRef.current : billingEnabledRef.current,+}));+vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));@@ -228,6 +261,7 @@ vi.mock("@multica/core/api", () => ({vi.mock("@multica/core/paths", () => ({useWorkspacePaths: () => ({agentDetail: (id: string) => `/acme/agents/${id}`,+ settings: () => "/acme/settings",}),}));@@ -326,12 +360,12 @@ describe("DashboardPage — viewing timezone drives the query key", () => {cleanup();});- // The `tz` segment is the last element of every dashboard key- // (see dashboardKeys in @multica/core/dashboard/queries).+ // The `tz` segment sits after the project in every dashboard key, before+ // the history limit (see dashboardKeys in @multica/core/dashboard/queries).function tzSegments(): unknown[] {return queryKeys.filter((k) => k[0] === "dashboard")- .map((k) => k[k.length - 1]);+ .map((k) => k[5]);}it("uses the stored timezone in every dashboard query key", () => {@@ -892,3 +926,133 @@ describe("DashboardPage — leaderboard density", () => {});});});++describe("DashboardPage — plan history limit (MUL-9490)", () => {+ beforeEach(() => {+ queryKeys.length = 0;+ dashboardDataRef.current = true;+ manyAgentsRef.current = false;+ restrictedBucketRef.current = false;+ historyLimitRef.current = null;+ planLimitsRef.current = null;+ billingEnabledRef.current = true;+ yearRangeEnabledRef.current = true;+ tzRef.current = "UTC";+ cleanup();+ });+ afterEach(() => {+ historyLimitRef.current = null;+ planLimitsRef.current = null;+ });++ const daysInKeys = (part: string) =>+ queryKeys.filter((k) => k[0] === "dashboard" && k[2] === part).map((k) => k[3]);++ async function openRangeMenu(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole("button", { name: "Period" }));+ return screen.findByRole("menu");+ }++ it("offers 365 days and fetches 371 for its weekly chart when nothing is enforced", async () => {+ const user = userEvent.setup();+ renderDashboard();+ const menu = await openRangeMenu(user);+ const option = within(menu).getByRole("menuitemradio", { name: /365d/ });+ expect(option).not.toHaveAttribute("aria-disabled", "true");+ expect(within(menu).queryByText(/Your plan covers/)).toBeNull();++ queryKeys.length = 0;+ await user.click(option);+ expect(daysInKeys("daily")).toContain(371);+ expect(daysInKeys("by-agent")).toContain(365);+ });++ it("leaves 365 days out until its flag is on", async () => {+ yearRangeEnabledRef.current = false;+ historyLimitRef.current = 30;+ const user = userEvent.setup();+ renderDashboard();+ const menu = await openRangeMenu(user);+ expect(within(menu).queryByRole("menuitemradio", { name: /365d/ })).toBeNull();+ expect(within(menu).getByRole("menuitemradio", { name: /180d/ })).toHaveAttribute("aria-disabled", "true");+ expect(queryKeys.filter((k) => k[0] === "dashboard").every((k) => k[3] !== 365 && k[3] !== 371)).toBe(true);+ });++ it("locks ranges past the plan and labels the plan that covers each", async () => {+ historyLimitRef.current = 30;+ planLimitsRef.current = {+ free: { dashboardHistoryDays: 30 },+ pro: { dashboardHistoryDays: 90 },+ business: { dashboardHistoryDays: 365 },+ };+ const user = userEvent.setup();+ renderDashboard();+ const menu = await openRangeMenu(user);++ for (const label of ["1d", "7d", "30d"]) {+ expect(within(menu).getByRole("menuitemradio", { name: new RegExp(`^${label}`) })).not.toHaveAttribute(+ "aria-disabled",+ "true",+ );+ }+ expect(within(menu).getByRole("menuitemradio", { name: /90d/ })).toHaveAttribute("aria-disabled", "true");+ expect(within(menu).getByRole("menuitemradio", { name: /90d/ })).toHaveTextContent("Pro");+ expect(within(menu).getByRole("menuitemradio", { name: /180d/ })).toHaveTextContent("Business");+ expect(within(menu).getByRole("menuitemradio", { name: /365d/ })).toHaveTextContent("Business");+ expect(menu).toHaveTextContent("Your plan covers the last 30 days.");+ expect(within(menu).getByRole("button", { name: "View plans" })).toBeInTheDocument();+ // Every query is keyed on the limit it is made under.+ expect(queryKeys.filter((k) => k[0] === "dashboard").every((k) => k[6] === 30)).toBe(true);+ });++ it("labels plans from the configured limits, not a fixed table", async () => {+ historyLimitRef.current = 30;+ planLimitsRef.current = {+ free: { dashboardHistoryDays: 30 },+ pro: { dashboardHistoryDays: 180 },+ business: { dashboardHistoryDays: 365 },+ };+ const user = userEvent.setup();+ renderDashboard();+ const menu = await openRangeMenu(user);+ expect(within(menu).getByRole("menuitemradio", { name: /180d/ })).toHaveTextContent("Pro");+ expect(within(menu).getByRole("menuitemradio", { name: /365d/ })).toHaveTextContent("Business");+ });++ it("shows only the lock when plan limits are unavailable, and no button without billing", async () => {+ historyLimitRef.current = 30;+ billingEnabledRef.current = false;+ const user = userEvent.setup();+ renderDashboard();+ const menu = await openRangeMenu(user);+ const option = within(menu).getByRole("menuitemradio", { name: /90d/ });+ expect(option).toHaveAttribute("aria-disabled", "true");+ expect(option).not.toHaveTextContent("Pro");+ expect(option).not.toHaveTextContent("Business");+ expect(menu).toHaveTextContent("Your plan covers the last 30 days.");+ expect(within(menu).queryByRole("button", { name: "View plans" })).toBeNull();+ });++ it("reads the longest range the plan covers after a downgrade, and restores the pick on upgrade", async () => {+ const user = userEvent.setup();+ const view = renderDashboard();+ const menu = await openRangeMenu(user);+ await user.click(within(menu).getByRole("menuitemradio", { name: /90d/ }));+ expect(screen.getByRole("button", { name: "Period" })).toHaveTextContent("90d");++ // The trial ends: the limit drops to 30 while the page is open.+ historyLimitRef.current = 30;+ queryKeys.length = 0;+ view.rerender(<DashboardHarness />);+ expect(screen.getByRole("button", { name: "Period" })).toHaveTextContent("30d");+ expect(daysInKeys("by-agent")).toEqual(expect.arrayContaining([30]));+ expect(daysInKeys("by-agent")).not.toContain(90);+ expect(daysInKeys("daily")).toContain(35);+ expect(screen.getByText(/Cost · 30D/)).toBeInTheDocument();++ // An upgrade lifts it; the reader's pick comes back.+ historyLimitRef.current = null;+ view.rerender(<DashboardHarness />);+ expect(screen.getByRole("button", { name: "Period" })).toHaveTextContent("90d");+ });+});diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex a4f9842ee4..b217aaed67 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { BarChart3, RefreshCw } from "@multica/ui/icons";import { useQuery, useQueryClient } from "@tanstack/react-query";import { IconButton } from "@multica/ui/components/common/icon-button";@@ -12,6 +12,13 @@ import {NumberFlow,} from "@multica/ui/components/ui/number-flow";import { useWorkspaceId } from "@multica/core/hooks";+import { useFeatureEnabled } from "@multica/core/config";+import {+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,+ DASHBOARD_HISTORY_365D_FLAG,+} from "@multica/core/feature-flags";+import { workspaceSubscriptionPricesOptions } from "@multica/core/billing";+import { useWorkspacePaths } from "@multica/core/paths";import type { Agent } from "@multica/core/types";import { agentListOptions } from "@multica/core/workspace/queries";import { projectListOptions } from "@multica/core/projects/queries";@@ -23,7 +30,9 @@ import {dashboardRunTimeDailyOptions,dashboardFailuresDailyOptions,dashboardFailuresByAgentOptions,+ useDashboardHistoryLimit,} from "@multica/core/dashboard";+import { toast } from "sonner";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import { useViewingTimezone } from "../../common/use-viewing-timezone";import { CollectionPageState } from "../../layout/collection-page";@@ -68,6 +77,13 @@ import { ProjectFilter, TimeRangeFilter } from "./dashboard-filters";import { UsageTrendCard } from "./usage-trend-card";import { Leaderboard } from "./leaderboard";import { ErrorsTab } from "./errors-tab";+import {+ earliestReadableDay,+ effectiveRange,+ isRangeAllowed,+ planForRange,+} from "../history-range";+import { dashboardTimeRanges } from "./dashboard-shared";// Stable references — `data ?? []` would create a new empty array on// every render while the query is loading, which breaks useMemo's@@ -153,7 +169,48 @@ export function DashboardPage() {const viewTZ = useViewingTimezone();const navigation = useNavigation();const locales = i18n.resolvedLanguage ?? i18n.language;- const [days, setDays] = useState<TimeRange>(30);+ // What the reader picked. The page reads `days`, the longest range the plan+ // covers up to that pick (MUL-9490), derived rather than written back so an+ // upgrade restores the pick.+ const [selectedDays, setSelectedDays] = useState<TimeRange>(30);+ const history = useDashboardHistoryLimit(wsId);+ const ranges = dashboardTimeRanges(useFeatureEnabled(DASHBOARD_HISTORY_365D_FLAG, false));+ const days = effectiveRange(selectedDays, history.maxDays, ranges);+ // Every dashboard query waits for the limit and is keyed on it.+ const historyLimit = history.ready ? history.maxDays : undefined;+ const billingEnabled = useFeatureEnabled(BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG, false);+ const workspacePaths = useWorkspacePaths();+ const viewPlans = () => navigation.push(`${workspacePaths.settings()}?tab=billing`);+ // Plan labels on locked ranges come from the limits Cloud enforces; prices+ // are read only once a range is actually locked.+ const hasLockedRange = ranges.some((r) => !isRangeAllowed(r.days, history.maxDays));+ const { data: prices } = useQuery({+ ...workspaceSubscriptionPricesOptions(wsId),+ enabled: billingEnabled && hasLockedRange && wsId.length > 0,+ });+ const planLimits = prices?.planLimits ?? null;++ // A limit that tightens while the page is open (a trial ending, a+ // downgrade) moves the page to a shorter range. Say so once, rather than+ // letting the range change silently.+ const previousMaxDays = useRef<number | null | undefined>(undefined);+ useEffect(() => {+ const previous = previousMaxDays.current;+ previousMaxDays.current = history.ready ? history.maxDays : undefined;+ if (!history.ready || previous === undefined || history.maxDays === null) return;+ const tightened = previous === null || history.maxDays < previous;+ if (!tightened || isRangeAllowed(selectedDays, history.maxDays)) return;+ const message = t(($) => $.history_limit.fell_back, { days: history.maxDays });+ if (billingEnabled) {+ toast(message, {+ action: { label: t(($) => $.history_limit.view_plans), onClick: viewPlans },+ });+ } else {+ toast(message);+ }+ // Only a change in the limit announces anything.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [history.ready, history.maxDays]);const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);// One scroller for both tabs: the offset restored is the shown tab's.const restoreScrollRef = useRestoredScrollRef("dashboard");@@ -208,7 +265,7 @@ export function DashboardPage() {const chartFetchDays = weekCount * 7;const dailyQuery = useQuery(- dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ),+ dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),);// The three per-agent rollups carry no date, so `dailyCutoffIso` below// cannot trim them — their window is closed server-side at exactly `days`@@ -218,19 +275,19 @@ export function DashboardPage() {// and the Run time / Tasks KPIs silently widen by one day while the chart// and the Cost / Tokens KPIs beside them do not (MUL-5551).const byAgentQuery = useQuery(- dashboardUsageByAgentOptions(wsId, days, projectId, viewTZ),+ dashboardUsageByAgentOptions(wsId, days, projectId, viewTZ, historyLimit),);const runTimeQuery = useQuery(- dashboardAgentRunTimeOptions(wsId, days, projectId, viewTZ),+ dashboardAgentRunTimeOptions(wsId, days, projectId, viewTZ, historyLimit),);const runTimeDailyQuery = useQuery(- dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId, viewTZ),+ dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),);const failuresDailyQuery = useQuery(- dashboardFailuresDailyOptions(wsId, chartFetchDays, projectId, viewTZ),+ dashboardFailuresDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),);const failuresByAgentQuery = useQuery(- dashboardFailuresByAgentOptions(wsId, days, projectId, viewTZ),+ dashboardFailuresByAgentOptions(wsId, days, projectId, viewTZ, historyLimit),);const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;@@ -295,12 +352,13 @@ export function DashboardPage() {// two failure rollups, and a workspace with spend but no failures is not an// empty dashboard.const usageLoading =+ !history.ready ||dailyQuery.isLoading ||byAgentQuery.isLoading ||runTimeQuery.isLoading ||runTimeDailyQuery.isLoading;const errorsLoading =- failuresDailyQuery.isLoading || failuresByAgentQuery.isLoading;+ !history.ready || failuresDailyQuery.isLoading || failuresByAgentQuery.isLoading;const usageHasNoData =!usageLoading &&@@ -387,23 +445,31 @@ export function DashboardPage() {// pre-zeroed inside the helpers, so sparse weeks render as empty bars// instead of being dropped (MUL-2382 weekly window scoping). Week// boundaries follow the viewer's timezone.+ //+ // Under a plan limit the leftmost week can start before the first day the+ // plan covers; the server returns nothing for those days, and the week is+ // marked partial so the short bar is not read as a dip.+ const earliestDay = useMemo(+ () => earliestReadableDay(todayIso(viewTZ), history.maxDays, addDaysIso),+ [viewTZ, history.maxDays],+ );const weekly = useMemo(- () => aggregateByWeek(dailyUsage, viewTZ, weekCount),- [dailyUsage, viewTZ, weekCount],+ () => aggregateByWeek(dailyUsage, viewTZ, weekCount, earliestDay),+ [dailyUsage, viewTZ, weekCount, earliestDay],);const weeklyCost = weekly.weeklyCostStack;const weeklyTokens = weekly.weeklyTokens;const weeklyTime = useMemo(- () => aggregateWeeklyTime(runTimeDailyRows, viewTZ, weekCount),- [runTimeDailyRows, viewTZ, weekCount],+ () => aggregateWeeklyTime(runTimeDailyRows, viewTZ, weekCount, earliestDay),+ [runTimeDailyRows, viewTZ, weekCount, earliestDay],);const weeklyTasks = useMemo(- () => aggregateWeeklyTasks(runTimeDailyRows, viewTZ, weekCount),- [runTimeDailyRows, viewTZ, weekCount],+ () => aggregateWeeklyTasks(runTimeDailyRows, viewTZ, weekCount, earliestDay),+ [runTimeDailyRows, viewTZ, weekCount, earliestDay],);const weeklyErrors = useMemo(- () => aggregateWeeklyErrors(failureDailyRows, viewTZ, weekCount),- [failureDailyRows, viewTZ, weekCount],+ () => aggregateWeeklyErrors(failureDailyRows, viewTZ, weekCount, earliestDay),+ [failureDailyRows, viewTZ, weekCount, earliestDay],);const agentTokenRows = useMemo(() => aggregateAgentTokens(byAgentUsage),@@ -499,7 +565,14 @@ export function DashboardPage() {: tzLabel}</span>) : null}- <TimeRangeFilter days={days} onChange={setDays} />+ <TimeRangeFilter+ days={days}+ onChange={setSelectedDays}+ maxDays={history.maxDays}+ planForDays={(range) => planForRange(range, planLimits)}+ onViewPlans={billingEnabled ? viewPlans : null}+ ranges={ranges}+ /><ProjectFilterprojects={projects}projectValue={projectValue}diff --git a/packages/views/dashboard/components/dashboard-shared.tsx b/packages/views/dashboard/components/dashboard-shared.tsxindex a1ad05eef0..a56b4cbdba 100644--- a/packages/views/dashboard/components/dashboard-shared.tsx+++ b/packages/views/dashboard/components/dashboard-shared.tsx@@ -9,7 +9,7 @@ import { formatDuration } from "../utils";// Period selector — mirrors the runtime detail page so users see the same// option set across both dashboards. `dims` declares which chart dimensions// each range may be drawn at: 1d / 7d at the weekly grain collapse to a single-// bar, 180d at the daily grain is 180 unreadable bars.+// bar, 180d / 365d at the daily grain are hundreds of unreadable bars.//// 1d semantic: "today" (the natural calendar day from 00:00 in the viewer's// timezone), not "the last 24 hours". The `dailyCutoffIso` filter on the page@@ -20,9 +20,20 @@ export const TIME_RANGES = [{ label: "30d", days: 30, dims: ["daily", "weekly"] as const },{ label: "90d", days: 90, dims: ["daily", "weekly"] as const },{ label: "180d", days: 180, dims: ["weekly"] as const },+ { label: "365d", days: 365, dims: ["weekly"] as const },] as const;export type TimeRange = (typeof TIME_RANGES)[number]["days"];+export type TimeRangeOption = (typeof TIME_RANGES)[number];++/**+ * The ranges the dashboard offers. 365d follows the dashboard_history_365d+ * flag: on by default on servers that support it, and a kill switch should+ * the year-long queries be too slow for a deployment (MUL-9490).+ */+export function dashboardTimeRanges(allowYear: boolean): readonly TimeRangeOption[] {+ return allowYear ? TIME_RANGES : TIME_RANGES.filter((r) => r.days !== 365);+}export type Dim = "daily" | "weekly";/**diff --git a/packages/views/dashboard/history-range.test.ts b/packages/views/dashboard/history-range.test.tsnew file mode 100644index 0000000000..8d5aa22340--- /dev/null+++ b/packages/views/dashboard/history-range.test.ts@@ -0,0 +1,153 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { addDaysIso, aggregateByWeek, todayIso } from "../runtimes/utils";+import { aggregateWeeklyErrors, aggregateWeeklyTasks, aggregateWeeklyTime } from "./utils";+import { dashboardTimeRanges } from "./components/dashboard-shared";+import {+ earliestReadableDay,+ effectiveRange,+ isRangeAllowed,+ planForRange,+} from "./history-range";++const limits = (free: number | null, pro: number | null, business: number | null) => ({+ free: { dashboardHistoryDays: free },+ pro: { dashboardHistoryDays: pro },+ business: { dashboardHistoryDays: business },+});++describe("effectiveRange", () => {+ it("keeps the pick the plan covers and otherwise falls back to the longest that fits", () => {+ expect(effectiveRange(90, null)).toBe(90);+ expect(effectiveRange(365, null)).toBe(365);+ expect(effectiveRange(90, 90)).toBe(90);+ expect(effectiveRange(90, 30)).toBe(30);+ expect(effectiveRange(365, 90)).toBe(90);+ expect(effectiveRange(180, 100)).toBe(90);+ expect(effectiveRange(7, 30)).toBe(7);+ // A limit shorter than every multi-day range still leaves today.+ expect(effectiveRange(30, 3)).toBe(1);+ // Without the year range, a 365 pick reads the longest offered range.+ expect(effectiveRange(365, null, dashboardTimeRanges(false))).toBe(180);+ expect(effectiveRange(365, null, dashboardTimeRanges(true))).toBe(365);+ expect(isRangeAllowed(30, 30)).toBe(true);+ expect(isRangeAllowed(90, 30)).toBe(false);+ });+});++describe("planForRange", () => {+ it("names the cheapest paid plan whose history covers the range", () => {+ const standard = limits(30, 90, 365);+ expect(planForRange(90, standard)).toBe("pro");+ expect(planForRange(180, standard)).toBe("business");+ expect(planForRange(365, standard)).toBe("business");+ // Follows the configuration rather than a fixed table.+ expect(planForRange(180, limits(30, 180, 365))).toBe("pro");+ });++ it("names nothing it cannot back with a configured limit", () => {+ expect(planForRange(90, null)).toBeNull();+ expect(planForRange(90, undefined)).toBeNull();+ expect(planForRange(365, limits(30, 90, 180))).toBeNull();+ expect(planForRange(90, limits(30, null, 365))).toBe("business");+ });+});++describe("earliestReadableDay", () => {+ it("is the first of the last N days, or none", () => {+ expect(earliestReadableDay("2026-11-20", 30, addDaysIso)).toBe("2026-10-22");+ expect(earliestReadableDay("2026-11-20", 1, addDaysIso)).toBe("2026-11-20");+ expect(earliestReadableDay("2026-11-20", null, addDaysIso)).toBeNull();+ });+});++describe("weekly charts under a history limit", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ // Weekly charts start on Monday; today falls on either end of a week.+ it.each([+ // Wednesday: 30 days back is Tuesday 10-20, one day into the week of Mon 10-19.+ { now: "2026-11-18T12:00:00Z", firstWeek: "2026-10-19", covered: 6, lastCovered: 3 },+ // Sunday: 30 days back is Saturday 10-24, the last day of the week of Mon 10-19.+ { now: "2026-11-22T12:00:00Z", firstWeek: "2026-10-19", covered: 2, lastCovered: 7 },+ // Monday: the five weeks drawn start after 30 days back, so none is cut.+ { now: "2026-11-16T12:00:00Z", firstWeek: "2026-10-19", covered: 7, lastCovered: 1 },+ ])("marks the leftmost week partial when the plan cuts into it ($now)", ({ now, firstWeek, covered, lastCovered }) => {+ vi.setSystemTime(new Date(now));+ const today = todayIso("UTC");+ const earliest = earliestReadableDay(today, 30, addDaysIso);+ const weekCount = Math.ceil(30 / 7);+ const rows = [+ { date: earliest!, total_seconds: 60, task_count: 1, failed_count: 0, cancelled_count: 0 },+ ];++ const time = aggregateWeeklyTime(rows, "UTC", weekCount, earliest);+ expect(time).toHaveLength(5);+ expect(time[0]).toMatchObject({ weekStart: firstWeek, partial: covered < 7, daysCovered: covered });+ expect(time[1]).toMatchObject({ partial: false, daysCovered: 7 });+ expect(time[4]).toMatchObject({ daysCovered: lastCovered, partial: lastCovered < 7 });++ const tasks = aggregateWeeklyTasks(rows, "UTC", weekCount, earliest);+ expect(tasks[0]).toMatchObject({ partial: covered < 7, daysCovered: covered });+ const errors = aggregateWeeklyErrors([], "UTC", weekCount, earliest);+ expect(errors[0]).toMatchObject({ partial: covered < 7, daysCovered: covered });+ const { weeklyTokens, weeklyCostStack } = aggregateByWeek([], "UTC", weekCount, earliest);+ expect(weeklyTokens[0]).toMatchObject({ partial: covered < 7, daysCovered: covered });+ expect(weeklyCostStack[0]).toMatchObject({ partial: covered < 7, daysCovered: covered });++ // Without a limit the same week is whole.+ expect(aggregateWeeklyTime(rows, "UTC", weekCount)[0]).toMatchObject({ partial: false, daysCovered: 7 });+ });++ // A replica still on the old policy answers the 35-day weekly request with+ // the day before the plan's range. That day must not reach the first bucket.+ it("leaves out days before the plan's first day that a stale replica returned", () => {+ vi.setSystemTime(new Date("2026-11-18T12:00:00Z")); // Wednesday+ const today = todayIso("UTC");+ const earliest = earliestReadableDay(today, 30, addDaysIso)!; // Tue 10-20+ const outside = addDaysIso(earliest, -1); // Mon 10-19, day 31+ const weekCount = Math.ceil(30 / 7);++ const runRows = [+ { date: outside, total_seconds: 420, task_count: 7, failed_count: 2, cancelled_count: 1 },+ { date: earliest, total_seconds: 60, task_count: 1, failed_count: 0, cancelled_count: 0 },+ ];+ const time = aggregateWeeklyTime(runRows, "UTC", weekCount, earliest);+ expect(time[0]).toMatchObject({ weekStart: "2026-10-19", daysCovered: 6, totalSeconds: 60 });+ const tasks = aggregateWeeklyTasks(runRows, "UTC", weekCount, earliest);+ expect(tasks[0]).toMatchObject({ completed: 1, failed: 0, cancelled: 0 });++ const errors = aggregateWeeklyErrors(+ [+ { date: outside, failure_reason: "timeout", task_count: 5 },+ { date: earliest, failure_reason: "", task_count: 2 },+ ],+ "UTC",+ weekCount,+ earliest,+ );+ expect(errors[0]).toMatchObject({ failed: 0, total: 2 });++ const usage = (date: string, input: number) => ({+ date,+ provider: "anthropic",+ model: "claude-sonnet-4-6",+ input_tokens: input,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ });+ const { weeklyTokens } = aggregateByWeek(+ [usage(outside, 9_000), usage(earliest, 100)],+ "UTC",+ weekCount,+ earliest,+ );+ expect(weeklyTokens[0]).toMatchObject({ input: 100 });+ });+});diff --git a/packages/views/dashboard/history-range.ts b/packages/views/dashboard/history-range.tsnew file mode 100644index 0000000000..24909feb9f--- /dev/null+++ b/packages/views/dashboard/history-range.ts@@ -0,0 +1,64 @@+import type { WorkspacePlanLimits } from "@multica/core/types";+import { TIME_RANGES, type TimeRange, type TimeRangeOption } from "./components/dashboard-shared";++/**+ * Plan-limited dashboard ranges (MUL-9490).+ *+ * `maxDays` is the enforced history limit, null for none. A range longer than+ * it is locked in the menu, and the page reads the longest range that fits.+ */++/** Whether the plan covers a range. */+export function isRangeAllowed(days: TimeRange, maxDays: number | null): boolean {+ return maxDays === null || days <= maxDays;+}++/**+ * The range the page reads: the selection when it is offered and the plan+ * covers it, otherwise the longest offered range that fits. Derived on every render and never written back,+ * so a plan change moves the page and an upgrade restores the selection.+ */+export function effectiveRange(+ selected: TimeRange,+ maxDays: number | null,+ ranges: readonly TimeRangeOption[] = TIME_RANGES,+): TimeRange {+ const offered = ranges.some((r) => r.days === selected);+ if (offered && isRangeAllowed(selected, maxDays)) return selected;+ let best: TimeRange = TIME_RANGES[0].days;+ for (const range of ranges) {+ if (range.days <= (maxDays ?? Infinity) && range.days > best) best = range.days;+ }+ return best;+}++export type UpgradePlan = "pro" | "business";++/**+ * The cheapest paid plan whose history covers a range, from the limits Cloud+ * enforces. Null when the limits are unknown or no plan covers it, so the menu+ * shows only the lock rather than pointing at a plan that may be wrong.+ */+export function planForRange(+ days: TimeRange,+ planLimits: WorkspacePlanLimits | null | undefined,+): UpgradePlan | null {+ if (!planLimits) return null;+ for (const plan of ["pro", "business"] as const) {+ const limit = planLimits[plan].dashboardHistoryDays;+ if (limit !== null && limit >= days) return plan;+ }+ return null;+}++/**+ * The first calendar day the plan lets the page read, as an ISO date, or null+ * when nothing is enforced. `today` is today's ISO date in the viewing zone.+ */+export function earliestReadableDay(+ today: string,+ maxDays: number | null,+ addDays: (iso: string, delta: number) => string,+): string | null {+ return maxDays === null ? null : addDays(today, -(maxDays - 1));+}diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex efcc1221e3..d80f075701 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -377,7 +377,18 @@ interface WeekShell {// carries the labels and partial-week metadata the chart components consume;// downstream aggregators fold their own per-week values onto the matching// shell.-function buildWeekShells(tz: string, weekCount: number): WeekShell[] {+//+// `earliestDay` is the first day the plan lets the page read (MUL-9490). The+// leftmost week it cuts into is partial like the current week: it covers only+// the days from `earliestDay` on, and the tooltip says how many. The weekly+// aggregators also drop rows dated before it: a replica still on the old+// policy can answer the over-fetched weekly request with days the plan no+// longer covers.+function buildWeekShells(+ tz: string,+ weekCount: number,+ earliestDay: string | null = null,+): WeekShell[] {const count = Math.max(1, Math.floor(weekCount));const today = todayIso(tz);const currentWeekStart = weekStartIso(today);@@ -386,24 +397,33 @@ function buildWeekShells(tz: string, weekCount: number): WeekShell[] {for (let i = 0; i < count; i++) {const weekStart = addDaysIso(firstWeekStart, i * 7);const weekEnd = addDaysIso(weekStart, 6);- const partial = today < weekEnd;- // Inclusive count of how many days of this week have actually elapsed.- // Closed weeks sit at 7; the current week reports 1..6.- const clampedToday =- today < weekStart ? weekStart : today < weekEnd ? today : weekEnd;- const elapsed = Math.min(7, Math.max(1, diffDaysIso(weekStart, clampedToday) + 1));+ const daysCovered = coveredDaysInWeek(weekStart, weekEnd, today, earliestDay);shells.push({weekStart,weekEnd,label: formatShortDate(weekStart),rangeLabel: `${formatShortDate(weekStart)} – ${formatShortDate(weekEnd)}`,- partial,- daysCovered: partial ? elapsed : 7,+ partial: daysCovered < 7,+ daysCovered,});}return shells;}+// Inclusive count of the week's days that have elapsed and that the plan+// covers: 7 for a whole week, fewer for the current week or for the leftmost+// week the plan cuts into.+export function coveredDaysInWeek(+ weekStart: string,+ weekEnd: string,+ today: string,+ earliestDay: string | null,+): number {+ const from = earliestDay && earliestDay > weekStart ? earliestDay : weekStart;+ const to = today < weekEnd ? today : weekEnd;+ return Math.min(7, Math.max(1, diffDaysIso(from, to) + 1));+}+function diffDaysIso(from: string, to: string): number {const [y1, m1, d1] = from.split("-").map(Number);const [y2, m2, d2] = to.split("-").map(Number);@@ -416,11 +436,13 @@ export function aggregateWeeklyTime(rows: DashboardRunTimeDaily[],tz: string,weekCount: number,+ earliestDay: string | null = null,): WeeklyTimeData[] {- const shells = buildWeekShells(tz, weekCount);+ const shells = buildWeekShells(tz, weekCount, earliestDay);const totals = new Map<string, number>();for (const shell of shells) totals.set(shell.weekStart, 0);for (const r of rows) {+ if (earliestDay && r.date < earliestDay) continue;const wkStart = weekStartIso(r.date);if (!totals.has(wkStart)) continue;totals.set(wkStart, (totals.get(wkStart) ?? 0) + r.total_seconds);@@ -432,8 +454,9 @@ export function aggregateWeeklyTasks(rows: DashboardRunTimeDaily[],tz: string,weekCount: number,+ earliestDay: string | null = null,): WeeklyTasksData[] {- const shells = buildWeekShells(tz, weekCount);+ const shells = buildWeekShells(tz, weekCount, earliestDay);const buckets = new Map<string,{ completed: number; failed: number; cancelled: number }@@ -441,6 +464,7 @@ export function aggregateWeeklyTasks(for (const shell of shells)buckets.set(shell.weekStart, { completed: 0, failed: 0, cancelled: 0 });for (const r of rows) {+ if (earliestDay && r.date < earliestDay) continue;const wkStart = weekStartIso(r.date);const bucket = buckets.get(wkStart);if (!bucket) continue;@@ -585,13 +609,15 @@ export function aggregateWeeklyErrors(rows: DashboardFailureDaily[],tz: string,weekCount: number,+ earliestDay: string | null = null,): WeeklyErrorsData[] {- const shells = buildWeekShells(tz, weekCount);+ const shells = buildWeekShells(tz, weekCount, earliestDay);const buckets = new Map<string, FailureClassCounts & FailureBucketTotals>();for (const shell of shells) {buckets.set(shell.weekStart, { ...emptyClassCounts(), failed: 0, total: 0 });}for (const r of rows) {+ if (earliestDay && r.date < earliestDay) continue;const bucket = buckets.get(weekStartIso(r.date));if (!bucket) continue;foldFailureRow(bucket, r.failure_reason, r.task_count);diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex f41ab1a49d..9de5458585 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -149,7 +149,9 @@"addon_none": "None this month","addon_purchased": "{{runs}} bought this month","addon_buy": "Buy · {{price}} / {{runs}} runs",- "addon_buy_fallback": "Buy more runs"+ "addon_buy_fallback": "Buy more runs",+ "dashboard_history": "Analytics history",+ "dashboard_history_days": "Last {{days}} days"},"seats": {"title": "Seats",diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.jsonindex c89140be72..6f3808d896 100644--- a/packages/views/locales/en/usage.json+++ b/packages/views/locales/en/usage.json@@ -10,6 +10,16 @@"all_projects": "All projects","period_label": "Period"},+ "history_limit": {+ "note": "Your plan covers the last {{days}} days. Upgrade to see earlier data. Nothing is deleted.",+ "fell_back": "Your plan covers the last {{days}} days.",+ "view_plans": "View plans",+ "locked": "Not included in your plan",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "Cost · {{days}}D","tokens_label": "Tokens · {{days}}D",diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 5f7795e15e..0431ad1f40 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -149,7 +149,9 @@"addon_none": "Ninguna este mes","addon_purchased": "{{runs}} compradas este mes","addon_buy": "Comprar · {{price}} / {{runs}} ejecuciones",- "addon_buy_fallback": "Comprar más ejecuciones"+ "addon_buy_fallback": "Comprar más ejecuciones",+ "dashboard_history": "Historial de analítica",+ "dashboard_history_days": "Últimos {{days}} días"},"seats": {"title": "Puestos",diff --git a/packages/views/locales/es/usage.json b/packages/views/locales/es/usage.jsonindex 1ee2d9ab8d..e4212a126e 100644--- a/packages/views/locales/es/usage.json+++ b/packages/views/locales/es/usage.json@@ -10,6 +10,16 @@"all_projects": "Todos los proyectos","period_label": "Periodo"},+ "history_limit": {+ "note": "Tu plan incluye los últimos {{days}} días. Mejora tu plan para ver datos anteriores. No se elimina nada.",+ "fell_back": "Tu plan incluye los últimos {{days}} días.",+ "view_plans": "Ver planes",+ "locked": "No incluido en tu plan",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "Coste · {{days}}D","tokens_label": "Tokens · {{days}}D",diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex 388070dfd6..597a72bdb9 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -149,7 +149,9 @@"addon_none": "Aucune ce mois-ci","addon_purchased": "{{runs}} achetées ce mois-ci","addon_buy": "Acheter · {{price}} / {{runs}} exécutions",- "addon_buy_fallback": "Acheter des exécutions"+ "addon_buy_fallback": "Acheter des exécutions",+ "dashboard_history": "Historique des statistiques",+ "dashboard_history_days": "{{days}} derniers jours"},"seats": {"title": "Sièges",diff --git a/packages/views/locales/fr/usage.json b/packages/views/locales/fr/usage.jsonindex 4fca0aa7ec..c8b82eedc5 100644--- a/packages/views/locales/fr/usage.json+++ b/packages/views/locales/fr/usage.json@@ -10,6 +10,16 @@"all_projects": "Tous les projets","period_label": "Période"},+ "history_limit": {+ "note": "Votre forfait couvre les {{days}} derniers jours. Passez à un forfait supérieur pour voir les données plus anciennes. Rien n'est supprimé.",+ "fell_back": "Votre forfait couvre les {{days}} derniers jours.",+ "view_plans": "Voir les forfaits",+ "locked": "Non inclus dans votre forfait",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "Coût · {{days}} j","tokens_label": "Tokens · {{days}} j",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 13a6e45bcd..43d0fe8793 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -148,7 +148,9 @@"addon_none": "今月の追加購入なし","addon_purchased": "今月 {{runs}} 回を追加購入済み","addon_buy": "追加購入 · {{price}} / {{runs}} 回",- "addon_buy_fallback": "実行回数を追加購入"+ "addon_buy_fallback": "実行回数を追加購入",+ "dashboard_history": "分析の表示期間",+ "dashboard_history_days": "直近 {{days}} 日"},"seats": {"title": "席数",diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.jsonindex 1534b383ef..527f673ee2 100644--- a/packages/views/locales/ja/usage.json+++ b/packages/views/locales/ja/usage.json@@ -10,6 +10,16 @@"all_projects": "すべてのプロジェクト","period_label": "期間"},+ "history_limit": {+ "note": "現在のプランでは直近 {{days}} 日を表示できます。アップグレードするとそれ以前のデータも表示できます。データは削除されません。",+ "fell_back": "現在のプランで表示できるのは直近 {{days}} 日です。",+ "view_plans": "プランを見る",+ "locked": "現在のプランに含まれていません",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "コスト · {{days}}日","tokens_label": "トークン · {{days}}日",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex e8a3413158..d7f258a8b2 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -148,7 +148,9 @@"addon_none": "이번 달 추가 구매 없음","addon_purchased": "이번 달 {{runs}}회 추가 구매함","addon_buy": "추가 구매 · {{price}} / {{runs}}회",- "addon_buy_fallback": "실행 횟수 추가 구매"+ "addon_buy_fallback": "실행 횟수 추가 구매",+ "dashboard_history": "분석 조회 기간",+ "dashboard_history_days": "최근 {{days}}일"},"seats": {"title": "좌석",diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.jsonindex c8d063dd69..0a9dc3b632 100644--- a/packages/views/locales/ko/usage.json+++ b/packages/views/locales/ko/usage.json@@ -10,6 +10,16 @@"all_projects": "모든 프로젝트","period_label": "기간"},+ "history_limit": {+ "note": "현재 요금제에서는 최근 {{days}}일을 볼 수 있습니다. 업그레이드하면 이전 데이터도 볼 수 있으며, 데이터는 삭제되지 않습니다.",+ "fell_back": "현재 요금제에서는 최근 {{days}}일만 볼 수 있습니다.",+ "view_plans": "요금제 보기",+ "locked": "현재 요금제에 포함되지 않음",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "비용 · {{days}}일","tokens_label": "토큰 · {{days}}일",diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex ed5cf52239..c6087281d9 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -151,7 +151,9 @@"addon_none": "В этом месяце не покупались","addon_purchased": "Куплено в этом месяце: {{runs}}","addon_buy": "Купить · {{price}} за {{runs}}",- "addon_buy_fallback": "Купить запуски"+ "addon_buy_fallback": "Купить запуски",+ "dashboard_history": "История аналитики",+ "dashboard_history_days": "Последние {{days}} дн."},"seats": {"title": "Места",diff --git a/packages/views/locales/ru/usage.json b/packages/views/locales/ru/usage.jsonindex ec5c8736f5..2209b3dbbb 100644--- a/packages/views/locales/ru/usage.json+++ b/packages/views/locales/ru/usage.json@@ -10,6 +10,16 @@"all_projects": "Все проекты","period_label": "Период"},+ "history_limit": {+ "note": "Ваш тариф охватывает последние {{days}} дн. Перейдите на другой тариф, чтобы увидеть более ранние данные. Данные не удаляются.",+ "fell_back": "Ваш тариф охватывает последние {{days}} дн.",+ "view_plans": "Посмотреть тарифы",+ "locked": "Не входит в ваш тариф",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "Стоимость · {{days}} дн.","tokens_label": "Токены · {{days}} дн.",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 22204b3f1c..c4eadccb81 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -148,7 +148,9 @@"addon_none": "本月未加购","addon_purchased": "本月已加购 {{runs}} 次","addon_buy": "加购 · {{price}} / {{runs}} 次",- "addon_buy_fallback": "加购执行次数"+ "addon_buy_fallback": "加购执行次数",+ "dashboard_history": "统计查看范围",+ "dashboard_history_days": "最近 {{days}} 天"},"seats": {"title": "席位",diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.jsonindex 519b62ac4e..748a91728b 100644--- a/packages/views/locales/zh-Hans/usage.json+++ b/packages/views/locales/zh-Hans/usage.json@@ -10,6 +10,16 @@"all_projects": "全部项目","period_label": "时间范围"},+ "history_limit": {+ "note": "当前套餐可以查看最近 {{days}} 天。升级后可以查看更早的数据,数据一直保留。",+ "fell_back": "当前套餐只能查看最近 {{days}} 天。",+ "view_plans": "查看套餐",+ "locked": "当前套餐不包含",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "费用 · {{days}}天","tokens_label": "Token · {{days}}天",diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex db0a54e8d8..b6d15e45c1 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -148,7 +148,9 @@"addon_none": "本月未加購","addon_purchased": "本月已加購 {{runs}} 次","addon_buy": "加購 · {{price}} / {{runs}} 次",- "addon_buy_fallback": "加購執行次數"+ "addon_buy_fallback": "加購執行次數",+ "dashboard_history": "統計查看範圍",+ "dashboard_history_days": "最近 {{days}} 天"},"seats": {"title": "席位",diff --git a/packages/views/locales/zh-Hant/usage.json b/packages/views/locales/zh-Hant/usage.jsonindex ae7666b999..eb5e09b581 100644--- a/packages/views/locales/zh-Hant/usage.json+++ b/packages/views/locales/zh-Hant/usage.json@@ -10,6 +10,16 @@"all_projects": "全部專案","period_label": "時間範圍"},+ "history_limit": {+ "note": "目前方案可以查看最近 {{days}} 天。升級後可以查看更早的資料,資料一直保留。",+ "fell_back": "目前方案只能查看最近 {{days}} 天。",+ "view_plans": "查看套餐",+ "locked": "目前方案不包含",+ "plan": {+ "pro": "Pro",+ "business": "Business"+ }+ },"kpi": {"cost_label": "費用 · {{days}}天","tokens_label": "Token · {{days}}天",diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsxindex df84fcee75..9da0952a66 100644--- a/packages/views/runtimes/components/usage-section.tsx+++ b/packages/views/runtimes/components/usage-section.tsx@@ -58,12 +58,14 @@ import { DimSegmented } from "../../dashboard/components/dim-segmented";// Single source of truth for the period selector. KPIs, the When-chart, the// Cost-by tabs, and the CSV export all read from the same `days` value so// the labels ("· 30D") and the data slice never disagree. Same ranges as the-// Analytics page except 1d.+// Analytics page except 1d, and except 365d: this page reads a fixed 180-day+// cache.const PERIODS = TIME_RANGES.filter(- (r): r is Exclude<(typeof TIME_RANGES)[number], { days: 1 }> => r.days !== 1,+ (r): r is Exclude<(typeof TIME_RANGES)[number], { days: 1 | 365 }> =>+ r.days !== 1 && r.days !== 365,);-type TimeRange = Exclude<DashboardTimeRange, 1>;+type TimeRange = Exclude<DashboardTimeRange, 1 | 365>;// Top-level orchestrator. Owns the time window, fetches a 180-day usage// cache once, slices it into "current" / "prior" windows for delta math,diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex 1c86ad0196..cdba446937 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -1330,6 +1330,9 @@ export function aggregateByWeek(usage: readonly WeeklyAggregable[],tz: string,weekCount: number,+ // The first day the plan lets the dashboard read (MUL-9490); the leftmost+ // week it cuts into is marked partial.+ earliestDay: string | null = null,): {weeklyTokens: WeeklyTokenData[];weeklyCostStack: WeeklyCostStackData[];@@ -1361,6 +1364,9 @@ export function aggregateByWeek(}for (const u of usage) {+ // Days before the plan's range never count, even when a response from a+ // replica still on the old policy includes them.+ if (earliestDay && u.date < earliestDay) continue;const wkStart = weekStartIso(u.date);if (wkStart < firstWeekStart || wkStart > currentWeekStart) continue;const tokens = tokenMap.get(wkStart);@@ -1381,24 +1387,19 @@ export function aggregateByWeek(const decorate = (weekStart: string) => {const weekEnd = addDaysIso(weekStart, 6);- const partial = today < weekEnd;- // Inclusive count of how many days of this week have actually elapsed.- // Sits at 7 for closed weeks, 1..6 for the current week.- const elapsedDays = Math.min(- 7,- Math.max(- 1,- // Day index of `today` within [weekStart, weekEnd] + 1.- diffDaysIso(weekStart, today < weekStart ? weekStart : today < weekEnd ? today : weekEnd) + 1,- ),- );+ // Inclusive count of the week's days that have elapsed and that the plan+ // covers: 7 for a closed week, fewer for the current week or the leftmost+ // week a history limit cuts into.+ const from = earliestDay && earliestDay > weekStart ? earliestDay : weekStart;+ const to = today < weekEnd ? today : weekEnd;+ const daysCovered = Math.min(7, Math.max(1, diffDaysIso(from, to) + 1));return {weekStart,weekEnd,label: formatShortDate(weekStart),rangeLabel: `${formatShortDate(weekStart)} – ${formatShortDate(weekEnd)}`,- partial,- daysCovered: partial ? elapsedDays : 7,+ partial: daysCovered < 7,+ daysCovered,};};diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 69de888bb7..cc91638416 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -461,6 +461,20 @@ describe("BillingTab", () => {expect(mocks.useQuery).not.toHaveBeenCalled();});+ it("shows the plan's analytics history range only when Cloud reports it", () => {+ const { unmount } = renderWithI18n(<BillingTab />);+ expect(screen.queryByText("Analytics history")).toBeNull();+ unmount();++ mocks.entitlements.limits = {+ ...mocks.entitlements.limits,+ dashboardHistoryDays: { mode: "limited", limit: 30 },+ };+ renderWithI18n(<BillingTab />);+ expect(screen.getByText("Analytics history")).toBeInTheDocument();+ expect(screen.getByText("Last 30 days")).toBeInTheDocument();+ });+it("shows server prices and keeps the selected interval in sync", async () => {const user = userEvent.setup();renderWithI18n(<BillingTab />);@@ -1141,6 +1155,10 @@ describe("BillingTab", () => {expect(screen.getByText("Unlimited")).toBeInTheDocument();expect(screen.queryByText("5 / 7")).not.toBeInTheDocument();expect(screen.queryByText(/Runs a member starts with Run now/)).not.toBeInTheDocument();+ // The paid plan is recorded: paid features and plan limits are re-read.+ expect(mocks.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["workspace-features", "workspace-1"],+ });} finally {vi.useRealTimers();}diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 99aa88847e..46b1fa87d4 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -38,6 +38,7 @@ import {storageUsageProgress,readUpgradeInvite,type HeldInvite,+ workspaceFeatureKeys,workspaceSubscriptionPricesOptions,workspaceSubscriptionSummaryOptions,} from "@multica/core/billing";@@ -446,6 +447,10 @@ function BillingTabContent() {}, [awaitingHeldCheckoutAt, refetchSummary]);const entitlements = summaryQuery.data?.entitlement;+ // Absent from an older Cloud; the row is then left out.+ const dashboardHistoryLimit = entitlements?.limits.dashboardHistoryDays;+ const dashboardHistoryDays =+ dashboardHistoryLimit?.mode === "limited" ? dashboardHistoryLimit.limit : null;// A confirmed upgrade or seat purchase changes the storage limit; the// entitlement already carries the new one, and this refreshes the usage// read behind it.@@ -720,8 +725,11 @@ function BillingTabContent() {setIsSyncingCheckout(false);setSyncTimedOut(false);checkoutIntentRef.current = null;+ // The paid plan is now recorded: re-read the paid features and plan+ // limits so nothing stays locked under the plan the user just left.+ void queryClient.invalidateQueries({ queryKey: workspaceFeatureKeys.all(wsId) });}- }, [isCheckoutConfirmed, isSyncingCheckout]);+ }, [isCheckoutConfirmed, isSyncingCheckout, queryClient, wsId]);const sendHeldInvite = (held: HeldInvite) => {setHeldInvitesToConfirm([]);@@ -2136,6 +2144,15 @@ function BillingTabContent() {</div></SettingsRow>) : null}+ {dashboardHistoryDays !== null ? (+ <SettingsRow label={t(($) => $.workspace.limits.dashboard_history)}>+ <span className="tabular-nums">+ {t(($) => $.workspace.limits.dashboard_history_days, {+ days: dashboardHistoryDays,+ })}+ </span>+ </SettingsRow>+ ) : null}{memberLimit ? (<SettingsRow label={t(($) => $.workspace.limits.members)}><div className="flex flex-col gap-1 sm:items-end">diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex fb0dbd56de..04eba6bd4a 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -159,6 +159,7 @@ var concurrentIndexCleanups = map[string]string{"706_doc_comment_doc_idx": "doc_comment_doc_idx","707_doc_comment_workspace_idx": "doc_comment_workspace_idx","708_attachment_workspace_size_idx": "idx_attachment_workspace_size",+ "712_dashboard_range_view_scope_idx": "uq_dashboard_range_view_scope","671_weixin_account_state_unique_index": "weixin_account_state_pkey","669_weixin_login_session_unique_index": "weixin_login_session_pkey","666_weixin_login_expiry_idx": "weixin_login_expiry_idx",diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.goindex ffcf07cd9e..e91c0a99c1 100644--- a/server/cmd/server/cors_headers_test.go+++ b/server/cmd/server/cors_headers_test.go@@ -49,6 +49,7 @@ func TestRouterCORSContract(t *testing.T) {handler.HeaderTimelineTruncated,handler.HeaderActiveRunsTruncated,handler.HeaderAgentTasksNextCursor,+ handler.HeaderDashboardHistoryLimit,} {if !headerListContains(rec.Header().Get("Access-Control-Expose-Headers"), want) {t.Errorf("Access-Control-Expose-Headers = %q, missing %q", rec.Header().Get("Access-Control-Expose-Headers"), want)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 36dd6bb2be..c7786e78fd 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -107,6 +107,7 @@ var corsExposedHeaders = []string{handler.HeaderTimelineTruncated,handler.HeaderActiveRunsTruncated,handler.HeaderAgentTasksNextCursor,+ handler.HeaderDashboardHistoryLimit,}func registerPluginActionRoutes(r chi.Router, h *handler.Handler) {diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 96e4455026..6edaa01ddb 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -17,7 +17,7 @@ The client reads:- `schema_version`: only version 1 is accepted.- `policy_revision`: the effective-instruction generation, currently fixed at- `7` by Cloud and not deployment configuration. Cloud advances it when the+ `9` by Cloud and not deployment configuration. Cloud advances it when themeaning or set of actionable instructions changes, including additiveinstructions; `schema_version` changes only for incompatible wire parsing.- `subscription_version`: the workspace's monotonic subscription revision. A@@ -74,6 +74,11 @@ Revision 7 adds the `agent_invocation_members`, `runtime_member_sharing` andignores features it does not know, and this consumer reads a policy withoutone as that feature `off` with reason `feature_missing`.+`gates.dashboard_history_days` (revision 9) is optional like `members`: a+missing or malformed gate, including a `limit` outside 1–365 or one carrying a+period, is `off` with reason `gate_missing` or `gate_invalid` for that gate+alone. See [Dashboard history limit](#dashboard-history-limit).+Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTPfailures, and timeouts fail open.@@ -273,3 +278,39 @@ Clients read `GET /api/workspaces/{id}/features`, which returns only`available` (off or observe) or `locked` (enforce) per feature, and renderread-only and upgrade states from it. The server enforces on every writeregardless.++## Dashboard history limit++`dashboard_history_days` caps how many calendar days back the workspace+dashboard can read. Its `limit` is a day count (1–365) and it has no period.+Cloud sends it for every known plan: Free, Pro and Business (trials included)+each get their own configured day count.++Only `enforce` limits anything (`server/internal/handler/dashboard_history.go`).+The six `/api/dashboard/*` endpoints then cut their cutoff to the first of the+most recent N calendar days in the viewing time zone, whatever `days` asked+for, including the date series' extra day of headroom and the days a weekly+chart fetches to fill its leftmost week, and send the limit in+`X-Dashboard-History-Limit-Days`. `off`, `observe` (including a downgraded+stale `enforce`, marked `Downgraded` on the `Decision`) and self-hosted+deployments read up to the request maximum of 371 days with no header. The+runtime usage endpoints keep their own 365-day maximum and no plan limit.+The dashboard's `365d` range follows the frontend flag+`dashboard_history_365d`: published on by default, and+`FF_DASHBOARD_HISTORY_365D=off` hides the range should the year-long queries+be too slow for a deployment.++`GET /api/workspaces/{id}/features` reports `limits.dashboard_history_days`+only under `enforce`, so an observed rollout is invisible to users.++Reads of `GET /api/dashboard/usage/by-agent`, the one dashboard endpoint+fetched once per page load or range change with the range the viewer picked,+are aggregated per workspace, UTC day, requested days and returned days in+`dashboard_range_view` while Cloud is connected: view count, reads past the+limit admitted under a configured observe, admitted because of a downgrade,+and cut short under enforce, with the latest limit, action and reason. The+write runs off the request path with its own 500 ms timeout; a failure drops+the row and never changes the response. It selects its workspace row under+`FOR KEY SHARE`, so a write racing workspace deletion either waits for it and+inserts nothing or is removed by it. Counts are read requests, including+the dashboard's periodic refresh, so use distinct workspaces for reach.diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex a36bee97c6..95668d72b2 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -410,7 +410,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {return fetchedPolicy{}, ErrInvalidPolicy}// Unknown gates are ignored for additive compatibility.- gates := make(map[GateName]Gate, 3)+ gates := make(map[GateName]Gate, 4)wireAutopilot, ok := wire.Gates[string(GateAutopilotRuns)]if !ok {return fetchedPolicy{}, ErrInvalidPolicy@@ -425,7 +425,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {// Cloud and Multica can deploy in either order and a bad value cannot turn// the autopilot quota off.gateReasons := make(map[GateName]Reason)- for _, name := range []GateName{GateMembers, GateStorageBytes} {+ for _, name := range []GateName{GateMembers, GateStorageBytes, GateDashboardHistoryDays} {if wire.undecodableGates[string(name)] {gates[name] = Gate{Action: ActionOff}gateReasons[name] = ReasonGateInvalid@@ -484,6 +484,11 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {if name == GateAutopilotRuns && periodFields != 3 {return Gate{}, ErrInvalidPolicy}+ // A day count: positive, within the product's range, never a period.+ if name == GateDashboardHistoryDays &&+ (periodFields != 0 || *wire.Limit < 1 || *wire.Limit > MaxDashboardHistoryDays) {+ return Gate{}, ErrInvalidPolicy+ }if periodFields == 3 && (!wire.PeriodStart.Before(*wire.PeriodEnd) || !wire.PeriodStart.Before(*wire.ResetAt)) {return Gate{}, ErrInvalidPolicy}@@ -562,12 +567,14 @@ func decisionFromEntry(entry cacheEntry, name GateName, reason Reason, stale booif fallback, ok := entry.policy.gateReasons[name]; ok {reason = fallback}- if stale && gate.Action == ActionEnforce {+ downgraded := stale && gate.Action == ActionEnforce+ if downgraded {gate.Action = ActionObserve}return Decision{Gate: gate,Reason: reason,+ Downgraded: downgraded,PolicyRevision: entry.policy.policyRevision,SubscriptionVersion: entry.policy.subscriptionVersion,CloudValidUntil: entry.policy.cloudValidUntil,diff --git a/server/internal/entitlement/dashboard_history_gate_test.go b/server/internal/entitlement/dashboard_history_gate_test.gonew file mode 100644index 0000000000..a9492af309--- /dev/null+++ b/server/internal/entitlement/dashboard_history_gate_test.go@@ -0,0 +1,164 @@+package entitlement++import (+ "context"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+)++func dashboardHistoryGate(action Action, days int) wireGate {+ gate := wireGate{Action: string(action)}+ if action != ActionOff {+ gate.Limit = &days+ }+ return gate+}++func TestDashboardHistoryGateIsADayCount(t *testing.T) {+ for _, action := range []Action{ActionOff, ActionObserve, ActionEnforce} {+ t.Run(string(action), func(t *testing.T) {+ server := httptest.NewServer(policyHandler(func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = dashboardHistoryGate(action, 30)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)++ decision := client.Gate(context.Background(), uuid.New(), GateDashboardHistoryDays)+ if decision.Gate.Action != action || decision.Reason != ReasonRefreshed || decision.Downgraded {+ t.Fatalf("decision = %+v", decision)+ }+ if action == ActionOff {+ return+ }+ if decision.Gate.Limit == nil || *decision.Gate.Limit != 30 || decision.Gate.PeriodStart != nil {+ t.Fatalf("gate = %+v, want limit 30 without a period", decision.Gate)+ }+ })+ }+}++// A Cloud that does not send the gate yet, or sends it malformed, leaves the+// dashboard unlimited without failing the autopilot quota open with it.+func TestDashboardHistoryGateFailsOpenAlone(t *testing.T) {+ zero, tooMany, negative, valid := 0, MaxDashboardHistoryDays+1, -1, 30+ periodStart := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)+ periodEnd := periodStart.AddDate(0, 1, 0)+ tests := []struct {+ name string+ mutate func(*wirePolicy)+ reason Reason+ }{+ {"missing", func(*wirePolicy) {}, ReasonGateMissing},+ {"unknown action", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{Action: "block", Limit: &valid}+ }, ReasonGateInvalid},+ {"enforce without limit", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{Action: string(ActionEnforce)}+ }, ReasonGateInvalid},+ {"zero days", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{Action: string(ActionEnforce), Limit: &zero}+ }, ReasonGateInvalid},+ {"negative days", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{Action: string(ActionEnforce), Limit: &negative}+ }, ReasonGateInvalid},+ {"past the product range", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{Action: string(ActionEnforce), Limit: &tooMany}+ }, ReasonGateInvalid},+ {"with a period", func(p *wirePolicy) {+ p.Gates[string(GateDashboardHistoryDays)] = wireGate{+ Action: string(ActionEnforce), Limit: &valid,+ PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,+ }+ }, ReasonGateInvalid},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ server := httptest.NewServer(policyHandler(tt.mutate))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ history := client.Gate(context.Background(), workspaceID, GateDashboardHistoryDays)+ if history.Gate.Action != ActionOff || history.Reason != tt.reason {+ t.Fatalf("dashboard_history_days = %+v, want off/%s", history, tt.reason)+ }+ autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ if autopilot.Gate.Action != ActionEnforce || autopilot.Reason != ReasonCacheFresh {+ t.Fatalf("autopilot = %+v, want the enforced quota from the same policy", autopilot)+ }+ })+ }+}++// A JSON type error inside the gate (a string day count) must not fail the+// decode of the whole policy.+func TestDashboardHistoryGateOfTheWrongShapeFailsOpenAlone(t *testing.T) {+ const autopilot = `"autopilot_runs": {"action": "enforce", "limit": 23,+ "period_start": "2026-08-01T00:00:00Z", "period_end": "2026-09-01T00:00:00Z",+ "reset_at": "2026-09-01T00:00:00Z"}`+ for _, gate := range []string{+ `"dashboard_history_days": {"action": "enforce", "limit": "30"}`,+ `"dashboard_history_days": {"action": "enforce", "limit": 30.5}`,+ `"dashboard_history_days": "enforce"`,+ } {+ t.Run(gate, func(t *testing.T) {+ body := `{"schema_version": 1, "policy_revision": 6, "subscription_version": 0,+ "valid_until": "2030-01-01T00:00:00Z", "valid_for_seconds": 60,+ "gates": {` + autopilot + `, ` + gate + `}}`+ server := httptest.NewServer(bodyHandler(http.StatusOK, body))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ if got := client.Gate(context.Background(), workspaceID, GateDashboardHistoryDays); got.Gate.Action != ActionOff || got.Reason != ReasonGateInvalid {+ t.Fatalf("dashboard_history_days = %+v, want off/gate_invalid", got)+ }+ if got := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); got.Gate.Action != ActionEnforce {+ t.Fatalf("autopilot = %+v, want the enforced quota", got)+ }+ })+ }+}++// A stale enforce is lowered to observe and marked Downgraded, so consumers+// can count Cloud outages apart from a configured observe.+func TestStaleEnforceIsMarkedDowngraded(t *testing.T) {+ for _, configured := range []Action{ActionEnforce, ActionObserve} {+ t.Run(string(configured), func(t *testing.T) {+ clock := time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC)+ var fail atomic.Bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ if fail.Load() {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ policy := samplePolicy(6, 1, 5, ActionEnforce)+ policy.Gates[string(GateDashboardHistoryDays)] = dashboardHistoryGate(configured, 30)+ writePolicy(t, w, policy)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ client.now = func() time.Time { return clock }+ workspaceID := uuid.New()++ if fresh := client.Gate(context.Background(), workspaceID, GateDashboardHistoryDays); fresh.Gate.Action != configured || fresh.Downgraded {+ t.Fatalf("fresh = %+v", fresh)+ }+ fail.Store(true)+ clock = clock.Add(6 * time.Second)+ stale := client.Gate(context.Background(), workspaceID, GateDashboardHistoryDays)+ wantDowngraded := configured == ActionEnforce+ if stale.Gate.Action != ActionObserve || stale.Reason != ReasonStale || stale.Downgraded != wantDowngraded {+ t.Fatalf("stale = %+v, want observe/stale downgraded=%v", stale, wantDowngraded)+ }+ if stale.Gate.Limit == nil || *stale.Gate.Limit != 30 {+ t.Fatalf("stale gate = %+v, want the cached limit kept", stale.Gate)+ }+ })+ }+}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex b03f302649..3332609f82 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -19,11 +19,18 @@ const (// GateStorageBytes caps the attachment bytes a workspace holds. Like// members it has no period: the limit is what the workspace may hold now.GateStorageBytes GateName = "storage_bytes"+ // GateDashboardHistoryDays caps how many calendar days back the workspace+ // dashboard can read. Limit is a day count with no period.+ GateDashboardHistoryDays GateName = "dashboard_history_days")+// MaxDashboardHistoryDays is the largest dashboard_history_days limit Cloud+// may send. A larger value is a malformed gate.+const MaxDashboardHistoryDays = 365+func (n GateName) valid() bool {switch n {- case GateAutopilotRuns, GateMembers, GateStorageBytes:+ case GateAutopilotRuns, GateMembers, GateStorageBytes, GateDashboardHistoryDays:return truedefault:return false@@ -89,8 +96,12 @@ type NotificationPolicy struct {// Decision carries enough source information for consumers to audit why a gate// was enforced, observed, or disabled without exposing Cloud's private inputs.type Decision struct {- Gate Gate- Reason Reason+ Gate Gate+ Reason Reason+ // Downgraded is set when Cloud sent enforce but the cached policy has gone+ // stale, so Gate.Action was lowered to observe. It tells a configured+ // observe apart from a Cloud outage, as FeatureDecision.Downgraded does.+ Downgraded boolPolicyRevision int64SubscriptionVersion int64CloudValidUntil time.Timediff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.goindex 1ceb379186..9acd80b011 100644--- a/server/internal/featureflags/keys.go+++ b/server/internal/featureflags/keys.go@@ -42,6 +42,14 @@ const (// for a deployment. It is a GLOBAL switch. Turning it off leaves existing// doc rows untouched — they simply become unreachable until it is back on.DocsV1 = "docs_v1"+ // DashboardHistory365d offers the 365-day range on the workspace dashboard+ // (MUL-9490). On by default; FF_DASHBOARD_HISTORY_365D=off hides the range+ // again if the year-long dashboard queries turn out too slow for a+ // deployment. It only hides the range in the client; the plan's history+ // limit is enforced on the server either way. Clients treat a missing key+ // as off, so a newer client never offers 365 days to a server that would+ // read days=371 as the default 30.+ DashboardHistory365d = "dashboard_history_365d"// agentBuilderCompat is no longer a release flag. Keep publishing the key// as enabled so installed desktop clients that still gate the AI creation// entry on this config decision receive the permanently enabled behavior.@@ -93,11 +101,16 @@ func DocsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, DocsV1, false)}+func DashboardHistory365dEnabled(ctx context.Context, flags *featureflag.Service) bool {+ return flags.IsEnabled(ctx, DashboardHistory365d, true)+}+func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {out := make(map[string]bool, len(frontendPublicFlags)+5)for _, key := range frontendPublicFlags {out[key] = flags.IsEnabled(ctx, key, false)}+ out[DashboardHistory365d] = DashboardHistory365dEnabled(ctx, flags)out[agentBuilderCompat] = trueout[agentSkillTogglesCompat] = trueout[resourceLabelsCompat] = truediff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 618bfe34ae..3152b256ec 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/themestore"@@ -481,6 +482,9 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {if cfg.FeatureFlags["plugins_v1"] {t.Fatalf("plugins_v1: want false by default, got true")}+ if !cfg.FeatureFlags["dashboard_history_365d"] {+ t.Fatal("dashboard_history_365d: want true by default")+ }for _, retired := range []string{"private_plugins_v1", "remote_mcp_plugins_v1"} {if _, published := cfg.FeatureFlags[retired]; published {t.Fatalf("retired Plugin sub-flag %q must not be published", retired)@@ -707,3 +711,17 @@ func TestGetConfigReportsTheThemeStore(t *testing.T) {t.Fatalf("theme_store_enabled: want true, got %s", raw)}}++func TestGetConfigDashboardHistory365dFlagCanBeTurnedOff(t *testing.T) {+ h := &Handler{}+ withFeatureFlag(t, h, featureflags.DashboardHistory365d, false)+ w := httptest.NewRecorder()+ h.GetConfig(w, httptest.NewRequest(http.MethodGet, "/api/config", nil))+ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if enabled, published := cfg.FeatureFlags["dashboard_history_365d"]; !published || enabled {+ t.Fatalf("dashboard_history_365d: want published false when turned off, got published=%v enabled=%v", published, enabled)+ }+}diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.goindex 091bec1fef..0027023f22 100644--- a/server/internal/handler/dashboard.go+++ b/server/internal/handler/dashboard.go@@ -20,9 +20,11 @@ import (// GET /api/dashboard/failures/daily per-(date, failure_reason) counts// GET /api/dashboard/failures/by-agent per-(agent, failure_reason) counts//-// All of them accept ?days=N (defaults to 30, capped at 365) and an optional-// ?project_id=<uuid> to scope the rollup to a single project. With no-// project_id the data spans the whole workspace.+// All of them accept ?days=N (defaults to 30, at most 371 so a 365-day weekly+// chart can round up to whole weeks) and an optional ?project_id=<uuid> to+// scope the rollup to a single project. With no project_id the data spans the+// whole workspace. The workspace's plan may cut the window shorter; see+// dashboard_history.go.//// Cutoff convention: the three date-bucketed series use parseSinceParamInTZ// (N+1 calendar days, the surplus day trimmed client-side with `-(days-1)`),@@ -203,7 +205,8 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)return}tz := h.resolveViewingTZ(r)- since := parseSinceParamInTZ(r, 30, tz)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 0)+ since := window.sinceresp, err := h.listDashboardUsageDaily(r.Context(), parseUUID(workspaceID), tz, since, projectID)if err != nil {@@ -303,13 +306,18 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Reques// the chart directly above it, so at 1D a single agent's row could read// higher than the workspace total (MUL-5551).tz := h.resolveViewingTZ(r)- since := parseExactSinceParamInTZ(r, 30, tz)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.sinceresp, err := h.listDashboardUsageByAgent(r.Context(), parseUUID(workspaceID), since, projectID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list usage by agent")return}+ // The one dashboard read recorded per page load or range change: this+ // endpoint is fetched once per (range, project) and receives the range+ // the viewer picked, where the date series receive it rounded to weeks.+ h.recordDashboardRangeView(r.Context(), parseUUID(workspaceID), window)writeJSON(w, http.StatusOK, foldRestrictedUsageByAgent(resp, restricted))}@@ -427,7 +435,8 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques// Tasks KPI tiles, so the N+1 cutoff put those two tiles on a wider// window than the Cost / Tokens tiles beside them (MUL-5551).tz := h.resolveViewingTZ(r)- since := parseExactSinceParamInTZ(r, 30, tz)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.sincerows, err := h.Queries.ListDashboardAgentRunTime(r.Context(), db.ListDashboardAgentRunTimeParams{WorkspaceID: parseUUID(workspaceID),@@ -510,7 +519,8 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques// 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)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 0)+ since := window.sincerows, err := h.Queries.ListDashboardRunTimeDaily(r.Context(), db.ListDashboardRunTimeDailyParams{WorkspaceID: parseUUID(workspaceID),@@ -578,7 +588,8 @@ func (h *Handler) GetDashboardFailuresDaily(w http.ResponseWriter, r *http.Reque// Same viewer-tz day boundary as every other daily series so the Errors// tab lines up with Cost / Tokens / Time / Tasks.tz := h.resolveViewingTZ(r)- since := parseSinceParamInTZ(r, 30, tz)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 0)+ since := window.sincerows, err := h.Queries.ListDashboardFailuresDaily(r.Context(), db.ListDashboardFailuresDailyParams{WorkspaceID: parseUUID(workspaceID),@@ -637,7 +648,8 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Req// covered one extra day, so at days=1 the card could report yesterday's// failures next to a chart showing none.tz := h.resolveViewingTZ(r)- since := parseExactSinceParamInTZ(r, 30, tz)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.sincerows, err := h.Queries.ListDashboardFailuresByAgent(r.Context(), db.ListDashboardFailuresByAgentParams{WorkspaceID: parseUUID(workspaceID),diff --git a/server/internal/handler/dashboard_history.go b/server/internal/handler/dashboard_history.gonew file mode 100644index 0000000000..6a223ed50b--- /dev/null+++ b/server/internal/handler/dashboard_history.go@@ -0,0 +1,139 @@+package handler++import (+ "context"+ "net/http"+ "strconv"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/service"+)++// Dashboard history limit (MUL-9490).+//+// Cloud sends dashboard_history_days per workspace: how many calendar days+// back the dashboard may read. Only enforce limits anything. Self-hosted+// (h.Entitlements nil), off and observe read as far back as the product+// allows, so an observed rollout changes nothing users can see.+//+// Under enforce every dashboard endpoint is cut to the most recent N calendar+// days in the viewing time zone, whatever `days` asked for: the extra day of+// headroom the date-bucketed series normally carry, and the days a weekly+// chart fetches to fill its leftmost week, are cut too, so no response holds+// data from before the plan's range. The response carries the limit in+// HeaderDashboardHistoryLimit so a page open across a plan change notices it.++// HeaderDashboardHistoryLimit carries the enforced limit, in days, on every+// dashboard response while one applies. Absent means no limit.+const HeaderDashboardHistoryLimit = "X-Dashboard-History-Limit-Days"++// dashboardMaxDaysParam is the largest `days` the dashboard endpoints accept:+// 53 weeks, because a 365-day weekly chart rounds its fetch up to whole weeks+// (371 days). It bounds the request, not what a plan may read.+const dashboardMaxDaysParam = 371++// dashboardHistoryDecision is the workspace's dashboard_history_days decision.+// ok=false when no Cloud is connected; the dashboard is then unlimited and+// reads are not recorded.+func (h *Handler) dashboardHistoryDecision(ctx context.Context, workspaceID string) (entitlement.Decision, bool) {+ if h.Entitlements == nil {+ return entitlement.Decision{}, false+ }+ id, err := uuid.Parse(workspaceID)+ if err != nil {+ return entitlement.Decision{}, false+ }+ return h.Entitlements.Gate(ctx, id, entitlement.GateDashboardHistoryDays), true+}++// enforcedDashboardHistoryDays is the limit a decision enforces, or 0.+func enforcedDashboardHistoryDays(decision entitlement.Decision) int {+ if decision.Gate.Action != entitlement.ActionEnforce || decision.Gate.Limit == nil || *decision.Gate.Limit < 1 {+ return 0+ }+ return *decision.Gate.Limit+}++// dashboardWindow is the resolved `days` window of one dashboard request.+type dashboardWindow struct {+ since pgtype.Timestamptz+ // requestedDays is the parsed `days`.+ requestedDays int+ // truncated is set when the enforced limit moved the cutoff forward.+ truncated bool+ // limitDays is the enforced limit, 0 when none applies.+ limitDays int+ decision entitlement.Decision+ // recordable is set when Cloud is connected, so the read may be recorded.+ recordable bool+}++// dashboardCutoff resolves the `days` cutoff of a dashboard request in tz and+// applies the workspace's history limit to it. trimDays is 0 for the+// date-bucketed series (N+1 days of headroom) and 1 for the per-agent rollups+// (exactly N). It sets HeaderDashboardHistoryLimit when a limit is enforced,+// so call it before writing the response.+func (h *Handler) dashboardCutoff(w http.ResponseWriter, r *http.Request, workspaceID, tz string, trimDays int) dashboardWindow {+ days := parseDaysParam(r, 30, dashboardMaxDaysParam)+ loc := loadViewingLocation(tz)+ now := dayWindowNow()+ since := sinceFromDays(now, days-trimDays, loc)+ window := dashboardWindow{requestedDays: days}++ if decision, ok := h.dashboardHistoryDecision(r.Context(), workspaceID); ok {+ window.decision = decision+ window.recordable = true+ if limit := enforcedDashboardHistoryDays(decision); limit > 0 {+ window.limitDays = limit+ // The first of the N most recent calendar days, today included.+ if floor := sinceFromDays(now, limit-1, loc); since.Before(floor) {+ since = floor+ window.truncated = true+ }+ w.Header().Set(HeaderDashboardHistoryLimit, strconv.Itoa(limit))+ }+ }+ window.since = pgtype.Timestamptz{Time: since, Valid: true}+ return window+}++// returnedDays is how many calendar days an exact-N window covered.+func (d dashboardWindow) returnedDays() int {+ if d.limitDays > 0 && d.requestedDays > d.limitDays {+ return d.limitDays+ }+ return d.requestedDays+}++// recordDashboardRangeView records a successful exact-N dashboard read off the+// request path. It never delays or changes the response.+func (h *Handler) recordDashboardRangeView(ctx context.Context, workspaceID pgtype.UUID, window dashboardWindow) {+ if !window.recordable || h.Queries == nil {+ return+ }+ view := service.DashboardRangeView{+ WorkspaceID: workspaceID,+ RequestedDays: window.requestedDays,+ ReturnedDays: window.returnedDays(),+ Decision: window.decision,+ }+ views := service.DashboardRangeViews{Queries: h.Queries}+ detached := context.WithoutCancel(ctx)+ go views.Record(detached, view)+}++// dashboardHistoryLimitForClient is the limit GET /features reports: the+// enforced day count, or nil when nothing is enforced.+func (h *Handler) dashboardHistoryLimitForClient(ctx context.Context, workspaceID string) *int {+ decision, ok := h.dashboardHistoryDecision(ctx, workspaceID)+ if !ok {+ return nil+ }+ if limit := enforcedDashboardHistoryDays(decision); limit > 0 {+ return &limit+ }+ return nil+}diff --git a/server/internal/handler/dashboard_history_test.go b/server/internal/handler/dashboard_history_test.gonew file mode 100644index 0000000000..f6eaec285a--- /dev/null+++ b/server/internal/handler/dashboard_history_test.go@@ -0,0 +1,605 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func historyDecision(action entitlement.Action, days int) entitlement.Decision {+ gate := entitlement.Gate{Action: action}+ if action != entitlement.ActionOff {+ gate.Limit = &days+ }+ return entitlement.Decision{Gate: gate}+}++// useDashboardHistoryLimit points the shared test handler at a stub that+// returns decision for dashboard_history_days in the test workspace, and+// clears the workspace's recorded reads before and after.+func useDashboardHistoryLimit(t *testing.T, decision entitlement.Decision) {+ t.Helper()+ stub := entitlementtest.New()+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateDashboardHistoryDays, decision)+ prior := testHandler.Entitlements+ testHandler.Entitlements = stub+ clearDashboardRangeViews(t)+ t.Cleanup(func() {+ testHandler.Entitlements = prior+ clearDashboardRangeViews(t)+ })+}++func clearDashboardRangeViews(t *testing.T) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(),+ `DELETE FROM dashboard_range_view WHERE workspace_id = $1`, testWorkspaceID); err != nil {+ t.Fatalf("clear dashboard range views: %v", err)+ }+}++// startOfDayBefore is local midnight `days` days before now's calendar day.+func startOfDayBefore(now time.Time, loc *time.Location, days int) time.Time {+ local := now.In(loc)+ return time.Date(local.Year(), local.Month(), local.Day()-days, 0, 0, 0, 0, loc)+}++// The cutoff every dashboard endpoint reads, across plans, actions, both+// cutoff conventions and time zones at the edges of the offset range.+func TestDashboardCutoffAppliesTheHistoryLimit(t *testing.T) {+ workspaceID := uuid.New()+ request := func(days int, tz string) *http.Request {+ return httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/dashboard/usage/daily?days=%d&tz=%s", days, tz), nil)+ }++ t.Run("enforce cuts every endpoint to the most recent N calendar days", func(t *testing.T) {+ // Request sizes the weekly chart sends for 30/90/365-day ranges.+ for _, tc := range []struct{ limit, requested int }{{30, 35}, {90, 91}, {365, 371}} {+ for _, tz := range []string{"UTC", "Pacific/Kiritimati", "Etc/GMT+12", "Asia/Kolkata"} {+ for _, trim := range []int{0, 1} {+ name := fmt.Sprintf("limit %d requested %d %s trim %d", tc.limit, tc.requested, tz, trim)+ t.Run(name, func(t *testing.T) {+ loc := loadViewingLocation(tz)+ now := pinDayWindowClock(t, time.Date(2026, 11, 20, 23, 30, 0, 0, time.UTC))+ stub := entitlementtest.New()+ stub.Set(workspaceID, entitlement.GateDashboardHistoryDays, historyDecision(entitlement.ActionEnforce, tc.limit))+ h := &Handler{Entitlements: stub}+ rec := httptest.NewRecorder()++ window := h.dashboardCutoff(rec, request(tc.requested, tz), workspaceID.String(), tz, trim)++ want := startOfDayBefore(now, loc, tc.limit-1)+ if !window.since.Time.Equal(want) {+ t.Fatalf("since = %s, want %s (first of the last %d local days)", window.since.Time.In(loc), want, tc.limit)+ }+ if !window.truncated || window.limitDays != tc.limit || window.requestedDays != tc.requested {+ t.Fatalf("window = %+v", window)+ }+ if got := rec.Header().Get(HeaderDashboardHistoryLimit); got != strconv.Itoa(tc.limit) {+ t.Fatalf("limit header = %q, want %d", got, tc.limit)+ }+ })+ }+ }+ }+ })++ t.Run("enforce cuts the headroom day of a request exactly at the limit", func(t *testing.T) {+ now := pinDayWindowClock(t, time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC))+ stub := entitlementtest.New()+ stub.Set(workspaceID, entitlement.GateDashboardHistoryDays, historyDecision(entitlement.ActionEnforce, 30))+ h := &Handler{Entitlements: stub}++ dated := h.dashboardCutoff(httptest.NewRecorder(), request(30, "UTC"), workspaceID.String(), "UTC", 0)+ if want := startOfDayBefore(now, time.UTC, 29); !dated.since.Time.Equal(want) {+ t.Fatalf("date series since = %s, want %s: the N+1 headroom day is outside the plan", dated.since.Time, want)+ }+ exact := h.dashboardCutoff(httptest.NewRecorder(), request(30, "UTC"), workspaceID.String(), "UTC", 1)+ if want := startOfDayBefore(now, time.UTC, 29); !exact.since.Time.Equal(want) || exact.truncated {+ t.Fatalf("per-agent window = %+v, want untouched exact 30 days", exact)+ }+ short := h.dashboardCutoff(httptest.NewRecorder(), request(7, "UTC"), workspaceID.String(), "UTC", 1)+ if want := startOfDayBefore(now, time.UTC, 6); !short.since.Time.Equal(want) || short.truncated {+ t.Fatalf("7-day window = %+v, want untouched", short)+ }+ })++ t.Run("the boundary follows the viewing zone across a DST change", func(t *testing.T) {+ // 2026-03-08 is the US spring-forward day; 30 local days back crosses it.+ loc := loadViewingLocation("America/New_York")+ now := pinDayWindowClock(t, time.Date(2026, 3, 20, 15, 0, 0, 0, time.UTC))+ stub := entitlementtest.New()+ stub.Set(workspaceID, entitlement.GateDashboardHistoryDays, historyDecision(entitlement.ActionEnforce, 30))+ h := &Handler{Entitlements: stub}++ window := h.dashboardCutoff(httptest.NewRecorder(), request(35, "America/New_York"), workspaceID.String(), "America/New_York", 0)+ want := time.Date(2026, 2, 19, 0, 0, 0, 0, loc)+ if !window.since.Time.Equal(want) || !window.since.Time.Equal(startOfDayBefore(now, loc, 29)) {+ t.Fatalf("since = %s, want local midnight %s", window.since.Time.In(loc), want)+ }+ })++ t.Run("off, observe, a downgraded enforce and self-host are unlimited", func(t *testing.T) {+ now := pinDayWindowClock(t, time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC))+ for name, provider := range map[string]entitlement.Provider{+ "off": stubWith(workspaceID, historyDecision(entitlement.ActionOff, 0)),+ "observe": stubWith(workspaceID, historyDecision(entitlement.ActionObserve, 30)),+ "downgraded": stubWith(workspaceID, entitlement.Decision{Gate: historyDecision(entitlement.ActionObserve, 30).Gate, Downgraded: true}),+ "self-host": nil,+ } {+ t.Run(name, func(t *testing.T) {+ h := &Handler{Entitlements: provider}+ rec := httptest.NewRecorder()+ window := h.dashboardCutoff(rec, request(371, "UTC"), workspaceID.String(), "UTC", 0)+ if want := startOfDayBefore(now, time.UTC, 371); !window.since.Time.Equal(want) || window.truncated {+ t.Fatalf("window = %+v, want the full 371-day request", window)+ }+ if got := rec.Header().Get(HeaderDashboardHistoryLimit); got != "" {+ t.Fatalf("limit header = %q, want none", got)+ }+ if window.recordable != (provider != nil) {+ t.Fatalf("recordable = %v; only a Cloud-connected read is recorded", window.recordable)+ }+ })+ }+ })++ t.Run("the dashboard accepts 371 days, the runtime pages still stop at 365", func(t *testing.T) {+ now := pinDayWindowClock(t, time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC))+ h := &Handler{}+ window := h.dashboardCutoff(httptest.NewRecorder(), request(371, "UTC"), workspaceID.String(), "UTC", 0)+ if window.requestedDays != 371 {+ t.Fatalf("dashboard days = %d, want 371", window.requestedDays)+ }+ if got := h.dashboardCutoff(httptest.NewRecorder(), request(372, "UTC"), workspaceID.String(), "UTC", 0); got.requestedDays != 30 {+ t.Fatalf("days=372 = %d, want the default 30", got.requestedDays)+ }+ runtime := parseSinceParamInTZ(request(366, "UTC"), 90, "UTC")+ if want := startOfDayBefore(now, time.UTC, 90); !runtime.Time.Equal(want) {+ t.Fatalf("runtime days=366 since = %s, want the default 90-day cutoff %s", runtime.Time, want)+ }+ })+}++func stubWith(workspaceID uuid.UUID, decision entitlement.Decision) *entitlementtest.Stub {+ stub := entitlementtest.New()+ stub.Set(workspaceID, entitlement.GateDashboardHistoryDays, decision)+ return stub+}++// All six dashboard endpoints, against the database: under enforce none of+// them returns a row from before the plan's range, whatever `days` asked for.+func TestDashboardEndpointsStopAtTheHistoryLimit(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ now := pinDayWindowClock(t, time.Now().UTC())++ type endpoint struct {+ path string+ handler http.HandlerFunc+ // count is how many fixture runs the response reflects.+ count func(t *testing.T, body []byte) int+ // dated responses also name the day of every row.+ dated bool+ }+ countRows := func(field string) func(t *testing.T, body []byte) int {+ return func(t *testing.T, body []byte) int {+ t.Helper()+ var rows []map[string]any+ if err := json.Unmarshal(body, &rows); err != nil {+ t.Fatalf("decode: %v", err)+ }+ n := 0+ for _, row := range rows {+ if v, ok := row[field].(float64); ok {+ n += int(v)+ }+ }+ return n+ }+ }+ // task_usage_hourly's task_count comes from event_count only after a+ // rollup; the two usage endpoints are read by tokens instead.+ endpoints := []endpoint{+ {"/api/dashboard/usage/daily", testHandler.GetDashboardUsageDaily, countTokens, true},+ {"/api/dashboard/usage/by-agent", testHandler.GetDashboardUsageByAgent, countTokens, false},+ {"/api/dashboard/agent-runtime", testHandler.GetDashboardAgentRunTime, countRows("task_count"), false},+ {"/api/dashboard/runtime/daily", testHandler.GetDashboardRunTimeDaily, countRows("task_count"), true},+ {"/api/dashboard/failures/daily", testHandler.GetDashboardFailuresDaily, countRows("task_count"), true},+ {"/api/dashboard/failures/by-agent", testHandler.GetDashboardFailuresByAgent, countRows("task_count"), false},+ }++ // Each plan's limit with the request its weekly chart sends. Fixtures sit+ // at noon on the plan's oldest day and on the day before it.+ for _, plan := range []struct {+ name string+ limit, requested int+ }{+ {"free", 30, 35},+ {"pro", 90, 91},+ {"business", 365, 371},+ } {+ t.Run(plan.name, func(t *testing.T) {+ inside := startOfDayBefore(now, time.UTC, plan.limit-1).Add(12 * time.Hour)+ outside := startOfDayBefore(now, time.UTC, plan.limit).Add(12 * time.Hour)+ runtimeID := dbfx.Runtime(t, "history limit runtime "+plan.name)+ agentID := dbfx.Agent(t, "history limit agent "+plan.name, runtimeID)+ projectID := dbfx.Project(t, "history limit project "+plan.name)+ issueID := dbfx.Issue(t, "history limit issue", testutil.Cols{"project_id": projectID})+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE runtime_id = $1`, runtimeID)+ })+ for _, at := range []time.Time{inside, outside} {+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "failed",+ "failure_reason": "timeout",+ "started_at": at.Add(-10 * time.Minute),+ "completed_at": at,+ "created_at": at.Add(-10 * time.Minute),+ })+ dbfx.Exec(t, `+ 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, $2, $3, $4, $5, 'history-limit', 'history-limit-model', 100, 0, 0, 0, 1)+ `, at.Truncate(time.Hour), testWorkspaceID, runtimeID, agentID, projectID)+ }+ call := func(t *testing.T, ep endpoint) *httptest.ResponseRecorder {+ t.Helper()+ rec := httptest.NewRecorder()+ ep.handler(rec, newRequest(http.MethodGet,+ fmt.Sprintf("%s?days=%d&tz=UTC&project_id=%s", ep.path, plan.requested, projectID), nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("%s: status %d: %s", ep.path, rec.Code, rec.Body.String())+ }+ return rec+ }++ for _, tc := range []struct {+ name string+ decision *entitlement.Decision+ want int+ wantLimit string+ }{+ {"enforce", ptrTo(historyDecision(entitlement.ActionEnforce, plan.limit)), 1, strconv.Itoa(plan.limit)},+ {"observe", ptrTo(historyDecision(entitlement.ActionObserve, plan.limit)), 2, ""},+ {"self-host", nil, 2, ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if tc.decision != nil {+ useDashboardHistoryLimit(t, *tc.decision)+ } else {+ prior := testHandler.Entitlements+ testHandler.Entitlements = nil+ t.Cleanup(func() { testHandler.Entitlements = prior })+ }+ for _, ep := range endpoints {+ rec := call(t, ep)+ if got := ep.count(t, rec.Body.Bytes()); got != tc.want {+ t.Errorf("%s: %d fixture runs, want %d", ep.path, got, tc.want)+ }+ if got := rec.Header().Get(HeaderDashboardHistoryLimit); got != tc.wantLimit {+ t.Errorf("%s: limit header %q, want %q", ep.path, got, tc.wantLimit)+ }+ if !ep.dated || tc.want != 1 {+ continue+ }+ var rows []struct {+ Date string `json:"date"`+ }+ _ = json.Unmarshal(rec.Body.Bytes(), &rows)+ for _, row := range rows {+ if row.Date < inside.Format("2006-01-02") {+ t.Errorf("%s: row dated %s is before the plan's first day %s", ep.path, row.Date, inside.Format("2006-01-02"))+ }+ }+ }+ })+ }+ })+ }+}++func ptrTo[T any](v T) *T { return &v }++func countTokens(t *testing.T, body []byte) int {+ t.Helper()+ var rows []struct {+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ }+ if err := json.Unmarshal(body, &rows); err != nil {+ t.Fatalf("decode: %v", err)+ }+ var tokens int64+ for _, row := range rows {+ if row.Model == "history-limit-model" {+ tokens += row.InputTokens+ }+ }+ return int(tokens / 100)+}++// Reads of usage/by-agent are recorded per workspace, day, requested and+// returned range, with the outcome under the limit.+func TestDashboardRangeViewsAreRecorded(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ read := func(t *testing.T, days int) {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.GetDashboardUsageByAgent(rec, newRequest(http.MethodGet, fmt.Sprintf("/api/dashboard/usage/by-agent?days=%d&tz=UTC", days), nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())+ }+ }+ type row struct {+ requested, returned int32+ views, observed, degraded, truncated int64+ limit *int32+ action string+ }+ waitRows := func(t *testing.T, wantViews int64) []row {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for {+ rows, err := testHandler.Queries.ListWorkspaceDashboardRangeViews(context.Background(), parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("list: %v", err)+ }+ var total int64+ out := make([]row, 0, len(rows))+ for _, r := range rows {+ total += r.ViewCount+ var limit *int32+ if r.LastLimitDays.Valid {+ v := r.LastLimitDays.Int32+ limit = &v+ }+ out = append(out, row{r.RequestedDays, r.ReturnedDays, r.ViewCount, r.ObservedOverLimitCount,+ r.DegradedOverLimitCount, r.TruncatedCount, limit, r.LastAction})+ }+ if total >= wantViews || time.Now().After(deadline) {+ return out+ }+ time.Sleep(20 * time.Millisecond)+ }+ }+ find := func(rows []row, requested, returned int32) row {+ for _, r := range rows {+ if r.requested == requested && r.returned == returned {+ return r+ }+ }+ return row{}+ }++ t.Run("enforce records requested and returned range", func(t *testing.T) {+ useDashboardHistoryLimit(t, historyDecision(entitlement.ActionEnforce, 30))+ read(t, 90)+ read(t, 90)+ read(t, 7)+ rows := waitRows(t, 3)+ cut := find(rows, 90, 30)+ if cut.views != 2 || cut.truncated != 2 || cut.observed != 0 || cut.limit == nil || *cut.limit != 30 || cut.action != "enforce" {+ t.Fatalf("90-day reads = %+v, want 2 views truncated to 30", cut)+ }+ if within := find(rows, 7, 7); within.views != 1 || within.truncated != 0 {+ t.Fatalf("7-day read = %+v", within)+ }+ })++ t.Run("observe and a downgraded enforce are counted apart", func(t *testing.T) {+ useDashboardHistoryLimit(t, historyDecision(entitlement.ActionObserve, 30))+ read(t, 90)+ rows := waitRows(t, 1)+ if got := find(rows, 90, 90); got.views != 1 || got.observed != 1 || got.degraded != 0 || got.truncated != 0 {+ t.Fatalf("observed read = %+v", got)+ }++ downgraded := historyDecision(entitlement.ActionObserve, 30)+ downgraded.Downgraded = true+ useDashboardHistoryLimit(t, downgraded)+ read(t, 90)+ rows = waitRows(t, 1)+ if got := find(rows, 90, 90); got.views != 1 || got.degraded != 1 || got.observed != 0 {+ t.Fatalf("downgraded read = %+v", got)+ }+ })++ t.Run("off still counts the read with no limit", func(t *testing.T) {+ useDashboardHistoryLimit(t, historyDecision(entitlement.ActionOff, 0))+ read(t, 365)+ rows := waitRows(t, 1)+ if got := find(rows, 365, 365); got.views != 1 || got.limit != nil || got.action != "off" {+ t.Fatalf("off read = %+v", got)+ }+ })++ t.Run("self-host writes nothing", func(t *testing.T) {+ clearDashboardRangeViews(t)+ prior := testHandler.Entitlements+ testHandler.Entitlements = nil+ t.Cleanup(func() { testHandler.Entitlements = prior })+ read(t, 90)+ time.Sleep(200 * time.Millisecond)+ if n := dbfx.Count(t, `SELECT count(*) FROM dashboard_range_view WHERE workspace_id = $1`, testWorkspaceID); n != 0 {+ t.Fatalf("self-host recorded %d rows", n)+ }+ })++ t.Run("a locked table never holds the response", func(t *testing.T) {+ useDashboardHistoryLimit(t, historyDecision(entitlement.ActionEnforce, 30))+ tx, err := testPool.Begin(context.Background())+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(context.Background())+ if _, err := tx.Exec(context.Background(), `LOCK TABLE dashboard_range_view IN ACCESS EXCLUSIVE MODE`); err != nil {+ t.Fatalf("lock: %v", err)+ }+ started := time.Now()+ read(t, 90)+ if elapsed := time.Since(started); elapsed > 300*time.Millisecond {+ t.Fatalf("GET took %s with the table locked; the record must stay off the request path", elapsed)+ }+ })+}++// Record drops the row, rather than waiting, when the table stays locked+// past its timeout.+func TestDashboardRangeViewRecordTimesOut(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ clearDashboardRangeViews(t)+ t.Cleanup(func() { clearDashboardRangeViews(t) })+ tx, err := testPool.Begin(context.Background())+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(context.Background())+ if _, err := tx.Exec(context.Background(), `LOCK TABLE dashboard_range_view IN ACCESS EXCLUSIVE MODE`); err != nil {+ t.Fatalf("lock: %v", err)+ }+ views := service.DashboardRangeViews{Queries: db.New(testPool), RecordTimeout: 100 * time.Millisecond}+ started := time.Now()+ views.Record(context.Background(), service.DashboardRangeView{+ WorkspaceID: parseUUID(testWorkspaceID), RequestedDays: 90, ReturnedDays: 30,+ Decision: historyDecision(entitlement.ActionEnforce, 30),+ })+ if elapsed := time.Since(started); elapsed > time.Second {+ t.Fatalf("Record took %s, want it bounded by its timeout", elapsed)+ }+}++func TestGetWorkspaceFeaturesReportsTheDashboardHistoryLimit(t *testing.T) {+ limit := func(t *testing.T) *int {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/features", nil), testUserID), "id", testWorkspaceID)+ var resp WorkspaceFeaturesResponse+ testutil.Call(t, testHandler.GetWorkspaceFeatures, req).Want(http.StatusOK).JSON(&resp)+ return resp.Limits.DashboardHistoryDays+ }+ t.Run("self-host", func(t *testing.T) {+ prior := testHandler.Entitlements+ testHandler.Entitlements = nil+ t.Cleanup(func() { testHandler.Entitlements = prior })+ if got := limit(t); got != nil {+ t.Fatalf("limit = %d, want null", *got)+ }+ })+ downgraded := historyDecision(entitlement.ActionObserve, 30)+ downgraded.Downgraded = true+ for name, tc := range map[string]struct {+ decision entitlement.Decision+ want *int+ }{+ "off": {historyDecision(entitlement.ActionOff, 0), nil},+ "observe": {historyDecision(entitlement.ActionObserve, 30), nil},+ "downgraded": {downgraded, nil},+ "enforce": {historyDecision(entitlement.ActionEnforce, 90), intPtr(90)},+ } {+ t.Run(name, func(t *testing.T) {+ useDashboardHistoryLimit(t, tc.decision)+ got := limit(t)+ if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) {+ t.Fatalf("limit = %v, want %v", got, tc.want)+ }+ })+ }+}++func intPtr(v int) *int { return &v }++// A record that lands after its workspace was deleted must not leave a row+// behind: the insert reads the workspace under FOR KEY SHARE, so it either+// waits for the deletion and finds nothing, or runs first and is deleted.+func TestDashboardRangeViewDoesNotOutliveItsWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ views := service.DashboardRangeViews{Queries: db.New(testPool), RecordTimeout: 10 * time.Second}+ record := func(workspaceID string) {+ views.Record(ctx, service.DashboardRangeView{+ WorkspaceID: parseUUID(workspaceID), RequestedDays: 90, ReturnedDays: 30,+ Decision: historyDecision(entitlement.ActionEnforce, 30),+ })+ }+ rows := func(workspaceID string) int {+ return dbfx.Count(t, `SELECT count(*) FROM dashboard_range_view WHERE workspace_id = $1`, workspaceID)+ }+ newWorkspace := func(t *testing.T) string {+ slug := "range-view-" + uuid.NewString()[:8]+ id := dbfx.Workspace(t, "range view", slug)+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM dashboard_range_view WHERE workspace_id = $1`, id)+ })+ return id+ }++ t.Run("after the deletion committed", func(t *testing.T) {+ id := newWorkspace(t)+ dbfx.Exec(t, `DELETE FROM workspace WHERE id = $1`, id)+ record(id)+ if n := rows(id); n != 0 {+ t.Fatalf("rows = %d for a deleted workspace", n)+ }+ })++ t.Run("racing a deletion in progress", func(t *testing.T) {+ id := newWorkspace(t)+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ // What DeleteWorkspace takes first.+ if _, err := tx.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, id); err != nil {+ t.Fatalf("lock: %v", err)+ }+ done := make(chan struct{})+ go func() {+ defer close(done)+ record(id)+ }()+ select {+ case <-done:+ t.Fatal("the record did not wait for the workspace lock")+ case <-time.After(300 * time.Millisecond):+ }+ if _, err := tx.Exec(ctx, `DELETE FROM dashboard_range_view WHERE workspace_id = $1`, id); err != nil {+ t.Fatalf("delete views: %v", err)+ }+ if _, err := tx.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, id); err != nil {+ t.Fatalf("delete workspace: %v", err)+ }+ if err := tx.Commit(ctx); err != nil {+ t.Fatalf("commit: %v", err)+ }+ <-done+ if n := rows(id); n != 0 {+ t.Fatalf("rows = %d after the workspace was deleted", n)+ }+ })+}diff --git a/server/internal/handler/paid_feature.go b/server/internal/handler/paid_feature.goindex d999ab43c6..c1eb7f8b61 100644--- a/server/internal/handler/paid_feature.go+++ b/server/internal/handler/paid_feature.go@@ -128,6 +128,16 @@ const (type WorkspaceFeaturesResponse struct {Features map[string]WorkspaceFeatureState `json:"features"`+ Limits WorkspaceFeatureLimits `json:"limits"`+}++// WorkspaceFeatureLimits are numeric plan limits clients render ahead of the+// server applying them. Each is null unless enforced, so an observed rollout+// stays invisible to users.+type WorkspaceFeatureLimits struct {+ // DashboardHistoryDays is how many calendar days back the dashboard can+ // read (dashboard_history.go).+ DashboardHistoryDays *int `json:"dashboard_history_days"`}// GetWorkspaceFeatures — GET /api/workspaces/{id}/features@@ -154,5 +164,6 @@ func (h *Handler) GetWorkspaceFeatures(w http.ResponseWriter, r *http.Request) {}resp.Features[string(feature)] = WorkspaceFeatureState{State: state}}+ resp.Limits.DashboardHistoryDays = h.dashboardHistoryLimitForClient(r.Context(), wsID)writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex e0de05e27e..69c9b6a162 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -365,7 +365,7 @@ func sinceFromDays(now time.Time, days int, loc *time.Location) time.Time {// bucket + N prior full days). If tzName is empty or unparseable, falls back// to UTC — never returns an error so handlers stay simple.func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {- return parseDaysCutoff(r, defaultDays, tzName, 0)+ return parseDaysCutoff(r, defaultDays, tzName, 0, maxDaysParam)}// parseExactSinceParamInTZ is parseSinceParamInTZ without the extra day of@@ -378,12 +378,32 @@ func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype// served off the N+1 cutoff silently covers one more day than the chart beside// it. Endpoints whose rows carry no date should use this variant instead.func parseExactSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {- return parseDaysCutoff(r, defaultDays, tzName, 1)+ return parseDaysCutoff(r, defaultDays, tzName, 1, maxDaysParam)+}++// maxDaysParam is the largest `days` the runtime usage endpoints accept.+const maxDaysParam = 365++// parseDaysParam reads `?days=N`. A missing, malformed, non-positive or+// larger-than-maxDays value falls back to defaultDays rather than erroring.+func parseDaysParam(r *http.Request, defaultDays, maxDays int) int {+ if d := r.URL.Query().Get("days"); d != "" {+ if parsed, err := strconv.Atoi(d); err == nil && parsed > 0 && parsed <= maxDays {+ return parsed+ }+ }+ return defaultDays+}++// loadViewingLocation resolves an IANA zone name, falling back to UTC.+func loadViewingLocation(tzName string) *time.Location {+ loc, err := time.LoadLocation(tzName)+ if err != nil || loc == nil {+ return time.UTC+ }+ return loc}-// parseDaysCutoff is the shared body of the two cutoff parsers. `trimDays`-// pulls the cutoff forward, so 0 keeps the N+1 headroom and 1 closes the-// window to exactly N calendar days.// dayWindowNow is the clock every `days=N` cutoff reads.//// A variable so a test can pin it. Without one, a fixture and the cutoff that@@ -394,22 +414,18 @@ func parseExactSinceParamInTZ(r *http.Request, defaultDays int, tzName string) p// wrote is excluded. Production always reads the real clock.var dayWindowNow = time.Now+// parseDaysCutoff is the shared body of the two cutoff parsers. `trimDays`+// pulls the cutoff forward, so 0 keeps the N+1 headroom and 1 closes the+// window to exactly N calendar days.func parseDaysCutoff(r *http.Request,defaultDays int,tzName string,trimDays int,+ maxDays 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- }- }- loc, err := time.LoadLocation(tzName)- if err != nil || loc == nil {- loc = time.UTC- }+ days := parseDaysParam(r, defaultDays, maxDays)+ loc := loadViewingLocation(tzName)// Guard the floor: days is already >= 1 here, and trimming a 1-day// window by one would put the cutoff at start-of-today+0 — still correct// ("today only"), which is exactly what days=1 means.diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 4443fa0892..690ce2782b 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1510,6 +1510,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "delete entitlement feature attempts",run: func() error { return qtx.DeleteWorkspaceEntitlementFeatureAttempts(ctx, requester.WorkspaceID) },},+ {+ name: "delete dashboard range views",+ run: func() error { return qtx.DeleteWorkspaceDashboardRangeViews(ctx, requester.WorkspaceID) },+ },{name: "delete chat messages",run: func() error { return qtx.DeleteWorkspaceChatMessages(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex b659c469f6..7a116ceb94 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -62,6 +62,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"contact_sales_inquiry": workspaceDeleteKeep,"daemon_connection": workspaceDelete,"daemon_token": workspaceDelete,+ "dashboard_range_view": workspaceDelete,"dingtalk_group_presence": workspaceDelete,"dingtalk_bot_identity": workspaceDelete,"dingtalk_group_route": workspaceDelete,diff --git a/server/internal/service/dashboard_range_view.go b/server/internal/service/dashboard_range_view.gonew file mode 100644index 0000000000..32a524064e--- /dev/null+++ b/server/internal/service/dashboard_range_view.go@@ -0,0 +1,102 @@+package service++import (+ "context"+ "log/slog"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// DashboardRangeOutcome is how a dashboard read related to the workspace's+// history limit (entitlement.GateDashboardHistoryDays).+type DashboardRangeOutcome string++const (+ // DashboardRangeWithin read no further back than the limit, or had none.+ DashboardRangeWithin DashboardRangeOutcome = "within"+ // DashboardRangeObserved read past the limit under a configured observe.+ DashboardRangeObserved DashboardRangeOutcome = "observed"+ // DashboardRangeDegraded read past the limit only because a stale cached+ // enforce had been downgraded to observe during a Cloud outage.+ DashboardRangeDegraded DashboardRangeOutcome = "degraded"+ // DashboardRangeTruncated asked past the limit and was cut to it.+ DashboardRangeTruncated DashboardRangeOutcome = "truncated"+)++// DashboardRangeOutcomeFor classifies a read of requestedDays under decision.+func DashboardRangeOutcomeFor(decision entitlement.Decision, requestedDays int) DashboardRangeOutcome {+ limit := decision.Gate.Limit+ if limit == nil || requestedDays <= *limit {+ return DashboardRangeWithin+ }+ switch decision.Gate.Action {+ case entitlement.ActionEnforce:+ return DashboardRangeTruncated+ case entitlement.ActionObserve:+ if decision.Downgraded {+ return DashboardRangeDegraded+ }+ return DashboardRangeObserved+ default:+ return DashboardRangeWithin+ }+}++// DashboardRangeView is one dashboard read: the range the viewer asked for,+// the range the response covered, and the limit decision it was served under.+type DashboardRangeView struct {+ WorkspaceID pgtype.UUID+ RequestedDays int+ ReturnedDays int+ Decision entitlement.Decision+}++// DashboardRangeViews records dashboard reads per workspace, UTC day and+// range, so the reach of the history limit can be measured per workspace.+type DashboardRangeViews struct {+ Queries *db.Queries+ // RecordTimeout bounds one Record; zero means defaultDashboardRangeViewRecordTimeout.+ RecordTimeout time.Duration+}++const defaultDashboardRangeViewRecordTimeout = 500 * time.Millisecond++// Record stores one read. It is best-effort and never part of the response:+// callers run it off the request path, it is detached from the request's+// cancellation, and a failure or timeout only drops the record.+func (v DashboardRangeViews) Record(ctx context.Context, view DashboardRangeView) {+ if v.Queries == nil || view.RequestedDays <= 0 || view.ReturnedDays <= 0 {+ return+ }+ timeout := v.RecordTimeout+ if timeout <= 0 {+ timeout = defaultDashboardRangeViewRecordTimeout+ }+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)+ defer cancel()+ outcome := DashboardRangeOutcomeFor(view.Decision, view.RequestedDays)+ var limit pgtype.Int4+ if view.Decision.Gate.Action != entitlement.ActionOff && view.Decision.Gate.Limit != nil {+ limit = pgtype.Int4{Int32: int32(*view.Decision.Gate.Limit), Valid: true}+ }+ err := v.Queries.RecordDashboardRangeView(ctx, db.RecordDashboardRangeViewParams{+ WorkspaceID: view.WorkspaceID,+ RequestedDays: int32(view.RequestedDays),+ ReturnedDays: int32(view.ReturnedDays),+ Outcome: string(outcome),+ LimitDays: limit,+ Action: string(view.Decision.Gate.Action),+ Reason: string(view.Decision.Reason),+ })+ if err != nil {+ slog.Warn("dashboard range view was not recorded; the response is unchanged",+ "workspace_id", util.UUIDToString(view.WorkspaceID),+ "outcome", string(outcome),+ "error", err,+ )+ }+}diff --git a/server/migrations/711_dashboard_range_view.down.sql b/server/migrations/711_dashboard_range_view.down.sqlnew file mode 100644index 0000000000..51698b966f--- /dev/null+++ b/server/migrations/711_dashboard_range_view.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS dashboard_range_view;diff --git a/server/migrations/711_dashboard_range_view.up.sql b/server/migrations/711_dashboard_range_view.up.sqlnew file mode 100644index 0000000000..b92d0bd7e5--- /dev/null+++ b/server/migrations/711_dashboard_range_view.up.sql@@ -0,0 +1,37 @@+-- Per-workspace record of the dashboard time ranges people look at, so the+-- reach of the plan-based history limit (dashboard_history_days) can be+-- measured per workspace: how many workspaces read past 30 or 90 days, and how+-- many would be cut short once the limit is enforced. Metrics carry no+-- workspace label, so this cannot live in Prometheus.+--+-- Written by GET /api/dashboard/usage/by-agent, once per page load or range+-- change, only when Multica Cloud is connected. Rows aggregate per UTC day,+-- requested day count (the range the viewer picked) and returned day count+-- (what the response actually covered after the limit).+--+-- view_count every recorded read+-- observed_over_limit_count read past the limit, admitted under a configured observe+-- degraded_over_limit_count read past the limit, admitted only because a stale+-- cached enforce was downgraded during a Cloud outage+-- truncated_count read past the limit, cut to the limit under enforce+--+-- The last_* columns describe the latest read. The scope unique index is built+-- concurrently in 712. No foreign keys (repo rule): workspace deletion removes+-- these rows explicitly.+CREATE TABLE IF NOT EXISTS dashboard_range_view (+ workspace_id UUID NOT NULL,+ day DATE NOT NULL,+ requested_days INTEGER NOT NULL CHECK (requested_days > 0),+ returned_days INTEGER NOT NULL CHECK (returned_days > 0),+ view_count BIGINT NOT NULL DEFAULT 0 CHECK (view_count >= 0),+ observed_over_limit_count BIGINT NOT NULL DEFAULT 0 CHECK (observed_over_limit_count >= 0),+ degraded_over_limit_count BIGINT NOT NULL DEFAULT 0 CHECK (degraded_over_limit_count >= 0),+ truncated_count BIGINT NOT NULL DEFAULT 0 CHECK (truncated_count >= 0),+ last_limit_days INTEGER,+ last_action TEXT NOT NULL,+ last_reason TEXT NOT NULL,+ first_viewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ last_viewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/712_dashboard_range_view_scope_idx.down.sql b/server/migrations/712_dashboard_range_view_scope_idx.down.sqlnew file mode 100644index 0000000000..79c7e7fa5b--- /dev/null+++ b/server/migrations/712_dashboard_range_view_scope_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_dashboard_range_view_scope;diff --git a/server/migrations/712_dashboard_range_view_scope_idx.up.sql b/server/migrations/712_dashboard_range_view_scope_idx.up.sqlnew file mode 100644index 0000000000..a63ebcea85--- /dev/null+++ b/server/migrations/712_dashboard_range_view_scope_idx.up.sql@@ -0,0 +1,3 @@+-- Upsert key for RecordDashboardRangeView and the per-workspace lookup.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_dashboard_range_view_scope+ ON dashboard_range_view (workspace_id, day, requested_days, returned_days);diff --git a/server/pkg/db/generated/dashboard_range_view.sql.go b/server/pkg/db/generated/dashboard_range_view.sql.gonew file mode 100644index 0000000000..16193345ef--- /dev/null+++ b/server/pkg/db/generated/dashboard_range_view.sql.go@@ -0,0 +1,117 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: dashboard_range_view.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const listWorkspaceDashboardRangeViews = `-- name: ListWorkspaceDashboardRangeViews :many+SELECT workspace_id, day, requested_days, returned_days, view_count, observed_over_limit_count, degraded_over_limit_count, truncated_count, last_limit_days, last_action, last_reason, first_viewed_at, last_viewed_at, created_at, updated_at FROM dashboard_range_view+WHERE workspace_id = $1+ORDER BY day DESC, requested_days, returned_days+`++// Every recorded day of one workspace, newest first.+func (q *Queries) ListWorkspaceDashboardRangeViews(ctx context.Context, workspaceID pgtype.UUID) ([]DashboardRangeView, error) {+ rows, err := q.db.Query(ctx, listWorkspaceDashboardRangeViews, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []DashboardRangeView{}+ for rows.Next() {+ var i DashboardRangeView+ if err := rows.Scan(+ &i.WorkspaceID,+ &i.Day,+ &i.RequestedDays,+ &i.ReturnedDays,+ &i.ViewCount,+ &i.ObservedOverLimitCount,+ &i.DegradedOverLimitCount,+ &i.TruncatedCount,+ &i.LastLimitDays,+ &i.LastAction,+ &i.LastReason,+ &i.FirstViewedAt,+ &i.LastViewedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const recordDashboardRangeView = `-- name: RecordDashboardRangeView :exec+INSERT INTO dashboard_range_view (+ workspace_id, day, requested_days, returned_days,+ view_count, observed_over_limit_count, degraded_over_limit_count, truncated_count,+ last_limit_days, last_action, last_reason,+ first_viewed_at, last_viewed_at+)+SELECT+ w.id, (now() AT TIME ZONE 'UTC')::date, $1, $2,+ 1,+ CASE WHEN $3::text = 'observed' THEN 1 ELSE 0 END,+ CASE WHEN $3::text = 'degraded' THEN 1 ELSE 0 END,+ CASE WHEN $3::text = 'truncated' THEN 1 ELSE 0 END,+ $4, $5, $6,+ now(), now()+FROM workspace w+WHERE w.id = $7+FOR KEY SHARE OF w+ON CONFLICT (workspace_id, day, requested_days, returned_days) DO UPDATE+SET view_count = dashboard_range_view.view_count + 1,+ observed_over_limit_count = dashboard_range_view.observed_over_limit_count + EXCLUDED.observed_over_limit_count,+ degraded_over_limit_count = dashboard_range_view.degraded_over_limit_count + EXCLUDED.degraded_over_limit_count,+ truncated_count = dashboard_range_view.truncated_count + EXCLUDED.truncated_count,+ last_limit_days = EXCLUDED.last_limit_days,+ last_action = EXCLUDED.last_action,+ last_reason = EXCLUDED.last_reason,+ last_viewed_at = now(),+ updated_at = now()+`++type RecordDashboardRangeViewParams struct {+ RequestedDays int32 `json:"requested_days"`+ ReturnedDays int32 `json:"returned_days"`+ Outcome string `json:"outcome"`+ LimitDays pgtype.Int4 `json:"limit_days"`+ Action string `json:"action"`+ Reason string `json:"reason"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// One dashboard read. outcome is within (inside the limit, or no limit),+// observed (past the limit, admitted under a configured observe), degraded+// (past the limit, admitted because a stale enforce was downgraded) or+// truncated (past the limit, cut to it under enforce).+//+// The row is selected from its workspace under FOR KEY SHARE, which conflicts+// with the FOR UPDATE workspace deletion takes first. A record that runs after+// the deletion committed finds no workspace and inserts nothing; one that runs+// first makes the deletion wait and is then removed by it.+func (q *Queries) RecordDashboardRangeView(ctx context.Context, arg RecordDashboardRangeViewParams) error {+ _, err := q.db.Exec(ctx, recordDashboardRangeView,+ arg.RequestedDays,+ arg.ReturnedDays,+ arg.Outcome,+ arg.LimitDays,+ arg.Action,+ arg.Reason,+ arg.WorkspaceID,+ )+ return err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 87be2c0a2b..417e1cf513 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -810,6 +810,24 @@ type DaemonToken struct {OwnerID pgtype.UUID `json:"owner_id"`}+type DashboardRangeView struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Day pgtype.Date `json:"day"`+ RequestedDays int32 `json:"requested_days"`+ ReturnedDays int32 `json:"returned_days"`+ ViewCount int64 `json:"view_count"`+ ObservedOverLimitCount int64 `json:"observed_over_limit_count"`+ DegradedOverLimitCount int64 `json:"degraded_over_limit_count"`+ TruncatedCount int64 `json:"truncated_count"`+ LastLimitDays pgtype.Int4 `json:"last_limit_days"`+ LastAction string `json:"last_action"`+ LastReason string `json:"last_reason"`+ FirstViewedAt pgtype.Timestamptz `json:"first_viewed_at"`+ LastViewedAt pgtype.Timestamptz `json:"last_viewed_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type DingtalkBotIdentity struct {WorkspaceID pgtype.UUID `json:"workspace_id"`InstallationID pgtype.UUID `json:"installation_id"`diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex be66ef845f..f09210560a 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -235,6 +235,16 @@ func (q *Queries) DeleteWorkspaceConnections(ctx context.Context, workspaceID pgreturn err}+const deleteWorkspaceDashboardRangeViews = `-- name: DeleteWorkspaceDashboardRangeViews :exec+DELETE FROM dashboard_range_view+WHERE dashboard_range_view.workspace_id = $1+`++func (q *Queries) DeleteWorkspaceDashboardRangeViews(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteWorkspaceDashboardRangeViews, workspaceID)+ return err+}+const deleteWorkspaceEntitlementFeatureAttempts = `-- name: DeleteWorkspaceEntitlementFeatureAttempts :execDELETE FROM entitlement_feature_attemptWHERE entitlement_feature_attempt.workspace_id = $1diff --git a/server/pkg/db/queries/dashboard_range_view.sql b/server/pkg/db/queries/dashboard_range_view.sqlnew file mode 100644index 0000000000..2340016ace--- /dev/null+++ b/server/pkg/db/queries/dashboard_range_view.sql@@ -0,0 +1,43 @@+-- name: RecordDashboardRangeView :exec+-- One dashboard read. outcome is within (inside the limit, or no limit),+-- observed (past the limit, admitted under a configured observe), degraded+-- (past the limit, admitted because a stale enforce was downgraded) or+-- truncated (past the limit, cut to it under enforce).+--+-- The row is selected from its workspace under FOR KEY SHARE, which conflicts+-- with the FOR UPDATE workspace deletion takes first. A record that runs after+-- the deletion committed finds no workspace and inserts nothing; one that runs+-- first makes the deletion wait and is then removed by it.+INSERT INTO dashboard_range_view (+ workspace_id, day, requested_days, returned_days,+ view_count, observed_over_limit_count, degraded_over_limit_count, truncated_count,+ last_limit_days, last_action, last_reason,+ first_viewed_at, last_viewed_at+)+SELECT+ w.id, (now() AT TIME ZONE 'UTC')::date, @requested_days, @returned_days,+ 1,+ CASE WHEN @outcome::text = 'observed' THEN 1 ELSE 0 END,+ CASE WHEN @outcome::text = 'degraded' THEN 1 ELSE 0 END,+ CASE WHEN @outcome::text = 'truncated' THEN 1 ELSE 0 END,+ sqlc.narg('limit_days'), @action, @reason,+ now(), now()+FROM workspace w+WHERE w.id = @workspace_id+FOR KEY SHARE OF w+ON CONFLICT (workspace_id, day, requested_days, returned_days) DO UPDATE+SET view_count = dashboard_range_view.view_count + 1,+ observed_over_limit_count = dashboard_range_view.observed_over_limit_count + EXCLUDED.observed_over_limit_count,+ degraded_over_limit_count = dashboard_range_view.degraded_over_limit_count + EXCLUDED.degraded_over_limit_count,+ truncated_count = dashboard_range_view.truncated_count + EXCLUDED.truncated_count,+ last_limit_days = EXCLUDED.last_limit_days,+ last_action = EXCLUDED.last_action,+ last_reason = EXCLUDED.last_reason,+ last_viewed_at = now(),+ updated_at = now();++-- name: ListWorkspaceDashboardRangeViews :many+-- Every recorded day of one workspace, newest first.+SELECT * FROM dashboard_range_view+WHERE workspace_id = @workspace_id+ORDER BY day DESC, requested_days, returned_days;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 664f61b5aa..34270cbcb9 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -654,6 +654,10 @@ WHERE entitlement_limit_overage.workspace_id = $1;DELETE FROM entitlement_feature_attemptWHERE entitlement_feature_attempt.workspace_id = $1;+-- name: DeleteWorkspaceDashboardRangeViews :exec+DELETE FROM dashboard_range_view+WHERE dashboard_range_view.workspace_id = $1;+-- name: DeleteWorkspaceAutopilotChildren :execWITHdeleted_triggers AS (