Skip to content

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

Go

feat(runtimes): show Claude Code and Codex plan limits on runtime pages (MUL-9427) (#10752)

Multica Eve71683141a764
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index bf5e1daa55..2058ab3643 100644
--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx
@@ -107,6 +107,8 @@ Une fois une limite atteinte, les nouvelles exécutions restent en file d'attent
La consommation de tokens, les coûts et les échecs des exécutions sont regroupés par espace de travail sur la page [Statistiques](/analytics) ; `multica runtime usage <runtime-id>` affiche la consommation de tokens d'un seul runtime.
+Pour les runtimes Claude Code et Codex, la page du runtime affiche aussi les **Limites** : la part déjà utilisée des fenêtres de 5 heures et hebdomadaire du forfait du compte de la CLI, leur prochaine réinitialisation, et si la consommation va plus vite que le temps écoulé. La CLI les signale pendant l'exécution des tâches : les valeurs datent donc de la dernière exécution du runtime. Les comptes à clé API n'ont pas de limites de forfait.
+
## Configuration MCP locale [#local-mcp]
Quand aucune configuration MCP n'est enregistrée sur un agent, Multica ne transmet aucun réglage MCP et l'outil lit comme d'habitude sa propre configuration sur cette machine.
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index d52c4680f5..f42db04bbc 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -107,6 +107,8 @@ multica daemon autostart disable
実行で使われたトークン、費用、失敗はワークスペースごとに[分析](/analytics)ページにまとまっています。1 つのランタイムのトークン使用量は `multica runtime usage <runtime-id>` でも確認できます。
+Claude Code と Codex のランタイムのページには**利用上限**も表示されます。CLI のアカウントがプランの 5 時間セッションと週間の枠をどれだけ使ったか、いつリセットされるか、使用量が経過時間より速く進んでいるかがわかります。値は CLI がタスク実行中に報告するもので、ランタイムの最新の実行時点のものです。API キーのアカウントにはプランの上限はありません。
+
## ローカルの MCP 設定 [#local-mcp]
エージェントに MCP 設定が保存されていない場合、Multica は MCP の設定を何も渡さず、ツールはそのコンピューター上の自身の設定をいつもどおり読み込みます。
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index 700468c168..a7b086970d 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -107,6 +107,8 @@ multica daemon autostart disable
실행에 쓰인 토큰, 비용, 실패는 워크스페이스별로 [분석](/analytics) 페이지에 모여 있습니다. 런타임 하나의 토큰 사용량은 `multica runtime usage <runtime-id>`로도 볼 수 있습니다.
+Claude Code와 Codex 런타임 페이지에는 **한도**도 표시됩니다. CLI 계정이 요금제의 5시간 세션과 주간 한도를 얼마나 썼는지, 언제 초기화되는지, 사용량이 경과 시간보다 빠르게 늘고 있는지 보여 줍니다. 이 값은 CLI가 작업을 실행하는 동안 보고하므로 런타임의 최근 실행 시점 기준입니다. API 키 계정에는 요금제 한도가 없습니다.
+
## 로컬 MCP 설정 [#local-mcp]
에이전트에 MCP 설정이 저장되어 있지 않으면 Multica는 MCP 설정을 전혀 전달하지 않고, 도구는 평소처럼 그 컴퓨터에 있는 자체 설정을 읽습니다.
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index c13751701b..b75e2bffe7 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -107,6 +107,8 @@ Once a limit is reached, new runs keep queueing. Adjust a single agent's concurr
Token usage, cost, and failures across runs are summarized per workspace on the [Analytics](/analytics) page; `multica runtime usage <runtime-id>` shows token usage for a single runtime.
+For Claude Code and Codex runtimes, the runtime's page also shows **Limits**: how much of the plan's 5-hour session and weekly windows the CLI account has used, when each resets, and whether usage is running ahead of the time elapsed. The CLI reports these while it runs tasks, so the numbers are as of the runtime's latest run. API-key accounts have no plan limits to show.
+
## Local MCP configuration [#local-mcp]
When an agent has no MCP configuration saved, Multica passes no MCP settings and the tool reads its own configuration on that computer as usual.
diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
index c2b9c6b621..9416ee56a4 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
@@ -108,6 +108,8 @@ multica daemon autostart disable
執行消耗的 token、費用和失敗情況在[統計](/analytics)頁按工作區彙總;單條執行時的 token 用量也可以用 `multica runtime usage <runtime-id>` 檢視。
+Claude Code 和 Codex 執行時的頁面上還有**額度**:CLI 帳號在方案的 5 小時工作階段和每週視窗裡已經用了多少、什麼時候重置,以及用量是否跑在時間前面。這些資料由 CLI 在執行任務時回報,反映的是這個執行時最近一次執行時的狀態。API Key 帳號沒有方案額度。
+
## 本機 MCP 配置 [#local-mcp]
AI 代理沒有儲存 MCP 配置時,Multica 不向工具傳任何 MCP 設定,工具照常讀取這臺電腦上它自己的配置。
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index bbe0009305..275eeb7f99 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -108,6 +108,8 @@ multica daemon autostart disable
运行消耗的 token、费用和失败情况在[统计](/analytics)页按工作区汇总;单条运行时的 token 用量也可以用 `multica runtime usage <runtime-id>` 查看。
+Claude Code 和 Codex 运行时的页面上还有**额度**:CLI 账号在套餐的 5 小时会话和每周窗口里已经用了多少、什么时候重置,以及用量是否跑在时间前面。这些数据由 CLI 在执行任务时上报,反映的是这个运行时最近一次运行时的状态。API Key 账号没有套餐额度。
+
## 本机 MCP 配置 [#local-mcp]
智能体没有保存 MCP 配置时,Multica 不向工具传任何 MCP 设置,工具照常读取这台电脑上它自己的配置。
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2a7457d63b..a4a4a43e00 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -104,6 +104,7 @@ import type {
AssigneeFrequencyEntry,
TaskMessagePayload,
TaskContextReceiptResponse,
+ RuntimeRateLimitsResponse,
Attachment,
ChatSession,
ChatPinnedAgent,
@@ -384,6 +385,7 @@ import {
RuntimeUsageByAgentListSchema,
RuntimeUsageByHourListSchema,
RuntimeUsageListSchema,
+ RuntimeRateLimitsResponseSchema,
SearchIssuesResponseSchema,
ProjectSchema,
ArchiveProjectResponseSchema,
@@ -2726,6 +2728,16 @@ export class ApiClient {
);
}
+ async getRuntimeRateLimits(runtimeId: string): Promise<RuntimeRateLimitsResponse> {
+ const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}/rate-limits`);
+ return parseWithFallback<RuntimeRateLimitsResponse>(
+ raw,
+ RuntimeRateLimitsResponseSchema,
+ { rate_limits: null },
+ { endpoint: "GET /api/runtimes/:id/rate-limits" },
+ );
+ }
+
async getRuntimeUsage(
runtimeId: string,
params?: { days?: number; tz?: string },
diff --git a/packages/core/api/runtime-rate-limits-schema.test.ts b/packages/core/api/runtime-rate-limits-schema.test.ts
new file mode 100644
index 0000000000..0d748de088
--- /dev/null
+++ b/packages/core/api/runtime-rate-limits-schema.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { RuntimeRateLimitsResponseSchema } from "./schemas";
+
+describe("RuntimeRateLimitsResponseSchema", () => {
+ it("passes a null snapshot through", () => {
+ expect(RuntimeRateLimitsResponseSchema.parse({ rate_limits: null })).toEqual({ rate_limits: null });
+ });
+
+ it("degrades unknown values and drops malformed windows", () => {
+ const parsed = RuntimeRateLimitsResponseSchema.parse({
+ rate_limits: {
+ plan_type: "pro",
+ status: "throttled_by_future_server",
+ windows: [
+ { kind: "session", used_percent: 72, window_minutes: 300, resets_at: "2026-11-16T06:00:00Z", status: "warning" },
+ { kind: "monthly", used_percent: "lots", window_minutes: 43200 },
+ "not a window",
+ ],
+ credits: { has_credits: true, unlimited: false, balance: "240" },
+ observed_at: "2026-11-16T03:46:00Z",
+ },
+ });
+ const rl = parsed.rate_limits;
+ expect(rl?.status).toBe("");
+ expect(rl?.windows).toHaveLength(2);
+ expect(rl?.windows[0]).toMatchObject({ kind: "session", used_percent: 72, status: "warning" });
+ expect(rl?.windows[1]).toMatchObject({ kind: "other", used_percent: undefined, window_minutes: 43200, status: "" });
+ expect(rl?.credits?.balance).toBe("240");
+ });
+
+ it("falls back to null when the snapshot itself is unusable", () => {
+ expect(RuntimeRateLimitsResponseSchema.parse({ rate_limits: { windows: [] } })).toEqual({ rate_limits: null });
+ expect(RuntimeRateLimitsResponseSchema.parse({ rate_limits: "nope" })).toEqual({ rate_limits: null });
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 5dee562816..30b93743bd 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2307,6 +2307,52 @@ const RuntimeUsageByHourSchema = z.object({
export const RuntimeUsageByHourListSchema = z.array(RuntimeUsageByHourSchema);
+// Runtime rate limits (`GET /api/runtimes/:id/rate-limits`). Unknown window
+// kinds and statuses from a newer server degrade to "other" / "" instead of
+// failing the whole response, and a malformed window is dropped on its own.
+const RuntimeRateLimitStatusSchema = z
+ .enum(["allowed", "warning", "rejected", ""])
+ .catch("");
+
+const RuntimeRateLimitWindowSchema = z.object({
+ kind: z
+ .enum(["session", "weekly", "weekly_opus", "weekly_sonnet", "other"])
+ .catch("other"),
+ used_percent: z.number().optional().catch(undefined),
+ window_minutes: z.number().default(0).catch(0),
+ resets_at: z.string().optional().catch(undefined),
+ status: RuntimeRateLimitStatusSchema.default(""),
+}).loose();
+
+const RuntimeRateLimitsSchema = z.object({
+ plan_type: z.string().default("").catch(""),
+ status: RuntimeRateLimitStatusSchema.default(""),
+ windows: z
+ .array(z.unknown())
+ .catch([])
+ .default([])
+ .transform((rows) =>
+ rows.flatMap((row) => {
+ const parsed = RuntimeRateLimitWindowSchema.safeParse(row);
+ return parsed.success ? [parsed.data] : [];
+ }),
+ ),
+ credits: z
+ .object({
+ has_credits: z.boolean().default(false),
+ unlimited: z.boolean().default(false),
+ balance: z.string().default(""),
+ })
+ .loose()
+ .optional()
+ .catch(undefined),
+ observed_at: z.string(),
+}).loose();
+
+export const RuntimeRateLimitsResponseSchema = z.object({
+ rate_limits: RuntimeRateLimitsSchema.nullable().catch(null),
+}).loose();
+
// Agent task responses. The base object stays loose so daemon/runtime fields
// can drift while task-list consumers still validate the fields they render.
diff --git a/packages/core/package.json b/packages/core/package.json
index 1a6cff429a..dc46cb7630 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -94,6 +94,7 @@
"./runtimes/queries": "./runtimes/queries.ts",
"./runtimes/mutations": "./runtimes/mutations.ts",
"./runtimes/custom-pricing-store": "./runtimes/custom-pricing-store.ts",
+ "./runtimes/rate-limits": "./runtimes/rate-limits.ts",
"./dashboard": "./dashboard/index.ts",
"./dashboard/queries": "./dashboard/queries.ts",
"./agents": "./agents/index.ts",
diff --git a/packages/core/runtimes/queries.ts b/packages/core/runtimes/queries.ts
index ec8f16d043..443aa4d5ea 100644
--- a/packages/core/runtimes/queries.ts
+++ b/packages/core/runtimes/queries.ts
@@ -12,8 +12,21 @@ export const runtimeKeys = {
// by-hour now follows the viewer's tz, like the other reports.
usageByHour: (rid: string, days: number, tz: string) =>
["runtimes", "usage", "by-hour", rid, days, tz] as const,
+ rateLimits: (rid: string) => ["runtimes", "rate-limits", rid] as const,
};
+// The daemon posts a runtime's rate limits while its tasks run, so the
+// snapshot only moves while something is running. A slow poll keeps an open
+// page roughly in step without a realtime event.
+export function runtimeRateLimitsOptions(runtimeId: string) {
+ return queryOptions({
+ queryKey: runtimeKeys.rateLimits(runtimeId),
+ queryFn: () => api.getRuntimeRateLimits(runtimeId),
+ staleTime: 30 * 1000,
+ refetchInterval: 60 * 1000,
+ });
+}
+
// `tz` is the viewer's IANA name — all reports follow the viewer's tz.
export function runtimeUsageOptions(
runtimeId: string,
diff --git a/packages/core/runtimes/rate-limits.test.ts b/packages/core/runtimes/rate-limits.test.ts
new file mode 100644
index 0000000000..d611087aa1
--- /dev/null
+++ b/packages/core/runtimes/rate-limits.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { RuntimeRateLimitWindow } from "../types";
+import {
+ describeRateLimitWindow,
+ runtimeReportsRateLimits,
+ tightestRateLimitWindow,
+} from "./rate-limits";
+
+const HOUR = 60 * 60_000;
+// The 5-hour window below runs 09:00-14:00 UTC.
+const RESET = Date.parse("2026-11-16T14:00:00Z");
+
+function session(used: number | undefined, extra: Partial<RuntimeRateLimitWindow> = {}): RuntimeRateLimitWindow {
+ return {
+ kind: "session",
+ used_percent: used,
+ window_minutes: 300,
+ resets_at: new Date(RESET).toISOString(),
+ status: "",
+ ...extra,
+ };
+}
+
+describe("describeRateLimitWindow", () => {
+ it("projects when a window that runs ahead of pace will run out", () => {
+ // 72% used at 11:46, 2h46m (55%) into the window.
+ const observed = new Date(RESET - 2 * HOUR - 14 * 60_000).toISOString();
+ const view = describeRateLimitWindow(session(72), observed, Date.parse(observed));
+ expect(view.tone).toBe("warning");
+ expect(view.elapsedPercent).toBeCloseTo(55.3, 0);
+ expect(view.aheadOfPace).toBe(17);
+ // 28% left at 72%/166min burns in ~65 minutes, before the 14:00 reset.
+ expect(view.runsOutInMinutes).toBe(65);
+ expect(view.resetsInMinutes).toBe(134);
+ });
+
+ it("counts the projection from now, not from the report", () => {
+ const observed = RESET - 2 * HOUR - 14 * 60_000;
+ const view = describeRateLimitWindow(session(72), new Date(observed).toISOString(), observed + 20 * 60_000);
+ expect(view.runsOutInMinutes).toBe(45);
+ });
+
+ it("gives no runout when usage stays behind the elapsed time", () => {
+ const observed = new Date(RESET - 2 * HOUR).toISOString();
+ const view = describeRateLimitWindow(session(40), observed, Date.parse(observed));
+ expect(view.tone).toBe("normal");
+ expect(view.aheadOfPace).toBeUndefined();
+ expect(view.runsOutInMinutes).toBeUndefined();
+ });
+
+ it("ignores usage within the pace tolerance", () => {
+ // 84% used 4h in (80% elapsed) is ahead by less than the tolerance.
+ const observed = new Date(RESET - HOUR).toISOString();
+ const close = describeRateLimitWindow(session(84), observed, Date.parse(observed));
+ expect(close.aheadOfPace).toBeUndefined();
+ const over = describeRateLimitWindow(session(86), observed, Date.parse(observed));
+ expect(over.aheadOfPace).toBe(6);
+ // 14% left at 86%/240min lasts ~39 minutes.
+ expect(over.runsOutInMinutes).toBe(39);
+ });
+
+ it("marks a limited window critical without a pace verdict", () => {
+ const observed = new Date(RESET - HOUR).toISOString();
+ for (const window of [session(100), session(40, { status: "rejected" })]) {
+ const view = describeRateLimitWindow(window, observed, Date.parse(observed));
+ expect(view.limited).toBe(true);
+ expect(view.tone).toBe("critical");
+ expect(view.aheadOfPace).toBeUndefined();
+ }
+ });
+
+ it("drops the usage of a window that reset after the report", () => {
+ const view = describeRateLimitWindow(session(95), new Date(RESET - HOUR).toISOString(), RESET + 60_000);
+ expect(view.hasReset).toBe(true);
+ expect(view.used).toBeUndefined();
+ expect(view.tone).toBe("normal");
+ expect(view.limited).toBe(false);
+ expect(view.resetsInMinutes).toBeUndefined();
+ });
+
+ it("uses the provider's warning status when no share is reported", () => {
+ const observed = new Date(RESET - HOUR).toISOString();
+ const view = describeRateLimitWindow(session(undefined, { status: "warning" }), observed, Date.parse(observed));
+ expect(view.tone).toBe("warning");
+ expect(view.used).toBeUndefined();
+ });
+
+ it("skips the pace verdict without a duration or reset", () => {
+ const observed = new Date(RESET - HOUR).toISOString();
+ expect(describeRateLimitWindow(session(80, { window_minutes: 0 }), observed, Date.parse(observed)).elapsedPercent).toBeUndefined();
+ expect(describeRateLimitWindow(session(80, { resets_at: undefined }), observed, Date.parse(observed)).elapsedPercent).toBeUndefined();
+ });
+});
+
+describe("tightestRateLimitWindow", () => {
+ const observed = new Date(RESET - HOUR).toISOString();
+ const now = Date.parse(observed);
+
+ it("picks the highest share, and a limited window over any share", () => {
+ const weekly = describeRateLimitWindow({ ...session(93), kind: "weekly", window_minutes: 10080 }, observed, now);
+ const five = describeRateLimitWindow(session(18), observed, now);
+ expect(tightestRateLimitWindow([five, weekly])).toBe(weekly);
+ const limited = describeRateLimitWindow(session(undefined, { status: "rejected" }), observed, now);
+ expect(tightestRateLimitWindow([weekly, limited])).toBe(limited);
+ expect(tightestRateLimitWindow([])).toBeUndefined();
+ });
+});
+
+describe("runtimeReportsRateLimits", () => {
+ it("covers the CLIs that report rate limits", () => {
+ expect(runtimeReportsRateLimits("claude")).toBe(true);
+ expect(runtimeReportsRateLimits("codex")).toBe(true);
+ expect(runtimeReportsRateLimits("cursor")).toBe(false);
+ });
+});
diff --git a/packages/core/runtimes/rate-limits.ts b/packages/core/runtimes/rate-limits.ts
new file mode 100644
index 0000000000..cd34ec7001
--- /dev/null
+++ b/packages/core/runtimes/rate-limits.ts
@@ -0,0 +1,107 @@
+import type { RuntimeRateLimitWindow } from "../types";
+
+// Runtime rate limits (MUL-9427): the plan windows (5-hour session, weekly)
+// of the account a runtime's agent CLI runs under, as the CLI last reported
+// them. These helpers turn one reported window into what the UI shows: tone,
+// whether usage runs ahead of the time elapsed, and when it would run out.
+
+/** Providers whose CLI reports rate limits that the daemon forwards. */
+const RATE_LIMIT_PROVIDERS = new Set(["claude", "codex"]);
+
+export function runtimeReportsRateLimits(provider: string): boolean {
+ return RATE_LIMIT_PROVIDERS.has(provider);
+}
+
+export const RATE_LIMIT_WARNING_PERCENT = 70;
+export const RATE_LIMIT_CRITICAL_PERCENT = 90;
+/** Usage this many points ahead of the elapsed time counts as over pace. */
+export const RATE_LIMIT_PACE_TOLERANCE = 5;
+/** Below this share of the window elapsed, a pace verdict is noise. */
+const MIN_ELAPSED_FOR_PACE = 0.03;
+
+export type RateLimitTone = "normal" | "warning" | "critical";
+
+export interface RateLimitWindowView {
+ window: RuntimeRateLimitWindow;
+ /** Reported share used, 0-100. Undefined when the CLI did not say. */
+ used?: number;
+ /** The window reset after the report, so its usage belongs to the last one. */
+ hasReset: boolean;
+ /** At or past the limit: the provider rejected requests or usage hit 100%. */
+ limited: boolean;
+ tone: RateLimitTone;
+ /** Share of the window elapsed when the usage was reported, 0-100. */
+ elapsedPercent?: number;
+ /** Points by which usage ran ahead of the elapsed time (only when ahead). */
+ aheadOfPace?: number;
+ /** Minutes from now until the window runs out at the reported pace (only when ahead). */
+ runsOutInMinutes?: number;
+ /** Minutes from now until the window resets. */
+ resetsInMinutes?: number;
+}
+
+function parseTime(value: string | undefined): number | undefined {
+ if (!value) return undefined;
+ const ms = Date.parse(value);
+ return Number.isFinite(ms) ? ms : undefined;
+}
+
+export function describeRateLimitWindow(
+ window: RuntimeRateLimitWindow,
+ observedAt: string,
+ now: number,
+): RateLimitWindowView {
+ const resetMs = parseTime(window.resets_at);
+ const observedMs = parseTime(observedAt) ?? now;
+ const hasReset = resetMs !== undefined && resetMs <= now;
+ const used = hasReset ? undefined : window.used_percent;
+ const limited =
+ !hasReset && (window.status === "rejected" || (used !== undefined && used >= 100));
+
+ let tone: RateLimitTone = "normal";
+ if (limited || (used !== undefined && used >= RATE_LIMIT_CRITICAL_PERCENT)) {
+ tone = "critical";
+ } else if (
+ !hasReset &&
+ (window.status === "warning" || (used !== undefined && used >= RATE_LIMIT_WARNING_PERCENT))
+ ) {
+ tone = "warning";
+ }
+
+ const view: RateLimitWindowView = { window, used, hasReset, limited, tone };
+ if (resetMs !== undefined && !hasReset) {
+ view.resetsInMinutes = Math.max(0, Math.round((resetMs - now) / 60_000));
+ }
+
+ const windowMs = window.window_minutes * 60_000;
+ if (hasReset || resetMs === undefined || windowMs <= 0) return view;
+ const startMs = resetMs - windowMs;
+ const elapsed = Math.min(1, Math.max(0, (observedMs - startMs) / windowMs));
+ view.elapsedPercent = elapsed * 100;
+ if (used === undefined || limited || elapsed < MIN_ELAPSED_FOR_PACE) return view;
+
+ const ahead = used - view.elapsedPercent;
+ if (ahead < RATE_LIMIT_PACE_TOLERANCE) return view;
+ view.aheadOfPace = Math.round(ahead);
+ // Project the observed burn rate forward from the moment it was observed.
+ // Running ahead of the elapsed time always runs out before the reset.
+ const usedPerMs = used / (observedMs - startMs);
+ const runsOutAt = observedMs + (100 - used) / usedPerMs;
+ view.runsOutInMinutes = Math.max(0, Math.round((runsOutAt - now) / 60_000));
+ return view;
+}
+
+/**
+ * The window closest to its limit, which is what a one-line summary shows.
+ * A limited window always wins; windows without a reported share rank last.
+ */
+export function tightestRateLimitWindow(
+ views: readonly RateLimitWindowView[],
+): RateLimitWindowView | undefined {
+ let best: RateLimitWindowView | undefined;
+ const rank = (v: RateLimitWindowView) => (v.limited ? 1000 : (v.used ?? -1));
+ for (const view of views) {
+ if (!best || rank(view) > rank(best)) best = view;
+ }
+ return best;
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index b6e1d37729..65118f46bb 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -1068,6 +1068,41 @@ export interface RuntimeHourlyActivity {
count: number;
}
+// Subscription rate limits of the account a runtime's agent CLI runs under
+// (`GET /api/runtimes/:id/rate-limits`, MUL-9427), as the CLI last reported
+// them during a task. Window kinds and statuses fall back to "other" / ""
+// when a newer server sends a value this client does not know.
+export type RuntimeRateLimitWindowKind =
+ | "session"
+ | "weekly"
+ | "weekly_opus"
+ | "weekly_sonnet"
+ | "other";
+
+export type RuntimeRateLimitStatus = "allowed" | "warning" | "rejected" | "";
+
+export interface RuntimeRateLimitWindow {
+ kind: RuntimeRateLimitWindowKind;
+ /** 0-100; can run slightly past 100. Absent when the CLI did not say. */
+ used_percent?: number;
+ /** 0 when unknown. */
+ window_minutes: number;
+ resets_at?: string;
+ status: RuntimeRateLimitStatus;
+}
+
+export interface RuntimeRateLimits {
+ plan_type: string;
+ status: RuntimeRateLimitStatus;
+ windows: RuntimeRateLimitWindow[];
+ credits?: { has_credits: boolean; unlimited: boolean; balance: string };
+ observed_at: string;
+}
+
+export interface RuntimeRateLimitsResponse {
+ rate_limits: RuntimeRateLimits | null;
+}
+
// One (agent, provider, model) row of the "Cost by agent" tab on the runtime
// detail page. provider + model stay on the wire because cost is computed
// client-side from a per-model pricing table (provider disambiguates bare
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index ab198a820f..6908946270 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -85,6 +85,11 @@ export type {
SetAgentSkillsRequest,
RuntimeUsage,
RuntimeHourlyActivity,
+ RuntimeRateLimitWindowKind,
+ RuntimeRateLimitStatus,
+ RuntimeRateLimitWindow,
+ RuntimeRateLimits,
+ RuntimeRateLimitsResponse,
RuntimeUsageByAgent,
RuntimeUsageByHour,
DashboardUsageDaily,
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 332ef4c8e7..3cdf14ae60 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -388,7 +388,8 @@
"pending_health_warning": "Waiting for daemon sync",
"pending_health_error": "Registration error",
"pending_health_disabled": "Disabled",
- "pending_cli_unknown": "waiting"
+ "pending_cli_unknown": "waiting",
+ "col_rate_limits": "Limits"
},
"profiles": {
"cta": "Add runtime",
@@ -694,5 +695,38 @@
"run_there": "Run on that machine",
"connected": "{{name}} connected to Multica"
}
+ },
+ "rate_limits": {
+ "title": "Limits",
+ "caption": "Reported by the CLI while tasks run",
+ "updated": "Updated {{ago}}",
+ "empty_title": "No limit data yet",
+ "empty_hint": "Recorded the next time this runtime runs a task. API-key accounts have no plan limits.",
+ "window_session": "Session",
+ "window_session_hours": "{{hours}}-hour session",
+ "window_weekly": "Weekly",
+ "window_weekly_opus": "Weekly · Opus",
+ "window_weekly_sonnet": "Weekly · Sonnet",
+ "window_generic": "Other limit",
+ "short_session": "Session",
+ "short_weekly": "Week",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "Other",
+ "used": "{{pct}}% used",
+ "limited": "Limit reached",
+ "resets_in": "Resets in {{duration}}",
+ "resets_at": "Resets {{time}}",
+ "reset_since": "Reset since last report",
+ "verdict_ahead": "{{pct}}% ahead of pace · runs out in about {{duration}}",
+ "verdict_on_pace": "On pace to last until reset",
+ "verdict_limited": "Resumes after the reset",
+ "credits": "Credits",
+ "credits_balance": "{{balance}} left",
+ "credits_unlimited": "Unlimited",
+ "credits_none": "None",
+ "duration_minutes": "{{minutes}}m",
+ "duration_hours": "{{hours}}h {{minutes}}m",
+ "duration_days": "{{days}}d {{hours}}h"
}
}
diff --git a/packages/views/locales/es/runtimes.json b/packages/views/locales/es/runtimes.json
index 753adf3378..dacf57083d 100644
--- a/packages/views/locales/es/runtimes.json
+++ b/packages/views/locales/es/runtimes.json
@@ -388,7 +388,8 @@
"pending_health_warning": "Esperando la sincronización del daemon",
"pending_health_error": "Error de registro",
"pending_health_disabled": "Desactivado",
- "pending_cli_unknown": "esperando"
+ "pending_cli_unknown": "esperando",
+ "col_rate_limits": "Límites"
},
"profiles": {
"cta": "Añadir runtime",
@@ -694,5 +695,38 @@
"run_there": "Ejecutar en esa máquina",
"connected": "{{name}} conectado a Multica"
}
+ },
+ "rate_limits": {
+ "title": "Límites",
+ "caption": "Los informa la CLI mientras se ejecutan tareas",
+ "updated": "Actualizado {{ago}}",
+ "empty_title": "Aún no hay datos de límites",
+ "empty_hint": "Se registran la próxima vez que este runtime ejecute una tarea. Las cuentas con clave de API no tienen límites de plan.",
+ "window_session": "Sesión",
+ "window_session_hours": "Sesión de {{hours}} h",
+ "window_weekly": "Semanal",
+ "window_weekly_opus": "Semanal · Opus",
+ "window_weekly_sonnet": "Semanal · Sonnet",
+ "window_generic": "Otro límite",
+ "short_session": "Sesión",
+ "short_weekly": "Semana",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "Otro",
+ "used": "{{pct}} % usado",
+ "limited": "Límite alcanzado",
+ "resets_in": "Se restablece en {{duration}}",
+ "resets_at": "Se restablece {{time}}",
+ "reset_since": "Restablecido desde el último informe",
+ "verdict_ahead": "{{pct}} % por delante del ritmo · se agota en unos {{duration}}",
+ "verdict_on_pace": "Al ritmo actual dura hasta el restablecimiento",
+ "verdict_limited": "Se reanuda tras el restablecimiento",
+ "credits": "Créditos",
+ "credits_balance": "Quedan {{balance}}",
+ "credits_unlimited": "Ilimitados",
+ "credits_none": "Ninguno",
+ "duration_minutes": "{{minutes}} min",
+ "duration_hours": "{{hours}} h {{minutes}} min",
+ "duration_days": "{{days}} d {{hours}} h"
}
}
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index 4576be8647..ae4c75e114 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -388,7 +388,8 @@
"pending_health_warning": "En attente de synchronisation du daemon",
"pending_health_error": "Erreur d'enregistrement",
"pending_health_disabled": "Désactivé",
- "pending_cli_unknown": "en attente"
+ "pending_cli_unknown": "en attente",
+ "col_rate_limits": "Limites"
},
"profiles": {
"cta": "Ajouter un runtime",
@@ -694,5 +695,38 @@
"run_there": "À lancer sur cette machine",
"connected": "{{name}} connecté à Multica"
}
+ },
+ "rate_limits": {
+ "title": "Limites",
+ "caption": "Signalées par la CLI pendant l'exécution des tâches",
+ "updated": "Mis à jour {{ago}}",
+ "empty_title": "Aucune donnée de limite pour l'instant",
+ "empty_hint": "Enregistrées la prochaine fois que ce runtime exécute une tâche. Les comptes à clé API n'ont pas de limites de forfait.",
+ "window_session": "Session",
+ "window_session_hours": "Session de {{hours}} h",
+ "window_weekly": "Hebdomadaire",
+ "window_weekly_opus": "Hebdomadaire · Opus",
+ "window_weekly_sonnet": "Hebdomadaire · Sonnet",
+ "window_generic": "Autre limite",
+ "short_session": "Session",
+ "short_weekly": "Semaine",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "Autre",
+ "used": "{{pct}} % utilisé",
+ "limited": "Limite atteinte",
+ "resets_in": "Réinitialisation dans {{duration}}",
+ "resets_at": "Réinitialisation {{time}}",
+ "reset_since": "Réinitialisée depuis le dernier relevé",
+ "verdict_ahead": "{{pct}} % d'avance sur le rythme · épuisée dans environ {{duration}}",
+ "verdict_on_pace": "Au rythme actuel, tient jusqu'à la réinitialisation",
+ "verdict_limited": "Reprend après la réinitialisation",
+ "credits": "Crédits",
+ "credits_balance": "Reste {{balance}}",
+ "credits_unlimited": "Illimités",
+ "credits_none": "Aucun",
+ "duration_minutes": "{{minutes}} min",
+ "duration_hours": "{{hours}} h {{minutes}} min",
+ "duration_days": "{{days}} j {{hours}} h"
}
}
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index f17b9572a8..00e482bbc4 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -376,7 +376,8 @@
"pending_health_warning": "Daemon 同期待ち",
"pending_health_error": "登録エラー",
"pending_health_disabled": "無効",
- "pending_cli_unknown": "待機中"
+ "pending_cli_unknown": "待機中",
+ "col_rate_limits": "上限"
},
"profiles": {
"cta": "ランタイムを追加",
@@ -674,5 +675,38 @@
"run_there": "そのマシンで実行",
"connected": "{{name}} が Multica に接続されました"
}
+ },
+ "rate_limits": {
+ "title": "利用上限",
+ "caption": "タスク実行中に CLI が報告",
+ "updated": "{{ago}}に更新",
+ "empty_title": "まだ上限のデータがありません",
+ "empty_hint": "このランタイムが次にタスクを実行したときに記録されます。API キーのアカウントにはプランの上限がありません。",
+ "window_session": "セッション",
+ "window_session_hours": "{{hours}} 時間セッション",
+ "window_weekly": "週間",
+ "window_weekly_opus": "週間 · Opus",
+ "window_weekly_sonnet": "週間 · Sonnet",
+ "window_generic": "その他の上限",
+ "short_session": "セッション",
+ "short_weekly": "週間",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "その他",
+ "used": "{{pct}}% 使用",
+ "limited": "上限に到達",
+ "resets_in": "{{duration}}後にリセット",
+ "resets_at": "{{time}} にリセット",
+ "reset_since": "前回の報告後にリセット済み",
+ "verdict_ahead": "ペースより {{pct}}% 速い · 約 {{duration}}で上限",
+ "verdict_on_pace": "このペースならリセットまで持ちます",
+ "verdict_limited": "リセット後に再開",
+ "credits": "クレジット",
+ "credits_balance": "残り {{balance}}",
+ "credits_unlimited": "無制限",
+ "credits_none": "なし",
+ "duration_minutes": "{{minutes}} 分",
+ "duration_hours": "{{hours}} 時間 {{minutes}} 分",
+ "duration_days": "{{days}} 日 {{hours}} 時間"
}
}
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index ac515d44fd..e193632c83 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -376,7 +376,8 @@
"pending_health_warning": "Daemon 동기화 대기 중",
"pending_health_error": "등록 오류",
"pending_health_disabled": "비활성화됨",
- "pending_cli_unknown": "대기 중"
+ "pending_cli_unknown": "대기 중",
+ "col_rate_limits": "한도"
},
"profiles": {
"cta": "런타임 추가",
@@ -674,5 +675,38 @@
"run_there": "해당 머신에서 실행",
"connected": "{{name}}이(가) Multica에 연결됨"
}
+ },
+ "rate_limits": {
+ "title": "한도",
+ "caption": "작업 실행 중 CLI가 보고",
+ "updated": "{{ago}} 업데이트",
+ "empty_title": "아직 한도 데이터가 없습니다",
+ "empty_hint": "이 런타임이 다음에 작업을 실행할 때 기록됩니다. API 키 계정에는 요금제 한도가 없습니다.",
+ "window_session": "세션",
+ "window_session_hours": "{{hours}}시간 세션",
+ "window_weekly": "주간",
+ "window_weekly_opus": "주간 · Opus",
+ "window_weekly_sonnet": "주간 · Sonnet",
+ "window_generic": "기타 한도",
+ "short_session": "세션",
+ "short_weekly": "주간",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "기타",
+ "used": "{{pct}}% 사용",
+ "limited": "한도 도달",
+ "resets_in": "{{duration}} 후 초기화",
+ "resets_at": "{{time}} 초기화",
+ "reset_since": "마지막 보고 이후 초기화됨",
+ "verdict_ahead": "예상보다 {{pct}}% 빠름 · 약 {{duration}} 후 소진",
+ "verdict_on_pace": "현재 속도면 초기화까지 충분합니다",
+ "verdict_limited": "초기화 후 재개",
+ "credits": "크레딧",
+ "credits_balance": "잔액 {{balance}}",
+ "credits_unlimited": "무제한",
+ "credits_none": "없음",
+ "duration_minutes": "{{minutes}}분",
+ "duration_hours": "{{hours}}시간 {{minutes}}분",
+ "duration_days": "{{days}}일 {{hours}}시간"
}
}
diff --git a/packages/views/locales/ru/runtimes.json b/packages/views/locales/ru/runtimes.json
index 3448c34ae7..cd46ccf3b7 100644
--- a/packages/views/locales/ru/runtimes.json
+++ b/packages/views/locales/ru/runtimes.json
@@ -408,7 +408,8 @@
"pending_health_warning": "Ожидание синхронизации с демоном",
"pending_health_error": "Ошибка регистрации",
"pending_health_disabled": "Отключена",
- "pending_cli_unknown": "ожидание"
+ "pending_cli_unknown": "ожидание",
+ "col_rate_limits": "Лимиты"
},
"profiles": {
"cta": "Добавить среду выполнения",
@@ -734,5 +735,38 @@
}
},
"title": "Предоставьте агентам компьютер для работы"
+ },
+ "rate_limits": {
+ "title": "Лимиты",
+ "caption": "Сообщает CLI во время выполнения задач",
+ "updated": "Обновлено {{ago}}",
+ "empty_title": "Данных о лимитах пока нет",
+ "empty_hint": "Появятся, когда эта среда выполнения в следующий раз выполнит задачу. У аккаунтов с API-ключом нет лимитов тарифа.",
+ "window_session": "Сессия",
+ "window_session_hours": "Сессия {{hours}} ч",
+ "window_weekly": "Неделя",
+ "window_weekly_opus": "Неделя · Opus",
+ "window_weekly_sonnet": "Неделя · Sonnet",
+ "window_generic": "Другой лимит",
+ "short_session": "Сессия",
+ "short_weekly": "Неделя",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "Другое",
+ "used": "Использовано {{pct}}%",
+ "limited": "Лимит исчерпан",
+ "resets_in": "Сброс через {{duration}}",
+ "resets_at": "Сброс {{time}}",
+ "reset_since": "Сброшен после последнего отчёта",
+ "verdict_ahead": "Опережение темпа на {{pct}}% · закончится примерно через {{duration}}",
+ "verdict_on_pace": "При текущем темпе хватит до сброса",
+ "verdict_limited": "Возобновится после сброса",
+ "credits": "Кредиты",
+ "credits_balance": "Осталось {{balance}}",
+ "credits_unlimited": "Без ограничений",
+ "credits_none": "Нет",
+ "duration_minutes": "{{minutes}} мин",
+ "duration_hours": "{{hours}} ч {{minutes}} мин",
+ "duration_days": "{{days}} д {{hours}} ч"
}
}
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 439e717b80..04ea6ed5e7 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -376,7 +376,8 @@
"pending_health_warning": "等待守护进程同步",
"pending_health_error": "注册错误",
"pending_health_disabled": "已禁用",
- "pending_cli_unknown": "等待中"
+ "pending_cli_unknown": "等待中",
+ "col_rate_limits": "额度"
},
"profiles": {
"cta": "添加运行时",
@@ -674,5 +675,38 @@
"run_there": "在那台机器上运行",
"connected": "{{name}} 已连接到 Multica"
}
+ },
+ "rate_limits": {
+ "title": "额度",
+ "caption": "运行任务时由 CLI 上报",
+ "updated": "{{ago}}更新",
+ "empty_title": "还没有额度数据",
+ "empty_hint": "这个运行时下次执行任务时会自动记录。API Key 账号没有套餐额度。",
+ "window_session": "会话",
+ "window_session_hours": "会话 · {{hours}} 小时",
+ "window_weekly": "本周",
+ "window_weekly_opus": "本周 · Opus",
+ "window_weekly_sonnet": "本周 · Sonnet",
+ "window_generic": "其他额度",
+ "short_session": "会话",
+ "short_weekly": "本周",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "其他",
+ "used": "已用 {{pct}}%",
+ "limited": "已触顶",
+ "resets_in": "{{duration}}后重置",
+ "resets_at": "{{time}} 重置",
+ "reset_since": "上次记录后已重置",
+ "verdict_ahead": "超出节奏 {{pct}}% · 约 {{duration}}后用完",
+ "verdict_on_pace": "按当前节奏可撑到重置",
+ "verdict_limited": "重置后恢复",
+ "credits": "Credits",
+ "credits_balance": "余额 {{balance}}",
+ "credits_unlimited": "不限",
+ "credits_none": "无",
+ "duration_minutes": "{{minutes}} 分钟",
+ "duration_hours": "{{hours}} 小时 {{minutes}} 分",
+ "duration_days": "{{days}} 天 {{hours}} 小时"
}
}
diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.json
index a07dfb4914..d22e73b3a5 100644
--- a/packages/views/locales/zh-Hant/runtimes.json
+++ b/packages/views/locales/zh-Hant/runtimes.json
@@ -376,7 +376,8 @@
"pending_health_warning": "等待守護程序同步",
"pending_health_error": "註冊錯誤",
"pending_health_disabled": "已禁用",
- "pending_cli_unknown": "等待中"
+ "pending_cli_unknown": "等待中",
+ "col_rate_limits": "額度"
},
"profiles": {
"cta": "新增執行時",
@@ -674,5 +675,38 @@
"run_there": "在那臺機器上執行",
"connected": "{{name}} 已連接到 Multica"
}
+ },
+ "rate_limits": {
+ "title": "額度",
+ "caption": "執行任務時由 CLI 回報",
+ "updated": "{{ago}}更新",
+ "empty_title": "還沒有額度資料",
+ "empty_hint": "這個執行時下次執行任務時會自動記錄。API Key 帳號沒有方案額度。",
+ "window_session": "工作階段",
+ "window_session_hours": "工作階段 · {{hours}} 小時",
+ "window_weekly": "本週",
+ "window_weekly_opus": "本週 · Opus",
+ "window_weekly_sonnet": "本週 · Sonnet",
+ "window_generic": "其他額度",
+ "short_session": "工作階段",
+ "short_weekly": "本週",
+ "short_weekly_opus": "Opus",
+ "short_weekly_sonnet": "Sonnet",
+ "short_generic": "其他",
+ "used": "已用 {{pct}}%",
+ "limited": "已達上限",
+ "resets_in": "{{duration}}後重置",
+ "resets_at": "{{time}} 重置",
+ "reset_since": "上次記錄後已重置",
+ "verdict_ahead": "超出節奏 {{pct}}% · 約 {{duration}}後用完",
+ "verdict_on_pace": "依目前節奏可撐到重置",
+ "verdict_limited": "重置後恢復",
+ "credits": "Credits",
+ "credits_balance": "餘額 {{balance}}",
+ "credits_unlimited": "不限",
+ "credits_none": "無",
+ "duration_minutes": "{{minutes}} 分鐘",
+ "duration_hours": "{{hours}} 小時 {{minutes}} 分",
+ "duration_days": "{{days}} 天 {{hours}} 小時"
}
}
diff --git a/packages/views/runtimes/components/rate-limit-section.test.tsx b/packages/views/runtimes/components/rate-limit-section.test.tsx
new file mode 100644
index 0000000000..ad286bfdfe
--- /dev/null
+++ b/packages/views/runtimes/components/rate-limit-section.test.tsx
@@ -0,0 +1,178 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { AgentRuntime, RuntimeRateLimitsResponse } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+
+const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
+
+const getRuntimeRateLimits = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/api", () => ({
+ api: { getRuntimeRateLimits },
+}));
+
+vi.mock("../../common/use-viewing-timezone", () => ({
+ useViewingTimezone: () => "UTC",
+}));
+
+import { RateLimitCell, RateLimitSection } from "./rate-limit-section";
+
+// Mon 2026-11-16 11:46 UTC: 2h46m into the 09:00-14:00 session window.
+const NOW = Date.parse("2026-11-16T11:46:00Z");
+
+const RUNTIME: AgentRuntime = {
+ id: "r-1",
+ workspace_id: "ws-1",
+ daemon_id: null,
+ name: "Claude Code",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: null,
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-05-01T00:00:00Z",
+ updated_at: "2026-05-01T00:00:00Z",
+};
+
+const SNAPSHOT: RuntimeRateLimitsResponse = {
+ rate_limits: {
+ plan_type: "pro",
+ status: "warning",
+ windows: [
+ { kind: "session", used_percent: 72, window_minutes: 300, resets_at: "2026-11-16T14:00:00Z", status: "warning" },
+ { kind: "weekly", used_percent: 41, window_minutes: 10080, resets_at: "2026-11-19T09:00:00Z", status: "allowed" },
+ ],
+ credits: { has_credits: true, unlimited: false, balance: "240" },
+ observed_at: "2026-11-16T11:44:00Z",
+ },
+};
+
+function Wrapper({ children }: { children: ReactNode }) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return (
+ <QueryClientProvider client={client}>
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>
+ </QueryClientProvider>
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(NOW);
+ getRuntimeRateLimits.mockReset();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("RateLimitSection", () => {
+ it("shows each window's usage, pace and reset", async () => {
+ getRuntimeRateLimits.mockResolvedValue(SNAPSHOT);
+ render(<RateLimitSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ expect(await screen.findByText("5-hour session")).toBeInTheDocument();
+ expect(getRuntimeRateLimits).toHaveBeenCalledWith("r-1");
+ expect(screen.getByText("Pro")).toBeInTheDocument();
+ expect(screen.getByText("Updated 2m ago")).toBeInTheDocument();
+
+ // 72% at 54.7% elapsed (reported 11:44): ahead of pace, out ~12:48.
+ expect(screen.getByText("72% used")).toBeInTheDocument();
+ expect(screen.getByText("17% ahead of pace · runs out in about 1h 2m")).toBeInTheDocument();
+ expect(screen.getByText("Resets in 2h 14m")).toBeInTheDocument();
+
+ // The weekly window is behind pace and resets more than a day out.
+ expect(screen.getByText("Weekly")).toBeInTheDocument();
+ expect(screen.getByText("41% used")).toBeInTheDocument();
+ expect(screen.getByText("On pace to last until reset")).toBeInTheDocument();
+ expect(screen.getByText("Resets Thu 09:00")).toBeInTheDocument();
+
+ expect(screen.getByText("240 left")).toBeInTheDocument();
+ const meters = screen.getAllByRole("meter");
+ expect(meters.map((m) => m.getAttribute("aria-valuenow"))).toEqual(["72", "41"]);
+ });
+
+ it("explains an empty runtime instead of showing zeros", async () => {
+ getRuntimeRateLimits.mockResolvedValue({ rate_limits: null });
+ render(<RateLimitSection runtime={RUNTIME} />, { wrapper: Wrapper });
+ expect(await screen.findByText("No limit data yet")).toBeInTheDocument();
+ expect(screen.queryByRole("meter")).not.toBeInTheDocument();
+ });
+
+ it("marks a reached limit and does not project a pace", async () => {
+ getRuntimeRateLimits.mockResolvedValue({
+ rate_limits: {
+ ...SNAPSHOT.rate_limits!,
+ credits: undefined,
+ windows: [{ kind: "session", used_percent: 100, window_minutes: 300, resets_at: "2026-11-16T14:20:00Z", status: "rejected" }],
+ },
+ });
+ render(<RateLimitSection runtime={RUNTIME} />, { wrapper: Wrapper });
+ expect(await screen.findByText("Limit reached")).toBeInTheDocument();
+ expect(screen.getByText("Resumes after the reset")).toBeInTheDocument();
+ expect(screen.queryByText(/ahead of pace/)).not.toBeInTheDocument();
+ });
+
+ it("drops the usage of a window that has reset since the report", async () => {
+ getRuntimeRateLimits.mockResolvedValue({
+ rate_limits: {
+ ...SNAPSHOT.rate_limits!,
+ credits: undefined,
+ windows: [{ kind: "session", used_percent: 95, window_minutes: 300, resets_at: "2026-11-16T09:00:00Z", status: "warning" }],
+ observed_at: "2026-11-16T08:30:00Z",
+ },
+ });
+ render(<RateLimitSection runtime={RUNTIME} />, { wrapper: Wrapper });
+ expect(await screen.findByText("Reset since last report")).toBeInTheDocument();
+ expect(screen.queryByText("95% used")).not.toBeInTheDocument();
+ });
+});
+
+describe("RateLimitCell", () => {
+ it("summarizes the window closest to its limit", async () => {
+ getRuntimeRateLimits.mockResolvedValue({
+ rate_limits: {
+ ...SNAPSHOT.rate_limits!,
+ windows: [
+ { kind: "session", used_percent: 18, window_minutes: 300, resets_at: "2026-11-16T15:32:00Z", status: "" },
+ { kind: "weekly", used_percent: 93, window_minutes: 10080, resets_at: "2026-11-18T08:00:00Z", status: "" },
+ ],
+ },
+ });
+ render(<RateLimitCell runtime={RUNTIME} enabled />, { wrapper: Wrapper });
+ expect(await screen.findByText("93%")).toBeInTheDocument();
+ });
+
+ it("shows a rejected window as full even without a reported share", async () => {
+ getRuntimeRateLimits.mockResolvedValue({
+ rate_limits: {
+ ...SNAPSHOT.rate_limits!,
+ windows: [{ kind: "session", window_minutes: 300, resets_at: "2026-11-16T14:20:00Z", status: "rejected" }],
+ },
+ });
+ render(<RateLimitCell runtime={RUNTIME} enabled />, { wrapper: Wrapper });
+ expect(await screen.findByText("100%")).toHaveClass("text-destructive");
+ });
+
+ it("does not fetch for a runtime whose CLI reports no limits", () => {
+ render(<RateLimitCell runtime={{ ...RUNTIME, provider: "cursor" }} enabled />, { wrapper: Wrapper });
+ expect(getRuntimeRateLimits).not.toHaveBeenCalled();
+ });
+
+ it("does not fetch for a viewer who cannot read the runtime", () => {
+ render(<RateLimitCell runtime={RUNTIME} enabled={false} />, { wrapper: Wrapper });
+ expect(getRuntimeRateLimits).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/runtimes/components/rate-limit-section.tsx b/packages/views/runtimes/components/rate-limit-section.tsx
new file mode 100644
index 0000000000..7e7987ace4
--- /dev/null
+++ b/packages/views/runtimes/components/rate-limit-section.tsx
@@ -0,0 +1,368 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Gauge } from "@multica/ui/icons";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import type {
+ AgentRuntime,
+ RuntimeRateLimits,
+ RuntimeRateLimitWindow,
+} from "@multica/core/types";
+import { runtimeRateLimitsOptions } from "@multica/core/runtimes/queries";
+import {
+ describeRateLimitWindow,
+ runtimeReportsRateLimits,
+ tightestRateLimitWindow,
+ type RateLimitTone,
+ type RateLimitWindowView,
+} from "@multica/core/runtimes/rate-limits";
+import { useT, useTimeAgo } from "../../i18n";
+import { useViewingTimezone } from "../../common/use-viewing-timezone";
+import { ObjectSectionCard, ObjectSectionEmpty } from "../../layout/object-page";
+import { CollectionEmptyValue } from "../../layout/collection-list";
+
+// Runtime rate limits (MUL-9427): the plan windows of the account the
+// runtime's agent CLI runs under, as the CLI last reported them while a task
+// ran. The detail page shows every window; the runtime list shows the window
+// closest to its limit.
+
+const FILL_TONE: Record<RateLimitTone, string> = {
+ normal: "bg-brand",
+ warning: "bg-warning",
+ critical: "bg-destructive",
+};
+
+const TEXT_TONE: Record<RateLimitTone, string> = {
+ normal: "",
+ warning: "text-warning",
+ critical: "text-destructive",
+};
+
+// Re-evaluates countdowns and pace between refetches.
+function useMinuteTick(): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), 60_000);
+ return () => clearInterval(id);
+ }, []);
+ return now;
+}
+
+function useRateLimitText() {
+ const { t, i18n } = useT("runtimes");
+ const tz = useViewingTimezone();
+ const locale = i18n.resolvedLanguage ?? i18n.language;
+ // Weekday and time are formatted apart: a combined zh format renders
+ // "周四14:54" with no separator.
+ const resetFormat = useMemo(() => {
+ const weekday = new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: tz });
+ const time = new Intl.DateTimeFormat(locale, {
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23",
+ timeZone: tz,
+ });
+ return (date: Date) => `${weekday.format(date)} ${time.format(date)}`;
+ }, [locale, tz]);
+
+ const duration = (minutes: number) => {
+ if (minutes < 60) {
+ return t(($) => $.rate_limits.duration_minutes, { minutes: Math.max(1, minutes) });
+ }
+ if (minutes < 24 * 60) {
+ return t(($) => $.rate_limits.duration_hours, {
+ hours: Math.floor(minutes / 60),
+ minutes: minutes % 60,
+ });
+ }
+ return t(($) => $.rate_limits.duration_days, {
+ days: Math.floor(minutes / (24 * 60)),
+ hours: Math.floor((minutes % (24 * 60)) / 60),
+ });
+ };
+
+ const windowLabel = (window: RuntimeRateLimitWindow) => {
+ switch (window.kind) {
+ case "session":
+ return window.window_minutes > 0 && window.window_minutes % 60 === 0
+ ? t(($) => $.rate_limits.window_session_hours, { hours: window.window_minutes / 60 })
+ : t(($) => $.rate_limits.window_session);
+ case "weekly":
+ return t(($) => $.rate_limits.window_weekly);
+ case "weekly_opus":
+ return t(($) => $.rate_limits.window_weekly_opus);
+ case "weekly_sonnet":
+ return t(($) => $.rate_limits.window_weekly_sonnet);
+ default:
+ return t(($) => $.rate_limits.window_generic);
+ }
+ };
+
+ const shortLabel = (window: RuntimeRateLimitWindow) => {
+ switch (window.kind) {
+ case "session":
+ return t(($) => $.rate_limits.short_session);
+ case "weekly":
+ return t(($) => $.rate_limits.short_weekly);
+ case "weekly_opus":
+ return t(($) => $.rate_limits.short_weekly_opus);
+ case "weekly_sonnet":
+ return t(($) => $.rate_limits.short_weekly_sonnet);
+ default:
+ return t(($) => $.rate_limits.short_generic);
+ }
+ };
+
+ const reset = (view: RateLimitWindowView) => {
+ if (view.hasReset) return t(($) => $.rate_limits.reset_since);
+ if (view.resetsInMinutes === undefined || !view.window.resets_at) return null;
+ if (view.resetsInMinutes < 24 * 60) {
+ return t(($) => $.rate_limits.resets_in, { duration: duration(view.resetsInMinutes) });
+ }
+ return t(($) => $.rate_limits.resets_at, {
+ time: resetFormat(new Date(view.window.resets_at)),
+ });
+ };
+
+ const usage = (view: RateLimitWindowView) => {
+ if (view.limited) return t(($) => $.rate_limits.limited);
+ if (view.used === undefined) return null;
+ return t(($) => $.rate_limits.used, { pct: Math.round(view.used) });
+ };
+
+ const verdict = (view: RateLimitWindowView): { text: string; tone: RateLimitTone } | null => {
+ if (view.hasReset) return null;
+ if (view.limited) return { text: t(($) => $.rate_limits.verdict_limited), tone: "critical" };
+ if (view.aheadOfPace !== undefined && view.runsOutInMinutes !== undefined) {
+ return {
+ text: t(($) => $.rate_limits.verdict_ahead, {
+ pct: view.aheadOfPace,
+ duration: duration(view.runsOutInMinutes),
+ }),
+ tone: view.tone === "critical" ? "critical" : "warning",
+ };
+ }
+ if (view.used !== undefined && view.elapsedPercent !== undefined) {
+ return { text: t(($) => $.rate_limits.verdict_on_pace), tone: "normal" };
+ }
+ return null;
+ };
+
+ return { t, windowLabel, shortLabel, reset, usage, verdict };
+}
+
+function useWindowViews(rateLimits: RuntimeRateLimits | null | undefined, now: number) {
+ return useMemo(
+ () =>
+ rateLimits
+ ? rateLimits.windows.map((w) => describeRateLimitWindow(w, rateLimits.observed_at, now))
+ : [],
+ [rateLimits, now],
+ );
+}
+
+function planLabel(plan: string): string {
+ const words = plan.replace(/[_-]+/g, " ").trim();
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : "";
+}
+
+function Meter({
+ view,
+ label,
+ className,
+}: {
+ view: RateLimitWindowView;
+ label: string;
+ className?: string;
+}) {
+ const used = view.limited ? 100 : (view.used ?? 0);
+ return (
+ <div
+ role="meter"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(Math.min(used, 100))}
+ className={cn("relative h-2 rounded-full bg-foreground/10", className)}
+ >
+ <div
+ className={cn("absolute inset-y-0 left-0 rounded-full", FILL_TONE[view.tone])}
+ style={{ width: `${Math.min(used, 100)}%` }}
+ />
+ {view.elapsedPercent !== undefined && !view.limited && (
+ // Pace marker: the share of the window that had elapsed when the
+ // usage was reported. Fill past it means usage runs ahead of time.
+ <div
+ aria-hidden="true"
+ data-slot="rate-limit-pace"
+ className="absolute -inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-foreground/50"
+ style={{ left: `${view.elapsedPercent}%` }}
+ />
+ )}
+ </div>
+ );
+}
+
+function WindowRow({ view }: { view: RateLimitWindowView }) {
+ const text = useRateLimitText();
+ const label = text.windowLabel(view.window);
+ const verdict = text.verdict(view);
+ const usage = text.usage(view);
+ const reset = text.reset(view);
+ return (
+ <div className="grid grid-cols-[minmax(0,8.5rem)_minmax(0,1fr)_minmax(0,8.5rem)] items-center gap-x-5 px-4 py-3">
+ <span className="truncate text-label font-medium">{label}</span>
+ <div className="min-w-0 space-y-1.5">
+ <Meter view={view} label={label} />
+ {verdict && (
+ <p className={cn("truncate text-caption text-muted-foreground", TEXT_TONE[verdict.tone])}>
+ {verdict.text}
+ </p>
+ )}
+ </div>
+ <div className="min-w-0 text-right">
+ <p className={cn("truncate text-body font-medium tabular-nums", TEXT_TONE[view.tone])}>
+ {usage ?? "—"}
+ </p>
+ {reset && (
+ <p className="truncate text-caption text-muted-foreground tabular-nums">{reset}</p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function RateLimitSection({ runtime }: { runtime: AgentRuntime }) {
+ const text = useRateLimitText();
+ const timeAgo = useTimeAgo();
+ const now = useMinuteTick();
+ const { data, isLoading } = useQuery(runtimeRateLimitsOptions(runtime.id));
+ const rateLimits = data?.rate_limits ?? null;
+ const views = useWindowViews(rateLimits, now);
+
+ if (isLoading) return <Skeleton className="h-32 w-full rounded-lg" />;
+ if (!rateLimits || (views.length === 0 && !rateLimits.credits)) {
+ return (
+ <ObjectSectionEmpty
+ icon={Gauge}
+ title={text.t(($) => $.rate_limits.empty_title)}
+ description={text.t(($) => $.rate_limits.empty_hint)}
+ />
+ );
+ }
+
+ const plan = planLabel(rateLimits.plan_type);
+ const credits = rateLimits.credits;
+ return (
+ <ObjectSectionCard>
+ <div className="flex min-w-0 items-center gap-2 px-4 py-2.5 text-caption text-muted-foreground">
+ {plan && (
+ <span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 font-medium text-foreground">
+ {plan}
+ </span>
+ )}
+ <span className="min-w-0 truncate">{text.t(($) => $.rate_limits.caption)}</span>
+ <span className="ml-auto shrink-0 tabular-nums">
+ {text.t(($) => $.rate_limits.updated, { ago: timeAgo(rateLimits.observed_at) })}
+ </span>
+ </div>
+ {views.map((view, index) => (
+ <WindowRow key={`${view.window.kind}-${index}`} view={view} />
+ ))}
+ {credits && (
+ <div className="flex items-center justify-between gap-4 px-4 py-3">
+ <span className="text-label font-medium">{text.t(($) => $.rate_limits.credits)}</span>
+ <span className="text-body font-medium tabular-nums">
+ {credits.unlimited
+ ? text.t(($) => $.rate_limits.credits_unlimited)
+ : credits.has_credits && credits.balance
+ ? text.t(($) => $.rate_limits.credits_balance, { balance: credits.balance })
+ : text.t(($) => $.rate_limits.credits_none)}
+ </span>
+ </div>
+ )}
+ </ObjectSectionCard>
+ );
+}
+
+/**
+ * Runtime-list cell: two stacked bars (the first two windows, usually the
+ * session and the week) and the share of the window closest to its limit.
+ * The list is already wider than the page at its default width, so the cell
+ * stays compact and names the windows only in its tooltip.
+ */
+export function RateLimitCell({
+ runtime,
+ enabled,
+}: {
+ runtime: AgentRuntime;
+ enabled: boolean;
+}) {
+ const supported = runtimeReportsRateLimits(runtime.provider);
+ const text = useRateLimitText();
+ const now = useMinuteTick();
+ const { data } = useQuery({
+ ...runtimeRateLimitsOptions(runtime.id),
+ enabled: enabled && supported,
+ });
+ const rateLimits = data?.rate_limits ?? null;
+ const views = useWindowViews(rateLimits, now);
+ const tightest = tightestRateLimitWindow(views);
+ if (!tightest) return <CollectionEmptyValue />;
+
+ // A rejected window may not report a share; it is at its limit either way.
+ const share = tightest.limited ? Math.max(tightest.used ?? 100, 100) : tightest.used;
+ const summary = share !== undefined ? `${Math.round(share)}%` : text.shortLabel(tightest.window);
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="flex w-10 shrink-0 flex-col gap-0.5" aria-hidden="true">
+ {views.slice(0, 2).map((view, index) => (
+ <span
+ key={`${view.window.kind}-${index}`}
+ className={cn(
+ "relative overflow-hidden rounded-full bg-foreground/10",
+ index === 0 ? "h-1" : "h-0.5",
+ )}
+ >
+ <span
+ className={cn("absolute inset-y-0 left-0 rounded-full", FILL_TONE[view.tone])}
+ style={{ width: `${Math.min(view.limited ? 100 : (view.used ?? 0), 100)}%` }}
+ />
+ </span>
+ ))}
+ </span>
+ <span
+ className={cn(
+ "truncate text-caption tabular-nums",
+ TEXT_TONE[tightest.tone] || "text-muted-foreground",
+ )}
+ >
+ {summary}
+ </span>
+ </span>
+ }
+ />
+ <TooltipContent className="flex-col items-start gap-0.5">
+ {views.map((view, index) => {
+ const usage = text.usage(view);
+ const reset = text.reset(view);
+ return (
+ <p key={`${view.window.kind}-${index}`} className="tabular-nums">
+ {[text.windowLabel(view.window), usage, reset].filter(Boolean).join(" · ")}
+ </p>
+ );
+ })}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 34938a037a..e5007d096f 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -25,6 +25,7 @@ import {
runtimeDisplayName,
runtimeProfileListOptions,
} from "@multica/core/runtimes";
+import { runtimeReportsRateLimits } from "@multica/core/runtimes/rate-limits";
import {
type AgentPresenceDetail,
useWorkspacePresenceMap,
@@ -54,6 +55,7 @@ import { availabilityConfig, workloadConfig } from "../../agents/presence";
import { HealthBadge, HealthIcon, shortDaemonId, useHealthLabel } from "./shared";
import { ProviderLogo } from "./provider-logo";
import { UsageSection } from "./usage-section";
+import { RateLimitSection } from "./rate-limit-section";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
import { RuntimeAccessEditor, RuntimeAccessReadout } from "./runtime-access-editor";
import { RuntimeConcurrencyField } from "./runtime-concurrency-field";
@@ -232,6 +234,12 @@ export function RuntimeDetail({
/>
</ObjectSection>
+ {canReadRuntime && runtimeReportsRateLimits(runtime.provider) && (
+ <ObjectSection title={t(($) => $.rate_limits.title)}>
+ <RateLimitSection runtime={runtime} />
+ </ObjectSection>
+ )}
+
{canReadRuntime && (
<ObjectSection title={t(($) => $.detail.usage_title)}>
<UsageSection runtime={runtime} />
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index c6219a941b..754a1145ab 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -54,6 +54,7 @@ import {
import { ActorAvatar } from "../../common/actor-avatar";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { ProviderLogo } from "./provider-logo";
+import { RateLimitCell } from "./rate-limit-section";
import { HealthIcon, useHealthLabel } from "./shared";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";
@@ -663,6 +664,20 @@ export function RuntimeList({
width: 92,
cell: (row) => <AgentStack agentIds={row.workload.agentIds} />,
},
+ {
+ key: "rate_limits",
+ header: t(($) => $.list.col_rate_limits),
+ width: 88,
+ cell: (row) =>
+ isPendingCustomRuntime(row.runtime) ? (
+ <CollectionEmptyValue />
+ ) : (
+ <RateLimitCell
+ runtime={row.runtime}
+ enabled={canReadRuntimeUsage(row.runtime, user?.id ?? null)}
+ />
+ ),
+ },
{
key: "cost",
header: t(($) => $.list.col_cost),
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 09cc720a2c..c1032cfb9f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1719,6 +1719,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/tasks/{taskId}/environments", h.ReportTaskEnvironments)
r.Post("/tasks/{taskId}/environment-configs", h.ReportTaskEnvironmentConfigs)
r.Post("/tasks/{taskId}/context-receipt", h.ReportTaskContextReceipt)
+ r.Post("/tasks/{taskId}/rate-limits", h.ReportTaskRateLimits)
r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)
r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)
r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)
@@ -2549,6 +2550,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/usage", h.GetRuntimeUsage)
r.Get("/usage/by-agent", h.GetRuntimeUsageByAgent)
r.Get("/usage/by-hour", h.GetRuntimeUsageByHour)
+ r.Get("/rate-limits", h.GetRuntimeRateLimits)
r.Get("/activity", h.GetRuntimeTaskActivity)
r.Post("/update", h.InitiateUpdate)
r.Get("/update/{updateId}", h.GetUpdate)
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 8fc55152b4..9f5af9bbc7 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -760,6 +760,15 @@ func (c *Client) ReportTaskContextReceipt(ctx context.Context, taskID string, re
}, nil)
}
+// ReportTaskRateLimits posts the subscription rate-limit snapshot the agent
+// CLI reported while running the task; the server keeps the newest one as the
+// state of the task's runtime.
+func (c *Client) ReportTaskRateLimits(ctx context.Context, taskID string, snapshot agent.RateLimitSnapshot) error {
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/rate-limits", taskID), map[string]any{
+ "rate_limits": snapshot,
+ }, nil)
+}
+
// EnvironmentCommand is a stop, restart, start or log read a member asked
// for from the issue sidebar.
type EnvironmentCommand struct {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index fa176fae17..4c96f8562a 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9429,6 +9429,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
stopUsageFlush := d.startUsageFlush(ctx, task.ID, &liveUsage, taskLog)
defer stopUsageFlush()
+ // MUL-9427: forward the account's rate-limit state the CLI reports, so the
+ // runtime pages show how much of the plan's windows is left.
+ observeRateLimits, stopRateLimitFlush := d.startRateLimitFlush(ctx, task.ID, taskLog)
+ execOpts.OnRateLimits = observeRateLimits
+ defer stopRateLimitFlush()
result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
if err != nil {
return TaskResult{}, err
diff --git a/server/internal/daemon/rate_limits.go b/server/internal/daemon/rate_limits.go
new file mode 100644
index 0000000000..319b64d183
--- /dev/null
+++ b/server/internal/daemon/rate_limits.go
@@ -0,0 +1,115 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "reflect"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// Runtime rate limits (MUL-9427). The agent backend hands every rate-limit
+// change the CLI reports to ExecOptions.OnRateLimits; this reporter forwards
+// the newest snapshot to the server, which keeps it as the runtime's latest
+// state. Only the newest snapshot matters, so a lost post is simply replaced
+// by the next one.
+
+// rateLimitFlushEvery bounds how often a running task posts rate limits. The
+// CLI reports a change whenever a window's rounded percentage moves, which
+// can be every model call.
+const rateLimitFlushEvery = 30 * time.Second
+
+const rateLimitReportTimeout = 5 * time.Second
+
+type rateLimitReporter struct {
+ post func(context.Context, agent.RateLimitSnapshot) error
+ log *slog.Logger
+ latest atomic.Pointer[agent.RateLimitSnapshot]
+
+ mu sync.Mutex
+ reported *agent.RateLimitSnapshot
+ // disabled is set once the server answers that it has no rate-limit
+ // endpoint (an older self-hosted server), so the task stops trying.
+ disabled bool
+}
+
+// observe records a snapshot. It runs on the backend's protocol reader
+// goroutine, so it only stores.
+func (r *rateLimitReporter) observe(snapshot agent.RateLimitSnapshot) {
+ r.latest.Store(&snapshot)
+}
+
+// flush posts the newest snapshot if it differs from the last one posted.
+func (r *rateLimitReporter) flush(ctx context.Context) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.disabled {
+ return
+ }
+ latest := r.latest.Load()
+ if latest == nil || (r.reported != nil && rateLimitSnapshotsEqual(*latest, *r.reported)) {
+ return
+ }
+ postCtx, cancel := context.WithTimeout(ctx, rateLimitReportTimeout)
+ defer cancel()
+ err := r.post(postCtx, *latest)
+ if err == nil {
+ r.reported = latest
+ return
+ }
+ var reqErr *requestError
+ if errors.As(err, &reqErr) && (reqErr.StatusCode == http.StatusNotFound || reqErr.StatusCode == http.StatusMethodNotAllowed) {
+ r.disabled = true
+ r.log.Debug("server does not accept rate limits; skipping", "error", err)
+ return
+ }
+ // Not fatal: the next change, or the final flush, posts again.
+ r.log.Warn("report rate limits failed", "error", err)
+}
+
+// rateLimitSnapshotsEqual ignores ObservedAt, which moves on every event even
+// when nothing the reader shows has changed.
+func rateLimitSnapshotsEqual(a, b agent.RateLimitSnapshot) bool {
+ a.ObservedAt, b.ObservedAt = time.Time{}, time.Time{}
+ return reflect.DeepEqual(a, b)
+}
+
+// startRateLimitFlush wires a reporter into the task's exec options and
+// returns a stop func that posts whatever is still unposted. The stop func
+// must run before the task's terminal report so the snapshot from a run that
+// hit its limit is stored.
+func (d *Daemon) startRateLimitFlush(ctx context.Context, taskID string, taskLog *slog.Logger) (observe func(agent.RateLimitSnapshot), stop func()) {
+ reporter := &rateLimitReporter{
+ post: func(ctx context.Context, s agent.RateLimitSnapshot) error {
+ return d.client.ReportTaskRateLimits(ctx, taskID, s)
+ },
+ log: taskLog,
+ }
+ done := make(chan struct{})
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(rateLimitFlushEvery)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-done:
+ return
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ reporter.flush(context.WithoutCancel(ctx))
+ }
+ }
+ }()
+ return reporter.observe, sync.OnceFunc(func() {
+ close(done)
+ <-stopped
+ reporter.flush(context.WithoutCancel(ctx))
+ })
+}
diff --git a/server/internal/daemon/rate_limits_test.go b/server/internal/daemon/rate_limits_test.go
new file mode 100644
index 0000000000..5b3d0ec4f5
--- /dev/null
+++ b/server/internal/daemon/rate_limits_test.go
@@ -0,0 +1,80 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+func rateLimitSnap(used float64, at time.Time) agent.RateLimitSnapshot {
+ return agent.RateLimitSnapshot{
+ Status: agent.RateLimitStatusAllowed,
+ Windows: []agent.RateLimitWindow{{Kind: agent.RateLimitWindowSession, UsedPercent: &used, WindowMinutes: 300}},
+ ObservedAt: at,
+ }
+}
+
+func TestRateLimitReporterPostsOnlyChanges(t *testing.T) {
+ var posted []agent.RateLimitSnapshot
+ var failNext error
+ r := &rateLimitReporter{
+ log: slog.Default(),
+ post: func(_ context.Context, s agent.RateLimitSnapshot) error {
+ if failNext != nil {
+ err := failNext
+ failNext = nil
+ return err
+ }
+ posted = append(posted, s)
+ return nil
+ },
+ }
+ ctx := context.Background()
+ start := time.Now()
+
+ r.flush(ctx) // nothing observed yet
+ if len(posted) != 0 {
+ t.Fatalf("posted before any observation: %v", posted)
+ }
+
+ r.observe(rateLimitSnap(10, start))
+ r.flush(ctx)
+ // Only ObservedAt moved: nothing a reader sees changed.
+ r.observe(rateLimitSnap(10, start.Add(time.Minute)))
+ r.flush(ctx)
+ if len(posted) != 1 {
+ t.Fatalf("posts = %d, want 1", len(posted))
+ }
+
+ // A failed post is retried by the next flush.
+ r.observe(rateLimitSnap(20, start.Add(2*time.Minute)))
+ failNext = errors.New("network down")
+ r.flush(ctx)
+ r.flush(ctx)
+ if len(posted) != 2 || *posted[1].Windows[0].UsedPercent != 20 {
+ t.Fatalf("posted = %+v", posted)
+ }
+}
+
+func TestRateLimitReporterStopsOnOlderServer(t *testing.T) {
+ calls := 0
+ r := &rateLimitReporter{
+ log: slog.Default(),
+ post: func(context.Context, agent.RateLimitSnapshot) error {
+ calls++
+ return &requestError{Method: http.MethodPost, Path: "/rate-limits", StatusCode: http.StatusNotFound}
+ },
+ }
+ r.observe(rateLimitSnap(10, time.Now()))
+ r.flush(context.Background())
+ r.observe(rateLimitSnap(30, time.Now()))
+ r.flush(context.Background())
+ if calls != 1 {
+ t.Fatalf("calls = %d, want 1 (a 404 means the server has no endpoint)", calls)
+ }
+}
diff --git a/server/internal/handler/runtime_rate_limit.go b/server/internal/handler/runtime_rate_limit.go
new file mode 100644
index 0000000000..3976d2a683
--- /dev/null
+++ b/server/internal/handler/runtime_rate_limit.go
@@ -0,0 +1,180 @@
+package handler
+
+import (
+ "encoding/json"
+ "log/slog"
+ "math"
+ "net/http"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Runtime rate limits (MUL-9427). While a task runs, the daemon forwards the
+// subscription rate-limit state the agent CLI reports for its account (Claude
+// Code's 5-hour / weekly windows, Codex's primary / secondary windows) and the
+// server keeps the newest snapshot per runtime. Members who may read the
+// runtime see it on the runtime pages.
+
+const (
+ maxRateLimitBodyBytes = 32 << 10
+ maxRateLimitWindows = 16
+ maxRateLimitString = 64
+ maxRateLimitPercent = 1000
+ maxRateLimitWindowMins = 366 * 24 * 60
+ // rateLimitClockSkew bounds how far in the future a daemon's observation
+ // time may sit before it is pulled back to the server clock, so a fast
+ // daemon clock cannot pin a snapshot no later report can replace.
+ rateLimitClockSkew = 5 * time.Minute
+)
+
+var rateLimitWindowKinds = map[string]bool{
+ "session": true,
+ "weekly": true,
+ "weekly_opus": true,
+ "weekly_sonnet": true,
+ "other": true,
+}
+
+var rateLimitStatuses = map[string]bool{
+ "": true,
+ "allowed": true,
+ "warning": true,
+ "rejected": true,
+}
+
+// runtimeRateLimitSnapshot is the stored shape. Decoding into it drops any
+// field this server does not know, so the column only holds what readers
+// are built for.
+type runtimeRateLimitSnapshot struct {
+ PlanType string `json:"plan_type,omitempty"`
+ Status string `json:"status,omitempty"`
+ Windows []runtimeRateLimitWindow `json:"windows"`
+ Credits *runtimeRateLimitCredits `json:"credits,omitempty"`
+ ObservedAt time.Time `json:"observed_at"`
+}
+
+type runtimeRateLimitWindow struct {
+ Kind string `json:"kind"`
+ UsedPercent *float64 `json:"used_percent,omitempty"`
+ WindowMinutes int64 `json:"window_minutes,omitempty"`
+ ResetsAt *time.Time `json:"resets_at,omitempty"`
+ Status string `json:"status,omitempty"`
+}
+
+type runtimeRateLimitCredits struct {
+ HasCredits bool `json:"has_credits"`
+ Unlimited bool `json:"unlimited"`
+ Balance string `json:"balance,omitempty"`
+}
+
+// normalize validates a daemon report in place. Windows of a kind this server
+// cannot label are dropped rather than rejected, so a newer daemon that learns
+// a new window still reports the ones this server understands.
+func (s *runtimeRateLimitSnapshot) normalize(now time.Time) bool {
+ if s.ObservedAt.IsZero() || len(s.Windows) > maxRateLimitWindows {
+ return false
+ }
+ if len(s.PlanType) > maxRateLimitString || !rateLimitStatuses[s.Status] {
+ return false
+ }
+ if s.Credits != nil && len(s.Credits.Balance) > maxRateLimitString {
+ return false
+ }
+ if s.ObservedAt.After(now.Add(rateLimitClockSkew)) {
+ s.ObservedAt = now
+ }
+ s.ObservedAt = s.ObservedAt.UTC()
+ windows := make([]runtimeRateLimitWindow, 0, len(s.Windows))
+ for _, w := range s.Windows {
+ if !rateLimitWindowKinds[w.Kind] {
+ continue
+ }
+ if !rateLimitStatuses[w.Status] || w.WindowMinutes < 0 || w.WindowMinutes > maxRateLimitWindowMins {
+ return false
+ }
+ if w.UsedPercent != nil {
+ v := *w.UsedPercent
+ if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > maxRateLimitPercent {
+ return false
+ }
+ }
+ if w.ResetsAt != nil {
+ reset := w.ResetsAt.UTC()
+ w.ResetsAt = &reset
+ }
+ windows = append(windows, w)
+ }
+ s.Windows = windows
+ return true
+}
+
+// ReportTaskRateLimits stores the rate-limit snapshot the daemon observed
+// while running a task, as the latest state of that task's runtime.
+func (h *Handler) ReportTaskRateLimits(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, maxRateLimitBodyBytes)
+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "taskId"))
+ if !ok {
+ return
+ }
+ if !task.RuntimeID.Valid {
+ writeError(w, http.StatusConflict, "task has no runtime")
+ return
+ }
+
+ var req struct {
+ RateLimits *runtimeRateLimitSnapshot `json:"rate_limits"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.RateLimits == nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if !req.RateLimits.normalize(time.Now()) {
+ writeError(w, http.StatusBadRequest, "invalid rate limits")
+ return
+ }
+ stored, err := json.Marshal(req.RateLimits)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode rate limits")
+ return
+ }
+ if err := h.Queries.UpsertRuntimeRateLimit(r.Context(), db.UpsertRuntimeRateLimitParams{
+ RuntimeID: task.RuntimeID,
+ WorkspaceID: parseUUID(workspaceID),
+ Snapshot: stored,
+ ObservedAt: pgtype.Timestamptz{Time: req.RateLimits.ObservedAt, Valid: true},
+ }); err != nil {
+ slog.Warn("store runtime rate limits failed", "task_id", uuidToString(task.ID), "runtime_id", uuidToString(task.RuntimeID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to store rate limits")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// GetRuntimeRateLimits returns a runtime's latest rate-limit snapshot to a
+// member who may read the runtime. A runtime that has not reported one (no
+// task yet, an older daemon, an API-key account, or a CLI that reports no
+// limits) answers 200 with null so the page can say so without an error.
+func (h *Handler) GetRuntimeRateLimits(w http.ResponseWriter, r *http.Request) {
+ rt, _, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, chi.URLParam(r, "runtimeId"))
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetRuntimeRateLimit(r.Context(), rt.ID)
+ if err != nil {
+ if isNotFound(err) {
+ writeJSON(w, http.StatusOK, map[string]any{"rate_limits": nil})
+ return
+ }
+ if writeQueryCancellation(w, r, err) {
+ return
+ }
+ slog.Warn("load runtime rate limits failed", "runtime_id", uuidToString(rt.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load rate limits")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"rate_limits": json.RawMessage(row.Snapshot)})
+}
diff --git a/server/internal/handler/runtime_rate_limit_test.go b/server/internal/handler/runtime_rate_limit_test.go
new file mode 100644
index 0000000000..72052c41e2
--- /dev/null
+++ b/server/internal/handler/runtime_rate_limit_test.go
@@ -0,0 +1,158 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func rateLimitFixture(t *testing.T, label string) (runtimeID, taskID string) {
+ t.Helper()
+ name := "rate-limits " + label
+ runtimeID = dbfx.Runtime(t, name+" runtime")
+ agentID := dbfx.Agent(t, name+" agent", runtimeID)
+ issueID := dbfx.Issue(t, name+" issue")
+ taskID = dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": "running"})
+ dbfx.Cleanup(t, `DELETE FROM runtime_rate_limit WHERE runtime_id = $1`, runtimeID)
+ return runtimeID, taskID
+}
+
+func sampleRateLimits(observedAt time.Time, sessionUsed float64) map[string]any {
+ return map[string]any{
+ "plan_type": "pro",
+ "status": "warning",
+ "windows": []map[string]any{
+ {"kind": "session", "used_percent": sessionUsed, "window_minutes": 300, "resets_at": "2026-11-16T06:00:00Z", "status": "warning"},
+ {"kind": "weekly", "used_percent": 41, "window_minutes": 10080, "resets_at": "2026-11-19T01:00:00Z"},
+ // A window kind this server cannot label is dropped, not rejected.
+ {"kind": "monthly_future", "used_percent": 3},
+ },
+ "credits": map[string]any{"has_credits": true, "unlimited": false, "balance": "240"},
+ "observed_at": observedAt.UTC().Format(time.RFC3339Nano),
+ // A field this server does not know must not reach the column.
+ "account_email": "[email protected]",
+ }
+}
+
+func reportRateLimits(t *testing.T, taskID string, snapshot any) *testutil.Response {
+ t.Helper()
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/rate-limits",
+ map[string]any{"rate_limits": snapshot}), "taskId", taskID)
+ return testutil.Call(t, testHandler.ReportTaskRateLimits, req)
+}
+
+type rateLimitsResponse struct {
+ RateLimits *runtimeRateLimitSnapshot `json:"rate_limits"`
+}
+
+func getRateLimits(t *testing.T, runtimeID string) rateLimitsResponse {
+ t.Helper()
+ req := withURLParam(newRequest(http.MethodGet, "/api/runtimes/"+runtimeID+"/rate-limits", nil), "runtimeId", runtimeID)
+ var resp rateLimitsResponse
+ testutil.Call(t, testHandler.GetRuntimeRateLimits, req).Want(http.StatusOK).JSON(&resp)
+ return resp
+}
+
+func TestRuntimeRateLimits_ReportThenRead(t *testing.T) {
+ runtimeID, taskID := rateLimitFixture(t, "report")
+
+ // Before any report the reader gets an explicit null.
+ if got := getRateLimits(t, runtimeID); got.RateLimits != nil {
+ t.Fatalf("rate limits before report = %+v, want null", got.RateLimits)
+ }
+
+ observed := time.Now().Add(-time.Minute).Truncate(time.Second)
+ reportRateLimits(t, taskID, sampleRateLimits(observed, 72)).Want(http.StatusNoContent)
+
+ got := getRateLimits(t, runtimeID).RateLimits
+ if got == nil || got.PlanType != "pro" || got.Status != "warning" || len(got.Windows) != 2 {
+ t.Fatalf("rate limits = %+v", got)
+ }
+ if w := got.Windows[0]; w.Kind != "session" || w.UsedPercent == nil || *w.UsedPercent != 72 || w.WindowMinutes != 300 || w.ResetsAt == nil {
+ t.Fatalf("session window = %+v", w)
+ }
+ if got.Credits == nil || got.Credits.Balance != "240" || !got.ObservedAt.Equal(observed) {
+ t.Fatalf("credits=%+v observed_at=%v", got.Credits, got.ObservedAt)
+ }
+
+ var stored string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT snapshot::text FROM runtime_rate_limit WHERE runtime_id = $1 AND workspace_id = $2`, runtimeID, testWorkspaceID,
+ ).Scan(&stored); err != nil {
+ t.Fatalf("load stored snapshot: %v", err)
+ }
+ if strings.Contains(stored, "[email protected]") || strings.Contains(stored, "monthly_future") {
+ t.Fatalf("unknown data reached storage: %s", stored)
+ }
+
+ // A late report from an older run cannot roll the snapshot back.
+ reportRateLimits(t, taskID, sampleRateLimits(observed.Add(-time.Hour), 10)).Want(http.StatusNoContent)
+ if w := getRateLimits(t, runtimeID).RateLimits.Windows[0]; *w.UsedPercent != 72 {
+ t.Fatalf("older observation replaced the snapshot: %+v", w)
+ }
+
+ // A newer one replaces it in place.
+ reportRateLimits(t, taskID, sampleRateLimits(observed.Add(30*time.Second), 80)).Want(http.StatusNoContent)
+ if w := getRateLimits(t, runtimeID).RateLimits.Windows[0]; *w.UsedPercent != 80 {
+ t.Fatalf("newer observation did not replace the snapshot: %+v", w)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM runtime_rate_limit WHERE runtime_id = $1`, runtimeID); n != 1 {
+ t.Fatalf("rows = %d, want 1", n)
+ }
+}
+
+func TestRuntimeRateLimits_FutureObservationIsClamped(t *testing.T) {
+ runtimeID, taskID := rateLimitFixture(t, "clock skew")
+ reportRateLimits(t, taskID, sampleRateLimits(time.Now().Add(48*time.Hour), 50)).Want(http.StatusNoContent)
+ got := getRateLimits(t, runtimeID).RateLimits
+ if got == nil || got.ObservedAt.After(time.Now().Add(time.Minute)) {
+ t.Fatalf("observed_at not clamped: %+v", got)
+ }
+ // The clamp keeps the runtime updatable by the next honest report.
+ reportRateLimits(t, taskID, sampleRateLimits(time.Now().Add(time.Second), 60)).Want(http.StatusNoContent)
+ if w := getRateLimits(t, runtimeID).RateLimits.Windows[0]; *w.UsedPercent != 60 {
+ t.Fatalf("report after a skewed one was ignored: %+v", w)
+ }
+}
+
+func TestRuntimeRateLimits_RejectsMalformed(t *testing.T) {
+ _, taskID := rateLimitFixture(t, "malformed")
+ now := time.Now()
+
+ noTime := sampleRateLimits(now, 10)
+ delete(noTime, "observed_at")
+ reportRateLimits(t, taskID, noTime).Want(http.StatusBadRequest)
+
+ badStatus := sampleRateLimits(now, 10)
+ badStatus["status"] = "throttled"
+ reportRateLimits(t, taskID, badStatus).Want(http.StatusBadRequest)
+
+ reportRateLimits(t, taskID, sampleRateLimits(now, maxRateLimitPercent+1)).Want(http.StatusBadRequest)
+ reportRateLimits(t, taskID, sampleRateLimits(now, -1)).Want(http.StatusBadRequest)
+
+ longPlan := sampleRateLimits(now, 10)
+ longPlan["plan_type"] = strings.Repeat("p", maxRateLimitString+1)
+ reportRateLimits(t, taskID, longPlan).Want(http.StatusBadRequest)
+
+ reportRateLimits(t, taskID, nil).Want(http.StatusBadRequest)
+}
+
+func TestRuntimeRateLimits_DeletedWithRuntime(t *testing.T) {
+ runtimeID, taskID := rateLimitFixture(t, "delete")
+ reportRateLimits(t, taskID, sampleRateLimits(time.Now(), 10)).Want(http.StatusNoContent)
+
+ // The runtime-delete handlers unbind agents first; do the same here.
+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET runtime_id = NULL WHERE runtime_id = $1`, runtimeID); err != nil {
+ t.Fatalf("unbind agent: %v", err)
+ }
+ if err := testHandler.Queries.DeleteAgentRuntime(context.Background(), parseUUID(runtimeID)); err != nil {
+ t.Fatalf("delete runtime: %v", err)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM runtime_rate_limit WHERE runtime_id = $1`, runtimeID); n != 0 {
+ t.Fatalf("rate-limit rows after runtime delete = %d, want 0", n)
+ }
+}
diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.go
index 70d402460e..11d0ba06a7 100644
--- a/server/internal/handler/runtime_test.go
+++ b/server/internal/handler/runtime_test.go
@@ -25,6 +25,12 @@ func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {
path: "/api/runtimes/not-a-uuid/usage",
handle: testHandler.GetRuntimeUsage,
},
+ {
+ name: "rate limits",
+ method: "GET",
+ path: "/api/runtimes/not-a-uuid/rate-limits",
+ handle: testHandler.GetRuntimeRateLimits,
+ },
{
name: "task activity",
method: "GET",
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 1d3cc5a0bc..5934977cc6 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -137,6 +137,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"sys_cron_executions": workspaceDeleteKeep,
"theme_store_download": workspaceDeleteKeep, // per registry theme, not workspace-owned
"task_context_receipt": workspaceDelete,
+ "runtime_rate_limit": workspaceDelete,
"task_message": workspaceDelete,
"chat_task_supplement": workspaceDelete,
"task_supplement": workspaceDelete,
diff --git a/server/migrations/665_runtime_rate_limit.down.sql b/server/migrations/665_runtime_rate_limit.down.sql
new file mode 100644
index 0000000000..07d63b25ef
--- /dev/null
+++ b/server/migrations/665_runtime_rate_limit.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS runtime_rate_limit;
diff --git a/server/migrations/665_runtime_rate_limit.up.sql b/server/migrations/665_runtime_rate_limit.up.sql
new file mode 100644
index 0000000000..7ee37283ce
--- /dev/null
+++ b/server/migrations/665_runtime_rate_limit.up.sql
@@ -0,0 +1,15 @@
+-- Latest subscription rate-limit snapshot per runtime (MUL-9427): how much of
+-- the agent CLI account's 5-hour / weekly windows is used and when each
+-- resets, as the CLI itself reported during the runtime's most recent task.
+-- One row per runtime, replaced by newer observations.
+--
+-- No foreign keys (repo rule): runtime deletion (DeleteAgentRuntime,
+-- DeleteAgentRuntimesByProfile) and workspace teardown remove these rows in
+-- the same statements that delete the runtimes.
+CREATE TABLE IF NOT EXISTS runtime_rate_limit (
+ runtime_id UUID PRIMARY KEY,
+ workspace_id UUID NOT NULL,
+ snapshot JSONB NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index e1a42c48f6..3231a140f8 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -172,6 +172,15 @@ type ExecOptions struct {
// can trip its idle watchdog. Take the snapshot and report on your own
// goroutine.
OnUsage func(map[string]TokenUsage)
+ // OnRateLimits optionally receives the account's subscription rate-limit
+ // snapshot each time the agent CLI reports a change (Claude Code's
+ // rate_limit_event, Codex's account/rateLimits/updated). Every call carries
+ // the full merged view, so the latest call supersedes earlier ones.
+ // Backends whose CLI reports no rate limits never call it.
+ //
+ // Like OnUsage it runs on the backend's protocol reader goroutine and MUST
+ // NOT block.
+ OnRateLimits func(RateLimitSnapshot)
// piMcpExtensionPath is set by piBackend.Execute after it writes the
// temporary MCP extension. The daemon does not fill it.
piMcpExtensionPath string
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 1232489226..69d46ae14e 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -221,6 +221,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
sawAsyncLaunch := false
usage := make(map[string]TokenUsage)
seenUsage := make(map[string]struct{})
+ rateLimits := newRateLimitTracker(opts.OnRateLimits)
eventCount := 0
invalidEventCount := 0
assistantEventCount := 0
@@ -319,6 +320,10 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
if b.handleUser(msg, msgCh) {
sawAsyncLaunch = true
}
+ case "rate_limit_event":
+ if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {
+ rateLimits.apply(update)
+ }
case "system":
if msg.SessionID != "" {
sessionID = msg.SessionID
@@ -743,6 +748,9 @@ type claudeSDKMessage struct {
// log fields
Log *claudeLogEntry `json:"log,omitempty"`
+ // rate_limit_event fields
+ RateLimitInfo json.RawMessage `json:"rate_limit_info,omitempty"`
+
// control request fields
RequestID string `json:"request_id,omitempty"`
Request json.RawMessage `json:"request,omitempty"`
diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.go
index 6fddf39ac5..7824632e69 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -1392,3 +1392,59 @@ func TestBuildClaudeArgsManagedSkillSettingsWins(t *testing.T) {
t.Fatalf("unrelated custom arg was dropped: %v", args)
}
}
+
+func TestClaudeExecuteReportsRateLimits(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ "printf '%s\\n' '{\"type\":\"system\",\"session_id\":\"sess-rate-limits\"}'\n" +
+ "printf '%s\\n' '{\"type\":\"rate_limit_event\",\"rate_limit_info\":{\"status\":\"allowed\",\"unifiedWindows\":{\"five_hour\":{\"utilization\":0.25,\"resetsAt\":1795327200},\"seven_day\":{\"utilization\":0.5,\"resetsAt\":1795568400}}},\"session_id\":\"sess-rate-limits\"}'\n" +
+ "printf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"session_id\":\"sess-rate-limits\",\"result\":\"done\"}'\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ snapshots := make(chan RateLimitSnapshot, 4)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Timeout: 5 * time.Second,
+ OnRateLimits: func(s RateLimitSnapshot) { snapshots <- s },
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ select {
+ case <-session.Result:
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+
+ select {
+ case snap := <-snapshots:
+ if snap.Status != RateLimitStatusAllowed || len(snap.Windows) != 2 {
+ t.Fatalf("snapshot = %+v", snap)
+ }
+ if snap.Windows[0].Kind != RateLimitWindowSession || *snap.Windows[0].UsedPercent != 25 {
+ t.Fatalf("session window = %+v", snap.Windows[0])
+ }
+ default:
+ t.Fatal("rate_limit_event did not reach OnRateLimits")
+ }
+}
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 532eee1444..9489929d08 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -1285,6 +1285,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
notificationProtocol: "unknown",
acceptNotification: turnNotificationGate.accept,
guardianRateLimitCircuit: &codexGuardianRateLimitCircuit{},
+ rateLimits: newRateLimitTracker(opts.OnRateLimits),
onGuardianRateLimit: func() {
guardianRateLimitTripped.Store(true)
b.cfg.Logger.Warn("codex Guardian approval rate-limit circuit opened",
@@ -2438,6 +2439,9 @@ type codexClient struct {
onTurnDone func(aborted bool)
guardianRateLimitCircuit *codexGuardianRateLimitCircuit
onGuardianRateLimit func()
+ // rateLimits merges account/rateLimits/updated notifications; nil when
+ // the caller does not collect rate limits.
+ rateLimits *rateLimitTracker
// onFinalAnswer fires only for an agent message the app-server itself
// labelled `phase: "final_answer"` — the turn's deliverable, as opposed to
// the intermediate agent messages that narrate work between tool calls.
@@ -3041,6 +3045,14 @@ func (c *codexClient) handleNotification(raw map[string]json.RawMessage) {
if p, ok := raw["params"]; ok {
_ = json.Unmarshal(p, &params)
}
+ // Rate limits belong to the account, not to a thread or turn, so they are
+ // read before the thread filter and the current-turn gate. The
+ // notification then continues down the usual path unchanged.
+ if method == "account/rateLimits/updated" {
+ if update, ok := parseCodexRateLimitsUpdated(params); ok {
+ c.rateLimits.apply(update)
+ }
+ }
// Filter multiplexed subagent threads before the current-turn gate. The
// gate mutates started/turnID on turn/started; letting another thread reach
// it first can replace the main turn ID and make subsequent main-thread
diff --git a/server/pkg/agent/rate_limits.go b/server/pkg/agent/rate_limits.go
new file mode 100644
index 0000000000..1aecee7aca
--- /dev/null
+++ b/server/pkg/agent/rate_limits.go
@@ -0,0 +1,387 @@
+package agent
+
+import (
+ "encoding/json"
+ "math"
+ "sort"
+ "sync"
+ "time"
+)
+
+// RateLimitSnapshot is the subscription rate-limit state an agent CLI last
+// reported for the account it runs under: how much of each limit window is
+// used and when it resets. Backends observe it passively from the events the
+// CLI already emits while a task runs; nothing here calls the provider.
+type RateLimitSnapshot struct {
+ // PlanType is the provider's plan identifier when it reports one (Codex:
+ // "plus", "pro", ...). Empty when unknown.
+ PlanType string `json:"plan_type,omitempty"`
+ // Status is the provider's overall verdict: allowed, warning or rejected.
+ // Empty when the provider does not state one.
+ Status string `json:"status,omitempty"`
+ Windows []RateLimitWindow `json:"windows"`
+ Credits *RateLimitCredits `json:"credits,omitempty"`
+ // ObservedAt is when the backend last merged an update into the snapshot.
+ ObservedAt time.Time `json:"observed_at"`
+}
+
+// RateLimitWindow is one limit window, such as the 5-hour session or the
+// weekly limit.
+type RateLimitWindow struct {
+ Kind string `json:"kind"`
+ // UsedPercent is 0-100. Providers can report slightly more than 100 when
+ // usage runs past the cap.
+ UsedPercent *float64 `json:"used_percent,omitempty"`
+ WindowMinutes int64 `json:"window_minutes,omitempty"`
+ ResetsAt *time.Time `json:"resets_at,omitempty"`
+ Status string `json:"status,omitempty"`
+}
+
+// RateLimitCredits is a prepaid balance that keeps the agent running after
+// the plan's windows are exhausted (Codex credits).
+type RateLimitCredits struct {
+ HasCredits bool `json:"has_credits"`
+ Unlimited bool `json:"unlimited"`
+ Balance string `json:"balance,omitempty"`
+}
+
+// Rate-limit window kinds. The UI labels windows by kind, so a provider's own
+// window names are mapped onto these rather than passed through.
+const (
+ RateLimitWindowSession = "session"
+ RateLimitWindowWeekly = "weekly"
+ RateLimitWindowWeeklyOpus = "weekly_opus"
+ RateLimitWindowWeeklySonnet = "weekly_sonnet"
+ RateLimitWindowOther = "other"
+)
+
+// Rate-limit statuses.
+const (
+ RateLimitStatusAllowed = "allowed"
+ RateLimitStatusWarning = "warning"
+ RateLimitStatusRejected = "rejected"
+)
+
+const (
+ sessionWindowMinutes = 5 * 60
+ weeklyWindowMinutes = 7 * 24 * 60
+)
+
+var rateLimitWindowOrder = map[string]int{
+ RateLimitWindowSession: 0,
+ RateLimitWindowWeekly: 1,
+ RateLimitWindowWeeklyOpus: 2,
+ RateLimitWindowWeeklySonnet: 3,
+ RateLimitWindowOther: 4,
+}
+
+// rateLimitTracker merges a CLI's incremental rate-limit events into one
+// snapshot and hands every change to the caller's callback. Events arrive on
+// the backend's stdout reader goroutine; the callback must not block (see
+// ExecOptions.OnRateLimits).
+type rateLimitTracker struct {
+ mu sync.Mutex
+ emit func(RateLimitSnapshot)
+ now func() time.Time
+ planType string
+ status string
+ credits *RateLimitCredits
+ windows map[string]RateLimitWindow
+}
+
+func newRateLimitTracker(emit func(RateLimitSnapshot)) *rateLimitTracker {
+ if emit == nil {
+ return nil
+ }
+ return &rateLimitTracker{emit: emit, now: time.Now, windows: map[string]RateLimitWindow{}}
+}
+
+// rateLimitUpdate is one event's worth of new information. Zero values mean
+// "not reported" and leave the previous value in place.
+type rateLimitUpdate struct {
+ planType string
+ status string
+ credits *RateLimitCredits
+ windows []RateLimitWindow
+}
+
+func (t *rateLimitTracker) apply(u rateLimitUpdate) {
+ if t == nil {
+ return
+ }
+ if u.planType == "" && u.status == "" && u.credits == nil && len(u.windows) == 0 {
+ return
+ }
+ t.mu.Lock()
+ if u.planType != "" {
+ t.planType = u.planType
+ }
+ if u.status != "" {
+ t.status = u.status
+ }
+ if u.credits != nil {
+ credits := *u.credits
+ t.credits = &credits
+ }
+ for _, w := range u.windows {
+ t.windows[w.Kind] = w
+ }
+ snap := RateLimitSnapshot{
+ PlanType: t.planType,
+ Status: t.status,
+ Windows: make([]RateLimitWindow, 0, len(t.windows)),
+ ObservedAt: t.now().UTC(),
+ }
+ if t.credits != nil {
+ credits := *t.credits
+ snap.Credits = &credits
+ }
+ for _, w := range t.windows {
+ snap.Windows = append(snap.Windows, w)
+ }
+ t.mu.Unlock()
+
+ sort.SliceStable(snap.Windows, func(i, j int) bool {
+ a, b := snap.Windows[i], snap.Windows[j]
+ if rateLimitWindowOrder[a.Kind] != rateLimitWindowOrder[b.Kind] {
+ return rateLimitWindowOrder[a.Kind] < rateLimitWindowOrder[b.Kind]
+ }
+ return a.WindowMinutes < b.WindowMinutes
+ })
+ t.emit(snap)
+}
+
+func unixSecondsPtr(sec *int64) *time.Time {
+ if sec == nil || *sec <= 0 {
+ return nil
+ }
+ t := time.Unix(*sec, 0).UTC()
+ return &t
+}
+
+func finitePercent(v float64) *float64 {
+ if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 {
+ return nil
+ }
+ return &v
+}
+
+// --- Claude Code -----------------------------------------------------------
+
+// claudeRateLimitInfo is the `rate_limit_info` payload of Claude Code's
+// stream-json `rate_limit_event`. The top-level fields describe the window
+// currently limiting the account; `unifiedWindows` carries every window on
+// every observation in newer CLIs. Utilization is a 0-1 fraction and resetsAt
+// is unix seconds. API-key sessions never emit the event.
+type claudeRateLimitInfo struct {
+ Status string `json:"status"`
+ ResetsAt *int64 `json:"resetsAt"`
+ RateLimitType string `json:"rateLimitType"`
+ Utilization *float64 `json:"utilization"`
+ UnifiedWindows map[string]claudeRateLimitWindowInfo `json:"unifiedWindows"`
+}
+
+type claudeRateLimitWindowInfo struct {
+ Utilization *float64 `json:"utilization"`
+ ResetsAt *int64 `json:"resetsAt"`
+ Status string `json:"status"`
+}
+
+func claudeRateLimitStatus(s string) string {
+ switch s {
+ case "allowed":
+ return RateLimitStatusAllowed
+ case "allowed_warning":
+ return RateLimitStatusWarning
+ case "rejected":
+ return RateLimitStatusRejected
+ default:
+ return ""
+ }
+}
+
+// claudeRateLimitKind maps Claude's window names onto window kinds. Windows
+// whose meaning the UI cannot label (overage buckets) are dropped.
+func claudeRateLimitKind(name string) (kind string, minutes int64, ok bool) {
+ switch name {
+ case "five_hour":
+ return RateLimitWindowSession, sessionWindowMinutes, true
+ case "seven_day":
+ return RateLimitWindowWeekly, weeklyWindowMinutes, true
+ case "seven_day_opus":
+ return RateLimitWindowWeeklyOpus, weeklyWindowMinutes, true
+ case "seven_day_sonnet":
+ return RateLimitWindowWeeklySonnet, weeklyWindowMinutes, true
+ default:
+ return "", 0, false
+ }
+}
+
+func claudeRateLimitWindow(name string, utilization *float64, resetsAt *int64, status string) (RateLimitWindow, bool) {
+ kind, minutes, ok := claudeRateLimitKind(name)
+ if !ok {
+ return RateLimitWindow{}, false
+ }
+ w := RateLimitWindow{
+ Kind: kind,
+ WindowMinutes: minutes,
+ ResetsAt: unixSecondsPtr(resetsAt),
+ Status: claudeRateLimitStatus(status),
+ }
+ if utilization != nil {
+ w.UsedPercent = finitePercent(*utilization * 100)
+ }
+ if w.UsedPercent == nil && w.ResetsAt == nil && w.Status == "" {
+ return RateLimitWindow{}, false
+ }
+ return w, true
+}
+
+// mergeClaudeRateLimitWindow combines the top-level summary of the limiting
+// window with its unifiedWindows entry. Usage and reset come from the
+// per-window view when present; the status stays the top-level one, which is
+// the CLI's verdict for that window (unifiedWindows often carries no status).
+func mergeClaudeRateLimitWindow(top, unified RateLimitWindow) RateLimitWindow {
+ merged := unified
+ if merged.UsedPercent == nil {
+ merged.UsedPercent = top.UsedPercent
+ }
+ if merged.ResetsAt == nil {
+ merged.ResetsAt = top.ResetsAt
+ }
+ if top.Status != "" {
+ merged.Status = top.Status
+ }
+ return merged
+}
+
+// parseClaudeRateLimitEvent converts one rate_limit_info payload into an
+// update. The top-level status applies only to the window rateLimitType
+// names; other windows keep their own.
+func parseClaudeRateLimitEvent(raw json.RawMessage) (rateLimitUpdate, bool) {
+ if len(raw) == 0 {
+ return rateLimitUpdate{}, false
+ }
+ var info claudeRateLimitInfo
+ if err := json.Unmarshal(raw, &info); err != nil {
+ return rateLimitUpdate{}, false
+ }
+ u := rateLimitUpdate{status: claudeRateLimitStatus(info.Status)}
+ byKind := map[string]RateLimitWindow{}
+ if w, ok := claudeRateLimitWindow(info.RateLimitType, info.Utilization, info.ResetsAt, info.Status); ok {
+ byKind[w.Kind] = w
+ }
+ for name, win := range info.UnifiedWindows {
+ w, ok := claudeRateLimitWindow(name, win.Utilization, win.ResetsAt, win.Status)
+ if !ok {
+ continue
+ }
+ if top, seen := byKind[w.Kind]; seen {
+ w = mergeClaudeRateLimitWindow(top, w)
+ }
+ byKind[w.Kind] = w
+ }
+ for _, w := range byKind {
+ u.windows = append(u.windows, w)
+ }
+ return u, u.status != "" || len(u.windows) > 0
+}
+
+// --- Codex -----------------------------------------------------------------
+
+// codexRateLimitSnapshot is the `rateLimits` payload of Codex app-server's
+// `account/rateLimits/updated` notification. Updates are sparse: a null field
+// keeps the previously observed value. usedPercent is 0-100 and resetsAt is
+// unix seconds.
+type codexRateLimitSnapshot struct {
+ LimitID *string `json:"limitId"`
+ Primary *codexRateLimitWindow `json:"primary"`
+ Secondary *codexRateLimitWindow `json:"secondary"`
+ Credits *struct {
+ HasCredits bool `json:"hasCredits"`
+ Unlimited bool `json:"unlimited"`
+ Balance *string `json:"balance"`
+ } `json:"credits"`
+ PlanType *string `json:"planType"`
+}
+
+type codexRateLimitWindow struct {
+ UsedPercent *float64 `json:"usedPercent"`
+ WindowDurationMins *int64 `json:"windowDurationMins"`
+ ResetsAt *int64 `json:"resetsAt"`
+}
+
+// codexMainRateLimitID is the limit bucket the plan's session/weekly windows
+// belong to. Model-specific buckets carry their own ids and are not shown.
+const codexMainRateLimitID = "codex"
+
+func codexRateLimitKind(minutes int64, fallback string) string {
+ switch {
+ case minutes <= 0:
+ return fallback
+ case minutes <= 24*60:
+ return RateLimitWindowSession
+ case minutes >= 6*24*60 && minutes <= 8*24*60:
+ return RateLimitWindowWeekly
+ default:
+ return RateLimitWindowOther
+ }
+}
+
+func codexRateLimitWindowFrom(w *codexRateLimitWindow, fallback string) (RateLimitWindow, bool) {
+ if w == nil || w.UsedPercent == nil {
+ return RateLimitWindow{}, false
+ }
+ var minutes int64
+ if w.WindowDurationMins != nil {
+ minutes = *w.WindowDurationMins
+ }
+ used := finitePercent(*w.UsedPercent)
+ if used == nil {
+ return RateLimitWindow{}, false
+ }
+ return RateLimitWindow{
+ Kind: codexRateLimitKind(minutes, fallback),
+ UsedPercent: used,
+ WindowMinutes: minutes,
+ ResetsAt: unixSecondsPtr(w.ResetsAt),
+ }, true
+}
+
+// parseCodexRateLimitsUpdated converts the notification params into an
+// update. Primary is the short window and secondary the weekly one; the
+// duration decides when Codex reports it.
+func parseCodexRateLimitsUpdated(params map[string]any) (rateLimitUpdate, bool) {
+ raw, ok := params["rateLimits"]
+ if !ok || raw == nil {
+ return rateLimitUpdate{}, false
+ }
+ data, err := json.Marshal(raw)
+ if err != nil {
+ return rateLimitUpdate{}, false
+ }
+ var snap codexRateLimitSnapshot
+ if err := json.Unmarshal(data, &snap); err != nil {
+ return rateLimitUpdate{}, false
+ }
+ if snap.LimitID != nil && *snap.LimitID != "" && *snap.LimitID != codexMainRateLimitID {
+ return rateLimitUpdate{}, false
+ }
+ var u rateLimitUpdate
+ if snap.PlanType != nil {
+ u.planType = *snap.PlanType
+ }
+ if snap.Credits != nil {
+ u.credits = &RateLimitCredits{HasCredits: snap.Credits.HasCredits, Unlimited: snap.Credits.Unlimited}
+ if snap.Credits.Balance != nil {
+ u.credits.Balance = *snap.Credits.Balance
+ }
+ }
+ if w, ok := codexRateLimitWindowFrom(snap.Primary, RateLimitWindowSession); ok {
+ u.windows = append(u.windows, w)
+ }
+ if w, ok := codexRateLimitWindowFrom(snap.Secondary, RateLimitWindowWeekly); ok {
+ u.windows = append(u.windows, w)
+ }
+ return u, u.planType != "" || u.credits != nil || len(u.windows) > 0
+}
diff --git a/server/pkg/agent/rate_limits_test.go b/server/pkg/agent/rate_limits_test.go
new file mode 100644
index 0000000000..d1f06810b2
--- /dev/null
+++ b/server/pkg/agent/rate_limits_test.go
@@ -0,0 +1,259 @@
+package agent
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+func collectRateLimits(t *testing.T) (*rateLimitTracker, *[]RateLimitSnapshot) {
+ t.Helper()
+ var got []RateLimitSnapshot
+ tr := newRateLimitTracker(func(s RateLimitSnapshot) { got = append(got, s) })
+ tr.now = func() time.Time { return time.Date(2026, 11, 16, 3, 46, 0, 0, time.UTC) }
+ return tr, &got
+}
+
+func windowByKind(t *testing.T, s RateLimitSnapshot, kind string) RateLimitWindow {
+ t.Helper()
+ for _, w := range s.Windows {
+ if w.Kind == kind {
+ return w
+ }
+ }
+ t.Fatalf("window %q missing from %+v", kind, s.Windows)
+ return RateLimitWindow{}
+}
+
+func TestParseClaudeRateLimitEventUnifiedWindows(t *testing.T) {
+ // Shape emitted by Claude Code 2.1.x: the top level names the limiting
+ // window, unifiedWindows carries every window.
+ raw := json.RawMessage(`{
+ "status": "allowed_warning",
+ "resetsAt": 1795327200,
+ "rateLimitType": "five_hour",
+ "utilization": 0.72,
+ "unifiedWindows": {
+ "five_hour": {"utilization": 0.72, "resetsAt": 1795327200, "status": "allowed_warning"},
+ "seven_day": {"utilization": 0.41, "resetsAt": 1795568400, "status": "allowed"},
+ "seven_day_overage_included": {"utilization": 0.1, "resetsAt": 1795568400}
+ }
+ }`)
+ update, ok := parseClaudeRateLimitEvent(raw)
+ if !ok {
+ t.Fatal("expected an update")
+ }
+ tr, got := collectRateLimits(t)
+ tr.apply(update)
+ if len(*got) != 1 {
+ t.Fatalf("emits = %d, want 1", len(*got))
+ }
+ snap := (*got)[0]
+ if snap.Status != RateLimitStatusWarning {
+ t.Fatalf("status = %q", snap.Status)
+ }
+ if len(snap.Windows) != 2 {
+ t.Fatalf("windows = %+v, want session and weekly only", snap.Windows)
+ }
+ if snap.Windows[0].Kind != RateLimitWindowSession || snap.Windows[1].Kind != RateLimitWindowWeekly {
+ t.Fatalf("window order = %+v", snap.Windows)
+ }
+ session := windowByKind(t, snap, RateLimitWindowSession)
+ if session.UsedPercent == nil || *session.UsedPercent < 71.99 || *session.UsedPercent > 72.01 {
+ t.Fatalf("session used = %v", session.UsedPercent)
+ }
+ if session.WindowMinutes != 300 || session.Status != RateLimitStatusWarning {
+ t.Fatalf("session = %+v", session)
+ }
+ if session.ResetsAt == nil || !session.ResetsAt.Equal(time.Unix(1795327200, 0)) {
+ t.Fatalf("session reset = %v", session.ResetsAt)
+ }
+ weekly := windowByKind(t, snap, RateLimitWindowWeekly)
+ if weekly.WindowMinutes != 7*24*60 || weekly.Status != RateLimitStatusAllowed {
+ t.Fatalf("weekly = %+v", weekly)
+ }
+}
+
+func TestParseClaudeRateLimitEventKeepsTopLevelRejection(t *testing.T) {
+ // Claude Code 2.1.300: unifiedWindows carries only utilization/resetsAt and
+ // the verdict lives at the top level, so a rejected account can still show
+ // a window just under 100%.
+ update, ok := parseClaudeRateLimitEvent(json.RawMessage(`{
+ "status": "rejected",
+ "resetsAt": 1795327200,
+ "rateLimitType": "five_hour",
+ "unifiedWindows": {
+ "five_hour": {"utilization": 0.99, "resetsAt": 1795327200},
+ "seven_day": {"utilization": 0.41, "resetsAt": 1795568400}
+ }
+ }`))
+ if !ok {
+ t.Fatal("expected an update")
+ }
+ tr, got := collectRateLimits(t)
+ tr.apply(update)
+ snap := (*got)[0]
+ if snap.Status != RateLimitStatusRejected {
+ t.Fatalf("status = %q", snap.Status)
+ }
+ session := windowByKind(t, snap, RateLimitWindowSession)
+ if session.Status != RateLimitStatusRejected {
+ t.Fatalf("session status = %q, want rejected", session.Status)
+ }
+ if session.UsedPercent == nil || *session.UsedPercent < 98.99 || *session.UsedPercent > 99.01 {
+ t.Fatalf("session used = %v", session.UsedPercent)
+ }
+ if session.ResetsAt == nil || !session.ResetsAt.Equal(time.Unix(1795327200, 0)) {
+ t.Fatalf("session reset = %v", session.ResetsAt)
+ }
+ if weekly := windowByKind(t, snap, RateLimitWindowWeekly); weekly.Status != "" {
+ t.Fatalf("weekly status = %q, top-level verdict leaked to another window", weekly.Status)
+ }
+}
+
+func TestParseClaudeRateLimitEventTopLevelFillsMissingUnifiedFields(t *testing.T) {
+ update, _ := parseClaudeRateLimitEvent(json.RawMessage(`{
+ "status": "allowed_warning",
+ "resetsAt": 1795327200,
+ "rateLimitType": "five_hour",
+ "utilization": 0.85,
+ "unifiedWindows": {"five_hour": {"status": "allowed"}}
+ }`))
+ if len(update.windows) != 1 {
+ t.Fatalf("windows = %+v", update.windows)
+ }
+ w := update.windows[0]
+ if w.Status != RateLimitStatusWarning || w.UsedPercent == nil || *w.UsedPercent < 84.99 || w.ResetsAt == nil {
+ t.Fatalf("window = %+v", w)
+ }
+}
+
+func TestParseClaudeRateLimitEventTopLevelOnly(t *testing.T) {
+ // Older CLIs send only the limiting window, often without utilization.
+ update, ok := parseClaudeRateLimitEvent(json.RawMessage(`{"status":"rejected","resetsAt":1795327200,"rateLimitType":"seven_day_opus"}`))
+ if !ok {
+ t.Fatal("expected an update")
+ }
+ if len(update.windows) != 1 {
+ t.Fatalf("windows = %+v", update.windows)
+ }
+ w := update.windows[0]
+ if w.Kind != RateLimitWindowWeeklyOpus || w.UsedPercent != nil || w.Status != RateLimitStatusRejected || w.ResetsAt == nil {
+ t.Fatalf("window = %+v", w)
+ }
+ if update.status != RateLimitStatusRejected {
+ t.Fatalf("status = %q", update.status)
+ }
+}
+
+func TestParseClaudeRateLimitEventRejectsGarbage(t *testing.T) {
+ for _, raw := range []string{``, `null`, `"x"`, `{}`, `{"rateLimitType":"overage","utilization":0.5}`} {
+ if _, ok := parseClaudeRateLimitEvent(json.RawMessage(raw)); ok {
+ t.Fatalf("%q produced an update", raw)
+ }
+ }
+}
+
+func TestRateLimitTrackerMergesWindowsAcrossEvents(t *testing.T) {
+ tr, got := collectRateLimits(t)
+ first, _ := parseClaudeRateLimitEvent(json.RawMessage(`{"status":"allowed","unifiedWindows":{"five_hour":{"utilization":0.2,"resetsAt":1795327200},"seven_day":{"utilization":0.4,"resetsAt":1795568400}}}`))
+ tr.apply(first)
+ second, _ := parseClaudeRateLimitEvent(json.RawMessage(`{"status":"allowed_warning","rateLimitType":"five_hour","utilization":0.8,"resetsAt":1795327200}`))
+ tr.apply(second)
+ if len(*got) != 2 {
+ t.Fatalf("emits = %d", len(*got))
+ }
+ last := (*got)[1]
+ if last.Status != RateLimitStatusWarning {
+ t.Fatalf("status = %q", last.Status)
+ }
+ if used := windowByKind(t, last, RateLimitWindowSession).UsedPercent; used == nil || *used < 79.99 {
+ t.Fatalf("session not updated: %v", used)
+ }
+ if used := windowByKind(t, last, RateLimitWindowWeekly).UsedPercent; used == nil || *used < 39.99 || *used > 40.01 {
+ t.Fatalf("weekly lost by a partial event: %v", used)
+ }
+ // Each emit is an independent copy.
+ if used := windowByKind(t, (*got)[0], RateLimitWindowSession).UsedPercent; *used > 20.01 {
+ t.Fatalf("earlier snapshot mutated: %v", *used)
+ }
+}
+
+func TestRateLimitTrackerNilIsInert(t *testing.T) {
+ var tr *rateLimitTracker
+ tr.apply(rateLimitUpdate{status: RateLimitStatusAllowed})
+ if newRateLimitTracker(nil) != nil {
+ t.Fatal("tracker without a callback should be nil")
+ }
+}
+
+func codexParams(t *testing.T, payload string) map[string]any {
+ t.Helper()
+ var params map[string]any
+ if err := json.Unmarshal([]byte(payload), &params); err != nil {
+ t.Fatal(err)
+ }
+ return params
+}
+
+func TestParseCodexRateLimitsUpdated(t *testing.T) {
+ params := codexParams(t, `{"rateLimits":{
+ "limitId":"codex",
+ "primary":{"usedPercent":18,"windowDurationMins":300,"resetsAt":1795331520},
+ "secondary":{"usedPercent":93,"windowDurationMins":10080,"resetsAt":1795478400},
+ "credits":{"hasCredits":true,"unlimited":false,"balance":"240"},
+ "planType":"pro"
+ }}`)
+ update, ok := parseCodexRateLimitsUpdated(params)
+ if !ok {
+ t.Fatal("expected an update")
+ }
+ tr, got := collectRateLimits(t)
+ tr.apply(update)
+ snap := (*got)[0]
+ if snap.PlanType != "pro" {
+ t.Fatalf("plan = %q", snap.PlanType)
+ }
+ if snap.Credits == nil || !snap.Credits.HasCredits || snap.Credits.Balance != "240" {
+ t.Fatalf("credits = %+v", snap.Credits)
+ }
+ if w := windowByKind(t, snap, RateLimitWindowSession); *w.UsedPercent != 18 || w.WindowMinutes != 300 {
+ t.Fatalf("session = %+v", w)
+ }
+ if w := windowByKind(t, snap, RateLimitWindowWeekly); *w.UsedPercent != 93 || w.ResetsAt == nil {
+ t.Fatalf("weekly = %+v", w)
+ }
+}
+
+func TestParseCodexRateLimitsUpdatedSparse(t *testing.T) {
+ tr, got := collectRateLimits(t)
+ full, _ := parseCodexRateLimitsUpdated(codexParams(t, `{"rateLimits":{"primary":{"usedPercent":10,"windowDurationMins":300},"secondary":{"usedPercent":50,"windowDurationMins":10080},"planType":"plus"}}`))
+ tr.apply(full)
+ // A rolling update without plan metadata or the weekly window keeps both.
+ sparse, ok := parseCodexRateLimitsUpdated(codexParams(t, `{"rateLimits":{"primary":{"usedPercent":12,"windowDurationMins":300},"secondary":null,"planType":null}}`))
+ if !ok {
+ t.Fatal("expected an update")
+ }
+ tr.apply(sparse)
+ last := (*got)[len(*got)-1]
+ if last.PlanType != "plus" {
+ t.Fatalf("plan cleared by a sparse update: %q", last.PlanType)
+ }
+ if *windowByKind(t, last, RateLimitWindowSession).UsedPercent != 12 || *windowByKind(t, last, RateLimitWindowWeekly).UsedPercent != 50 {
+ t.Fatalf("windows = %+v", last.Windows)
+ }
+}
+
+func TestParseCodexRateLimitsUpdatedIgnoresOtherBuckets(t *testing.T) {
+ if _, ok := parseCodexRateLimitsUpdated(codexParams(t, `{"rateLimits":{"limitId":"codex_spark","primary":{"usedPercent":90,"windowDurationMins":300}}}`)); ok {
+ t.Fatal("a model-specific bucket must not overwrite the plan's windows")
+ }
+ if _, ok := parseCodexRateLimitsUpdated(codexParams(t, `{"other":1}`)); ok {
+ t.Fatal("missing rateLimits produced an update")
+ }
+ // Without a duration, primary/secondary fall back to session/weekly.
+ update, ok := parseCodexRateLimitsUpdated(codexParams(t, `{"rateLimits":{"primary":{"usedPercent":5},"secondary":{"usedPercent":6}}}`))
+ if !ok || len(update.windows) != 2 || update.windows[0].Kind != RateLimitWindowSession || update.windows[1].Kind != RateLimitWindowWeekly {
+ t.Fatalf("fallback kinds = %+v", update.windows)
+ }
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index c5bab6d5ee..121b1021f7 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1616,6 +1616,14 @@ type RuntimeProfile struct {
RuntimeType string `json:"runtime_type"`
}
+type RuntimeRateLimit struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Snapshot []byte `json:"snapshot"`
+ ObservedAt pgtype.Timestamptz `json:"observed_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type SearchIndexChange struct {
EntityType string `json:"entity_type"`
EntityID pgtype.UUID `json:"entity_id"`
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 924b4afcc2..b2c75ef59d 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -309,9 +309,13 @@ func (q *Queries) CountUndrainedTasksByRuntimeOrAgent(ctx context.Context, arg C
}
const deleteAgentRuntime = `-- name: DeleteAgentRuntime :exec
+WITH deleted_rate_limit AS (
+ DELETE FROM runtime_rate_limit WHERE runtime_id = $1
+)
DELETE FROM agent_runtime WHERE id = $1
`
+// runtime_rate_limit has no FK; its row goes with the runtime.
func (q *Queries) DeleteAgentRuntime(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteAgentRuntime, id)
return err
diff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.go
index e5e12c1412..e7870004f2 100644
--- a/server/pkg/db/generated/runtime_profile.sql.go
+++ b/server/pkg/db/generated/runtime_profile.sql.go
@@ -77,8 +77,15 @@ func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimePro
}
const deleteAgentRuntimesByProfile = `-- name: DeleteAgentRuntimesByProfile :many
+WITH deleted_rate_limits AS (
+ DELETE FROM runtime_rate_limit
+ WHERE runtime_rate_limit.runtime_id IN (
+ SELECT profile_runtime.id FROM agent_runtime AS profile_runtime
+ WHERE profile_runtime.profile_id = $1 AND profile_runtime.workspace_id = $2
+ )
+)
DELETE FROM agent_runtime
-WHERE profile_id = $1 AND workspace_id = $2
+WHERE agent_runtime.profile_id = $1 AND agent_runtime.workspace_id = $2
RETURNING id, workspace_id, owner_id, daemon_id, provider
`
diff --git a/server/pkg/db/generated/runtime_rate_limit.sql.go b/server/pkg/db/generated/runtime_rate_limit.sql.go
new file mode 100644
index 0000000000..7ffa5a5837
--- /dev/null
+++ b/server/pkg/db/generated/runtime_rate_limit.sql.go
@@ -0,0 +1,62 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: runtime_rate_limit.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const getRuntimeRateLimit = `-- name: GetRuntimeRateLimit :one
+SELECT runtime_id, workspace_id, snapshot, observed_at, updated_at
+FROM runtime_rate_limit
+WHERE runtime_id = $1
+`
+
+func (q *Queries) GetRuntimeRateLimit(ctx context.Context, runtimeID pgtype.UUID) (RuntimeRateLimit, error) {
+ row := q.db.QueryRow(ctx, getRuntimeRateLimit, runtimeID)
+ var i RuntimeRateLimit
+ err := row.Scan(
+ &i.RuntimeID,
+ &i.WorkspaceID,
+ &i.Snapshot,
+ &i.ObservedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const upsertRuntimeRateLimit = `-- name: UpsertRuntimeRateLimit :exec
+INSERT INTO runtime_rate_limit (runtime_id, workspace_id, snapshot, observed_at)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (runtime_id) DO UPDATE
+SET snapshot = EXCLUDED.snapshot,
+ workspace_id = EXCLUDED.workspace_id,
+ observed_at = EXCLUDED.observed_at,
+ updated_at = now()
+WHERE runtime_rate_limit.observed_at <= EXCLUDED.observed_at
+`
+
+type UpsertRuntimeRateLimitParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Snapshot []byte `json:"snapshot"`
+ ObservedAt pgtype.Timestamptz `json:"observed_at"`
+}
+
+// One snapshot per runtime (MUL-9427). Concurrent runs on the same runtime
+// each report their own view; the newest observation wins, so a late report
+// from an older run cannot roll the snapshot back.
+func (q *Queries) UpsertRuntimeRateLimit(ctx context.Context, arg UpsertRuntimeRateLimitParams) error {
+ _, err := q.db.Exec(ctx, upsertRuntimeRateLimit,
+ arg.RuntimeID,
+ arg.WorkspaceID,
+ arg.Snapshot,
+ arg.ObservedAt,
+ )
+ return err
+}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 2f796ffb04..cded9c7afb 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -655,6 +655,9 @@ WITH
deleted_runtimes AS (
DELETE FROM agent_runtime WHERE agent_runtime.workspace_id = $1
),
+deleted_runtime_rate_limits AS (
+ DELETE FROM runtime_rate_limit WHERE runtime_rate_limit.workspace_id = $1
+),
deleted_profiles AS (
DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1
),
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 82c86103a4..583b4633d6 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -495,6 +495,10 @@ WHERE runtime_id = @runtime_id
RETURNING *;
-- name: DeleteAgentRuntime :exec
+-- runtime_rate_limit has no FK; its row goes with the runtime.
+WITH deleted_rate_limit AS (
+ DELETE FROM runtime_rate_limit WHERE runtime_id = $1
+)
DELETE FROM agent_runtime WHERE id = $1;
-- name: DeleteSystemAgentsByRuntime :exec
diff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sql
index 0636bac425..18082cd480 100644
--- a/server/pkg/db/queries/runtime_profile.sql
+++ b/server/pkg/db/queries/runtime_profile.sql
@@ -78,8 +78,15 @@ WHERE id = $1 AND workspace_id = $2;
-- the profile-delete path must remove the profile's registered runtime
-- instances itself. Returns the deleted rows so the caller can broadcast /
-- audit. Runs inside the same transaction as DeleteRuntimeProfile.
+WITH deleted_rate_limits AS (
+ DELETE FROM runtime_rate_limit
+ WHERE runtime_rate_limit.runtime_id IN (
+ SELECT profile_runtime.id FROM agent_runtime AS profile_runtime
+ WHERE profile_runtime.profile_id = $1 AND profile_runtime.workspace_id = $2
+ )
+)
DELETE FROM agent_runtime
-WHERE profile_id = $1 AND workspace_id = $2
+WHERE agent_runtime.profile_id = $1 AND agent_runtime.workspace_id = $2
RETURNING id, workspace_id, owner_id, daemon_id, provider;
-- name: ListActiveAgentsByProfile :many
diff --git a/server/pkg/db/queries/runtime_rate_limit.sql b/server/pkg/db/queries/runtime_rate_limit.sql
new file mode 100644
index 0000000000..00f681bb17
--- /dev/null
+++ b/server/pkg/db/queries/runtime_rate_limit.sql
@@ -0,0 +1,17 @@
+-- name: UpsertRuntimeRateLimit :exec
+-- One snapshot per runtime (MUL-9427). Concurrent runs on the same runtime
+-- each report their own view; the newest observation wins, so a late report
+-- from an older run cannot roll the snapshot back.
+INSERT INTO runtime_rate_limit (runtime_id, workspace_id, snapshot, observed_at)
+VALUES (@runtime_id, @workspace_id, @snapshot, @observed_at)
+ON CONFLICT (runtime_id) DO UPDATE
+SET snapshot = EXCLUDED.snapshot,
+ workspace_id = EXCLUDED.workspace_id,
+ observed_at = EXCLUDED.observed_at,
+ updated_at = now()
+WHERE runtime_rate_limit.observed_at <= EXCLUDED.observed_at;
+
+-- name: GetRuntimeRateLimit :one
+SELECT runtime_id, workspace_id, snapshot, observed_at, updated_at
+FROM runtime_rate_limit
+WHERE runtime_id = $1;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 9779dc6b73..3d7ce93b7f 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -740,6 +740,9 @@ WITH
deleted_runtimes AS (
DELETE FROM agent_runtime WHERE agent_runtime.workspace_id = $1
),
+deleted_runtime_rate_limits AS (
+ DELETE FROM runtime_rate_limit WHERE runtime_rate_limit.workspace_id = $1
+),
deleted_profiles AS (
DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1
),