Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add provider token usage and quota (#617)

Gustavo Ye83748d9da9ff
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 1d2cac942..af5cd9568 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -46,6 +46,7 @@ export const SPEC_SECONDS = {
"33-picker-async-layout.spec.ts": 57,
"34-inbox-read-race.spec.ts": 42,
"35-channel-ref-directory-states.spec.ts": 60,
+ "35-bot-token-usage-quota.spec.ts": 45,
"36-server-switch-pending-checkpoint.spec.ts": 60,
"37-server-rail-pdd.spec.ts": 10,
"38-community-navigation-checkpoint-matrix.spec.ts": 60,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 97461529e..de27f9eab 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([347, 348, 349, 349, 352])
+ expect(totals.sort((left, right) => left - right)).toEqual([355, 356, 359, 360, 360])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
index e5cdc4fc8..d73fafebb 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
@@ -68,6 +68,16 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
expect(kinds).toContain("turn_end");
expect(kinds).toContain("telemetry");
expect(out).toContainEqual({ kind: "turn_end", sessionId: "s1", turnOwner: "claude:root-1" });
+ expect(out).toContainEqual({
+ kind: "telemetry",
+ name: "token_usage",
+ source: "claude_result_usage",
+ usage: {
+ input: 3,
+ output: 5,
+ cache: null,
+ },
+ });
});
it("result with is_error → error + turn_end", () => {
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
index bce13f94a..aadfca22b 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
@@ -132,24 +132,24 @@ export class ClaudeEventNormalizer {
private buildUsageTelemetry(event: any): AdapterEvent | null {
const u = event?.usage;
- if (!u && event?.total_cost_usd == null) return null;
+ if (!u) return null;
+ const metric = (value: unknown) =>
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+ ? value
+ : null;
+ const cacheParts = [u.cache_read_input_tokens, u.cache_creation_input_tokens]
+ .filter((value): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
+ const cache = cacheParts.length > 0 && Number.isSafeInteger(cacheParts.reduce((sum, value) => sum + value, 0))
+ ? cacheParts.reduce((sum, value) => sum + value, 0)
+ : null;
return {
kind: "telemetry",
name: "token_usage",
source: "claude_result_usage",
- usageKind: "per_turn",
- attrs: {
- inputTokens: u?.input_tokens,
- outputTokens: u?.output_tokens,
- cachedInputTokens: u?.cache_read_input_tokens,
- cacheCreationInputTokens: u?.cache_creation_input_tokens,
- totalCostUsd: event?.total_cost_usd,
- durationMs: event?.duration_ms,
- durationApiMs: event?.duration_api_ms,
- numTurns: event?.num_turns,
- resultSubtype: event?.subtype,
- resultIsError: event?.is_error,
- serviceTier: u?.service_tier,
+ usage: {
+ input: metric(u.input_tokens),
+ output: metric(u.output_tokens),
+ cache,
},
};
}
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
index 9bb9f975a..ad6d1ea39 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
@@ -352,6 +352,26 @@ describe("CodexDriver initialize payload", () => {
.find((message) => message.method === "thread/start");
expect(defaultStart.params.config).toBeUndefined();
});
+
+ it("reads the account before requesting its quota snapshot", async () => {
+ const driver = new CodexDriver();
+ const { process: proc } = await driver.spawn(baseCtx());
+ await Promise.resolve();
+
+ const beforeAccount = stdinWrites(proc).map((line) => JSON.parse(line.trim()));
+ const accountRead = beforeAccount.find((message) => message.method === "account/read");
+ expect(accountRead).toBeDefined();
+ expect(beforeAccount.some((message) => message.method === "account/rateLimits/read")).toBe(false);
+
+ driver.normalizeLine(JSON.stringify({
+ jsonrpc: "2.0",
+ id: accountRead.id,
+ result: { account: { type: "chatgpt", email: "[email protected]", planType: "pro" } },
+ }));
+
+ const afterAccount = stdinWrites(proc).map((line) => JSON.parse(line.trim()));
+ expect(afterAccount.filter((message) => message.method === "account/rateLimits/read")).toHaveLength(1);
+ });
});
// The `thread/start` (or resume) RESULT line carries the new thread id and is
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
index 599b967e5..be44ca953 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -30,7 +30,7 @@ import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
import { resolveCodexHomeRootFromEnv } from "./home.js";
import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";
-import { jsonRpcRequest } from "../../internal/utils.js";
+import { jsonRpcRequest, tryParseJsonLine } from "../../internal/utils.js";
import { scrubDriverErrorMessage } from "../../internal/errors.js";
const SETTINGS_UPDATE_TIMEOUT_MS = 5_000;
@@ -65,6 +65,7 @@ export class CodexDriver implements BackendAdapter {
} as const;
private readonly eventNormalizer = new CodexEventNormalizer();
+ private readonly pendingAccountReadRequestIds = new Set<number>();
private requestId = 0;
/** Resolved Codex home root (CODEX_HOME or ~/.codex); set on spawn. */
private codexHomeRoot: string | null = null;
@@ -99,6 +100,25 @@ export class CodexDriver implements BackendAdapter {
return ++this.requestId;
}
+ private requestAccountQuotaSnapshot(): void {
+ if (!this.proc?.stdin || this.proc.stdin.destroyed) return;
+ const accountReadRequestId = this.nextRequestId();
+ this.pendingAccountReadRequestIds.add(accountReadRequestId);
+ this.eventNormalizer.registerAccountReadRequest(accountReadRequestId);
+ this.proc.stdin.write(jsonRpcRequest(
+ "account/read",
+ { refreshToken: false },
+ accountReadRequestId,
+ ) + "\n");
+ }
+
+ private requestQuotaSnapshot(): void {
+ if (!this.proc?.stdin || this.proc.stdin.destroyed) return;
+ const quotaReadRequestId = this.nextRequestId();
+ this.eventNormalizer.registerQuotaReadRequest(quotaReadRequestId);
+ this.proc.stdin.write(jsonRpcRequest("account/rateLimits/read", {}, quotaReadRequestId) + "\n");
+ }
+
/** Resolved Codex home root (CODEX_HOME or ~/.codex). Null until spawned. */
get codexHome(): string | null {
return this.codexHomeRoot;
@@ -301,6 +321,7 @@ export class CodexDriver implements BackendAdapter {
} else {
proc.stdin?.write(jsonRpcRequest("thread/start", freshParams, this.nextRequestId()) + "\n");
}
+ this.requestAccountQuotaSnapshot();
});
return { process: proc };
@@ -329,7 +350,18 @@ export class CodexDriver implements BackendAdapter {
normalizeLine(line: string): AdapterEvent[] {
const settingsResponse = this.consumeSettingsUpdateResponse(line);
if (settingsResponse) return [];
+ const parsed = tryParseJsonLine(line) as { id?: unknown; method?: unknown } | null;
const events = this.eventNormalizer.normalizeLine(line);
+ if (
+ typeof parsed?.id === "number"
+ && this.pendingAccountReadRequestIds.delete(parsed.id)
+ ) {
+ // Establish (and, if needed, rotate) the account-scoped source epoch
+ // before asking for limits. Issuing both RPCs concurrently can associate
+ // a fast quota response with the previous account after an account swap.
+ this.requestQuotaSnapshot();
+ }
+ if (parsed?.method === "account/updated") this.requestAccountQuotaSnapshot();
// Missing-rollout resume recovery — before any session_init is adopted.
if (this.pendingResumeFallbackParams && this.proc?.stdin && !this.proc.stdin.destroyed) {
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
index ce053555f..7357f6891 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
@@ -345,11 +345,153 @@ describe("CodexEventNormalizer — complete owned event family", () => {
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "agentMessage", text: "final" } }))).toEqual([{ kind: "assistant_message_completed", text: "final" }]);
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "reasoning", text: "thought" } }))).toEqual([{ kind: "assistant_reasoning_completed", text: "thought" }]);
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "unknown" } }))).toEqual([]);
- expect(n.normalizeLine(notify("thread/tokenUsage/updated", { threadId: "root", tokenUsage: {} }))).toHaveLength(1);
- expect(n.normalizeLine(notify("account/rateLimits/updated", { threadId: "root", rateLimits: {} }))).toHaveLength(1);
+ expect(n.normalizeLine(notify("thread/tokenUsage/updated", { threadId: "root", tokenUsage: {} }))).toEqual([]);
+ expect(n.normalizeLine(notify("account/rateLimits/updated", { threadId: "root", rateLimits: {} }))).toEqual([]);
expect(n.normalizeLine(notify("turn/completed", { threadId: "root", turn: { id: "turn", status: "interrupted" } }))).toEqual([
{ kind: "error", message: "Codex turn interrupted" },
{ kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },
]);
});
+
+ it("emits only the latest current-turn usage at terminal and maps Spark quota windows", () => {
+ const n = new CodexEventNormalizer();
+ adoptRootTurn(n, "root", "turn");
+ expect(n.normalizeLine(notify("thread/tokenUsage/updated", {
+ threadId: "root",
+ tokenUsage: {
+ last: { inputTokens: 100, cachedInputTokens: 40, outputTokens: 12 },
+ total: { inputTokens: 9_999, cachedInputTokens: 8_888, outputTokens: 7_777 },
+ },
+ }))).toEqual([]);
+ expect(n.normalizeLine(notify("thread/tokenUsage/updated", {
+ threadId: "root",
+ tokenUsage: {
+ last: { inputTokens: 120, cachedInputTokens: 50, outputTokens: 14 },
+ },
+ }))).toEqual([]);
+ const terminal = n.normalizeLine(notify("turn/completed", {
+ threadId: "root",
+ turn: { id: "turn", status: "completed" },
+ }));
+ expect(terminal).toEqual([
+ {
+ kind: "telemetry",
+ name: "token_usage",
+ source: "codex_thread_token_usage_updated",
+ usage: {
+ input: 70,
+ output: 14,
+ cache: 50,
+ },
+ },
+ { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },
+ ]);
+
+ n.registerQuotaReadRequest(99);
+ const quota = n.normalizeLine(JSON.stringify({
+ id: 99,
+ result: {
+ rateLimitsByLimitId: {
+ "gpt-5.3-codex-spark": {
+ limitName: "Spark",
+ planType: "pro",
+ primary: { usedPercent: 82, windowDurationMins: 300, resetsAt: 1_800_000_000 },
+ secondary: { usedPercent: 40, windowDurationMins: 10_080, resetsAt: 1_800_604_800 },
+ },
+ },
+ },
+ }));
+ expect(quota).toHaveLength(1);
+ expect(quota[0]).toMatchObject({
+ kind: "telemetry",
+ name: "rate_limits",
+ quota: {
+ status: "available",
+ planName: "Pro",
+ limits: [
+ { bucket: { product: { id: "codex-spark" }, model: { id: "gpt-5.3-codex-spark" }, window: { kind: "rolling", durationSeconds: 18_000 } }, usedPercent: 82 },
+ { bucket: { product: { id: "codex-spark" }, model: { id: "gpt-5.3-codex-spark" }, window: { kind: "calendar", period: "week" } }, usedPercent: 40 },
+ ],
+ },
+ });
+ });
+
+ it("uses one machine-process quota source generation across Codex sessions", () => {
+ const first = new CodexEventNormalizer();
+ const second = new CodexEventNormalizer();
+ first.registerQuotaReadRequest(1);
+ second.registerQuotaReadRequest(2);
+ const firstFrame = JSON.stringify({
+ id: 1,
+ result: { rateLimits: {
+ primary: { usedPercent: 20, windowDurationMins: 300 },
+ } },
+ });
+ const secondFrame = JSON.stringify({
+ id: 2,
+ result: { rateLimits: {
+ primary: { usedPercent: 20, windowDurationMins: 300 },
+ } },
+ });
+ const firstQuota = first.normalizeLine(firstFrame)[0];
+ const secondQuota = second.normalizeLine(secondFrame)[0];
+ expect(firstQuota).toMatchObject({ kind: "telemetry", name: "rate_limits" });
+ expect(secondQuota).toMatchObject({ kind: "telemetry", name: "rate_limits" });
+ if (firstQuota?.kind !== "telemetry" || firstQuota.name !== "rate_limits") throw new Error("missing quota");
+ if (secondQuota?.kind !== "telemetry" || secondQuota.name !== "rate_limits") throw new Error("missing quota");
+ expect(firstQuota.quota.sourceEpoch).toBe(secondQuota.quota.sourceEpoch);
+ });
+
+ it("merges sparse rate-limit notifications into the complete read snapshot", () => {
+ const n = new CodexEventNormalizer();
+ n.registerQuotaReadRequest(7);
+ expect(n.normalizeLine(JSON.stringify({
+ id: 7,
+ result: {
+ rateLimits: {
+ primary: { usedPercent: 20, windowDurationMins: 300 },
+ secondary: { usedPercent: 40, windowDurationMins: 10_080 },
+ },
+ },
+ }))[0]).toMatchObject({ quota: { limits: [{ usedPercent: 20 }, { usedPercent: 40 }] } });
+
+ const updated = n.normalizeLine(notify("account/rateLimits/updated", {
+ rateLimits: { primary: { usedPercent: 25, windowDurationMins: 300 } },
+ }));
+ expect(updated[0]).toMatchObject({
+ quota: { limits: [{ usedPercent: 25 }, { usedPercent: 40 }] },
+ });
+ });
+
+ it("rotates the opaque source generation and requires a fresh snapshot after account updates", () => {
+ const n = new CodexEventNormalizer();
+ n.registerAccountReadRequest(1);
+ expect(n.normalizeLine(JSON.stringify({
+ id: 1,
+ result: { account: { type: "chatgpt", email: "[email protected]", planType: "pro" } },
+ }))).toEqual([]);
+ n.registerQuotaReadRequest(2);
+ const before = n.normalizeLine(JSON.stringify({
+ id: 2,
+ result: { rateLimits: { primary: { usedPercent: 10, windowDurationMins: 300 } } },
+ }))[0];
+ if (before?.kind !== "telemetry" || before.name !== "rate_limits") throw new Error("missing quota");
+
+ expect(n.normalizeLine(notify("account/updated", { authMode: "chatgpt", planType: "pro" }))).toEqual([]);
+ expect(n.normalizeLine(notify("account/rateLimits/updated", {
+ rateLimits: { primary: { usedPercent: 11, windowDurationMins: 300 } },
+ }))).toEqual([]);
+ n.registerAccountReadRequest(3);
+ n.normalizeLine(JSON.stringify({
+ id: 3,
+ result: { account: { type: "chatgpt", email: "[email protected]", planType: "pro" } },
+ }));
+ n.registerQuotaReadRequest(4);
+ const after = n.normalizeLine(JSON.stringify({
+ id: 4,
+ result: { rateLimits: { primary: { usedPercent: 11, windowDurationMins: 300 } } },
+ }))[0];
+ if (after?.kind !== "telemetry" || after.name !== "rate_limits") throw new Error("missing quota");
+ expect(after.quota.sourceEpoch).not.toBe(before.quota.sourceEpoch);
+ });
});
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
index f0d03c83a..94aa43413 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
@@ -1,6 +1,32 @@
import type { AdapterEvent } from "../../internal/adapter.js";
-import { mapCodexTelemetry } from "./telemetry.js";
+import { mapCodexQuotaSnapshots, mapCodexTelemetry } from "./telemetry.js";
import { tryParseJsonLine } from "../../internal/utils.js";
+import { randomBytes } from "node:crypto";
+
+let codexQuotaSourceEpoch = randomBytes(16).toString("base64url");
+let codexQuotaSourceGeneration = 0;
+let codexAccountFingerprint: string | null = null;
+
+function rotateCodexQuotaSource(): void {
+ codexQuotaSourceEpoch = randomBytes(16).toString("base64url");
+ codexQuotaSourceGeneration += 1;
+ codexAccountFingerprint = null;
+}
+
+function observeCodexAccount(result: any): void {
+ const account = result?.account;
+ const fingerprint = account && typeof account === "object"
+ ? JSON.stringify([
+ account.type ?? "unknown",
+ account.email ?? null,
+ account.planType ?? account.plan_type ?? null,
+ ])
+ : "none";
+ if (codexAccountFingerprint !== null && codexAccountFingerprint !== fingerprint) {
+ rotateCodexQuotaSource();
+ }
+ codexAccountFingerprint = fingerprint;
+}
function normalizeFileChangeInput(item: any): { path?: string } {
const paths: string[] = [];
@@ -23,6 +49,12 @@ function normalizeFileChangeInput(item: any): { path?: string } {
}
export class CodexEventNormalizer {
+ private readonly quotaReadRequestIds = new Set<number>();
+ private readonly accountReadRequestIds = new Set<number>();
+ private readonly rateLimitSnapshots = new Map<string, Record<string, unknown>>();
+ private quotaSnapshotInitialized = false;
+ private quotaSourceGeneration = codexQuotaSourceGeneration;
+ private pendingTurnUsage: AdapterEvent | null = null;
private threadId: string | null = null;
private turnId: string | null = null;
/**
@@ -48,10 +80,76 @@ export class CodexEventNormalizer {
return this.turnId;
}
+ registerQuotaReadRequest(requestId: number): void {
+ this.quotaReadRequestIds.add(requestId);
+ }
+
+ registerAccountReadRequest(requestId: number): void {
+ this.accountReadRequestIds.add(requestId);
+ }
+
+ private syncQuotaSourceGeneration(): void {
+ if (this.quotaSourceGeneration === codexQuotaSourceGeneration) return;
+ this.quotaSourceGeneration = codexQuotaSourceGeneration;
+ this.rateLimitSnapshots.clear();
+ this.quotaSnapshotInitialized = false;
+ }
+
+ private quotaSnapshots(value: any): Array<[string, Record<string, unknown>]> {
+ const byLimitId = value?.rateLimitsByLimitId ?? value?.rate_limits_by_limit_id;
+ if (byLimitId && typeof byLimitId === "object" && !Array.isArray(byLimitId)) {
+ return Object.entries(byLimitId).flatMap(([key, snapshot]) => {
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) return [];
+ return [[key, {
+ ...(snapshot as Record<string, unknown>),
+ limitId: (snapshot as Record<string, unknown>).limitId
+ ?? (snapshot as Record<string, unknown>).limit_id
+ ?? key,
+ }]];
+ });
+ }
+ const snapshot = value?.rateLimits ?? value?.rate_limits ?? value;
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) return [];
+ const record = snapshot as Record<string, unknown>;
+ const key = typeof record.limitId === "string"
+ ? record.limitId
+ : typeof record.limit_id === "string"
+ ? record.limit_id
+ : "codex";
+ return [[key, { ...record, limitId: key }]];
+ }
+
+ private replaceQuotaSnapshots(value: any): AdapterEvent[] {
+ this.syncQuotaSourceGeneration();
+ this.rateLimitSnapshots.clear();
+ for (const [key, snapshot] of this.quotaSnapshots(value)) {
+ this.rateLimitSnapshots.set(key, snapshot);
+ }
+ this.quotaSnapshotInitialized = true;
+ return [mapCodexQuotaSnapshots([...this.rateLimitSnapshots.values()], codexQuotaSourceEpoch)];
+ }
+
+ private mergeQuotaSnapshots(value: any): AdapterEvent[] {
+ this.syncQuotaSourceGeneration();
+ for (const [key, update] of this.quotaSnapshots(value)) {
+ const merged: Record<string, unknown> = {
+ ...(this.rateLimitSnapshots.get(key) ?? {}),
+ limitId: key,
+ };
+ for (const [field, fieldValue] of Object.entries(update)) {
+ if (fieldValue !== undefined && fieldValue !== null) merged[field] = fieldValue;
+ }
+ this.rateLimitSnapshots.set(key, merged);
+ }
+ if (!this.quotaSnapshotInitialized) return [];
+ return [mapCodexQuotaSnapshots([...this.rateLimitSnapshots.values()], codexQuotaSourceEpoch)];
+ }
+
adoptThreadId(threadId: string | null): void {
if (threadId !== this.threadId) {
this.turnId = null;
this.terminalTurn = null;
+ this.pendingTurnUsage = null;
}
this.threadId = threadId;
}
@@ -69,6 +167,27 @@ export class CodexEventNormalizer {
const msg = tryParseJsonLine(line) as any;
if (!msg) return [];
+ if (msg?.id !== undefined && this.accountReadRequestIds.delete(msg.id)) {
+ if (!msg.error) {
+ observeCodexAccount(msg.result);
+ this.syncQuotaSourceGeneration();
+ }
+ return [];
+ }
+
+ if (msg?.id !== undefined && this.quotaReadRequestIds.delete(msg.id)) {
+ this.syncQuotaSourceGeneration();
+ if (msg.error) {
+ return [{
+ kind: "telemetry",
+ name: "rate_limits",
+ source: "codex_account_rate_limits_read",
+ quota: { status: "error", sourceEpoch: codexQuotaSourceEpoch, code: "provider_error", retryable: true },
+ }];
+ }
+ return this.replaceQuotaSnapshots(msg.result ?? {});
+ }
+
if (msg?.error && msg.id !== undefined) {
return [{ kind: "error", message: msg.error?.message ?? "Codex RPC error" }];
}
@@ -102,6 +221,7 @@ export class CodexEventNormalizer {
) return [];
this.turnId = params.turn.id;
this.terminalTurn = null;
+ this.pendingTurnUsage = null;
return [
{
kind: "turn_owner",
@@ -136,16 +256,19 @@ export class CodexEventNormalizer {
case "turn/completed":
if (!this.acceptRootTerminal(params)) return [];
+ const usage = this.pendingTurnUsage;
+ this.pendingTurnUsage = null;
if (params.turn.status === "failed") {
return [
+ ...(usage ? [usage] : []),
{ kind: "error", message: "Codex turn failed" },
{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) },
];
}
if (params.turn.status === "interrupted") {
- return [{ kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
+ return [...(usage ? [usage] : []), { kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
}
- return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
+ return [...(usage ? [usage] : []), { kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
case "error":
if (params?.willRetry === true) {
@@ -153,9 +276,17 @@ export class CodexEventNormalizer {
}
return [{ kind: "error", message: params?.error?.message ?? params?.message ?? "Codex error" }];
- case "thread/tokenUsage/updated":
+ case "thread/tokenUsage/updated": {
+ const usage = mapCodexTelemetry(method, params, codexQuotaSourceEpoch)[0];
+ if (usage) this.pendingTurnUsage = usage;
+ return [];
+ }
case "account/rateLimits/updated":
- return mapCodexTelemetry(method, params);
+ return this.mergeQuotaSnapshots(params);
+ case "account/updated":
+ rotateCodexQuotaSource();
+ this.syncQuotaSourceGeneration();
+ return [];
default:
return [];
diff --git a/src/daemon/agent-driver/src/adapters/codex/telemetry.ts b/src/daemon/agent-driver/src/adapters/codex/telemetry.ts
index b53bb9506..f3f66faac 100644
--- a/src/daemon/agent-driver/src/adapters/codex/telemetry.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/telemetry.ts
@@ -1,48 +1,137 @@
-/**
- * Codex telemetry sidecar — maps Codex's two telemetry notifications into
- * `telemetry` adapter events. Kept separate from the main event flow because it
- * is purely observability (token accounting + rate limits), not turn content.
- */
import type { AdapterEvent } from "../../internal/adapter.js";
+import type { QuotaLimit, QuotaWindowIdentity, TokenMetricDelta } from "../../contract.js";
-export function mapCodexTelemetry(method: string, params: any): AdapterEvent[] {
+function metric(value: unknown): TokenMetricDelta {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+ ? value
+ : null;
+}
+
+function nonCachedInput(input: unknown, cached: unknown): TokenMetricDelta {
+ if (
+ typeof input !== "number"
+ || !Number.isSafeInteger(input)
+ || input < 0
+ || typeof cached !== "number"
+ || !Number.isSafeInteger(cached)
+ || cached < 0
+ || cached > input
+ ) return null;
+ return input - cached;
+}
+
+function canonicalId(value: unknown, fallback: string): string {
+ return typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).length <= 64
+ ? value
+ : fallback;
+}
+
+function mappedPlanName(value: unknown): string | undefined {
+ switch (value) {
+ case "free": return "Free";
+ case "plus": return "Plus";
+ case "pro": return "Pro";
+ case "team": return "Team";
+ case "business": return "Business";
+ case "enterprise": return "Enterprise";
+ case "edu": return "Education";
+ default: return undefined;
+ }
+}
+
+function quotaWindow(minutes: unknown, slot: "primary" | "secondary"): QuotaWindowIdentity | null {
+ if (typeof minutes !== "number" || !Number.isSafeInteger(minutes) || minutes <= 0) return null;
+ if (minutes === 1_440) return { kind: "calendar", period: "day", displayName: "Daily usage limit" };
+ if (minutes === 10_080) return { kind: "calendar", period: "week", displayName: "Weekly usage limit" };
+ if (minutes === 43_200) return { kind: "calendar", period: "month", displayName: "Monthly usage limit" };
+ return {
+ kind: "rolling",
+ durationSeconds: minutes * 60,
+ displayName: slot === "primary" && minutes === 300
+ ? "5 hour usage limit"
+ : `${minutes} minute usage limit`,
+ };
+}
+
+function resetIso(value: unknown): string | undefined {
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
+ const date = new Date(value < 10_000_000_000 ? value * 1_000 : value);
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+ }
+ if (typeof value === "string") {
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+ }
+ return undefined;
+}
+
+export function mapCodexQuotaSnapshots(snapshots: any[], sourceEpoch: string): AdapterEvent {
+ const limits: QuotaLimit[] = [];
+ let planName: string | undefined;
+ for (const snapshot of snapshots) {
+ const limitId = canonicalId(snapshot?.limitId ?? snapshot?.limit_id, "codex");
+ const spark = /spark/i.test(limitId) || /spark/i.test(String(snapshot?.limitName ?? snapshot?.limit_name ?? ""));
+ const product = spark
+ ? { kind: "reported" as const, id: "codex-spark", displayName: "Spark" }
+ : { kind: "reported" as const, id: "codex", displayName: "Codex" };
+ const model = spark
+ ? { kind: "reported" as const, id: "gpt-5.3-codex-spark" }
+ : { kind: "not_applicable" as const };
+ planName ??= mappedPlanName(snapshot?.planType ?? snapshot?.plan_type);
+ for (const slot of ["primary", "secondary"] as const) {
+ const value = snapshot?.[slot];
+ const window = quotaWindow(value?.windowDurationMins ?? value?.window_duration_mins, slot);
+ const usedPercent = value?.usedPercent ?? value?.used_percent;
+ if (!window || typeof usedPercent !== "number" || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) continue;
+ const resetsAt = resetIso(value?.resetsAt ?? value?.resets_at);
+ limits.push({
+ bucket: { limitId, product, model, window },
+ usedPercent,
+ ...(resetsAt ? { resetsAt } : {}),
+ });
+ }
+ }
+ if (limits.length === 0) {
+ return {
+ kind: "telemetry",
+ name: "rate_limits",
+ source: "codex_account_rate_limits_updated",
+ quota: { status: "error", sourceEpoch, code: "invalid_response", retryable: true },
+ };
+ }
+ return {
+ kind: "telemetry",
+ name: "rate_limits",
+ source: "codex_account_rate_limits_updated",
+ quota: {
+ status: "available",
+ sourceEpoch,
+ ...(planName ? { planName } : {}),
+ freshForSeconds: 300,
+ limits,
+ },
+ };
+}
+
+export function mapCodexTelemetry(method: string, params: any, sourceEpoch: string): AdapterEvent[] {
if (method === "thread/tokenUsage/updated") {
- const u = params?.usage ?? params ?? {};
- return [
- {
- kind: "telemetry",
- name: "token_usage",
- source: "codex_thread_token_usage_updated",
- usageKind: "cumulative_session",
- attrs: {
- totalTokens: u.totalTokens ?? u.total_tokens,
- inputTokens: u.inputTokens ?? u.input_tokens,
- cachedInputTokens: u.cachedInputTokens ?? u.cached_input_tokens,
- outputTokens: u.outputTokens ?? u.output_tokens,
- reasoningOutputTokens: u.reasoningOutputTokens ?? u.reasoning_output_tokens,
- modelContextWindow: u.modelContextWindow ?? u.model_context_window,
- cachedInputRatio: u.cachedInputRatio,
- contextUtilization: u.contextUtilization,
- },
+ const u = params?.tokenUsage?.last ?? params?.token_usage?.last;
+ if (!u) return [];
+ const input = u.inputTokens ?? u.input_tokens;
+ const cached = u.cachedInputTokens ?? u.cached_input_tokens;
+ return [{
+ kind: "telemetry",
+ name: "token_usage",
+ source: "codex_thread_token_usage_updated",
+ usage: {
+ input: nonCachedInput(input, cached),
+ output: metric(u.outputTokens ?? u.output_tokens),
+ cache: metric(cached),
},
- ];
+ }];
}
if (method === "account/rateLimits/updated") {
- const r = params ?? {};
- return [
- {
- kind: "telemetry",
- name: "rate_limits",
- source: "codex_account_rate_limits_updated",
- attrs: {
- limitId: r.limitId,
- planType: r.planType,
- usedPercent: r.usedPercent,
- windowDurationMins: r.windowDurationMins,
- resetsAt: r.resetsAt,
- },
- },
- ];
+ return [mapCodexQuotaSnapshots([params?.rateLimits ?? params ?? {}], sourceEpoch)];
}
return [];
}
diff --git a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
index d505e0e7b..b9a3730b1 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
@@ -362,15 +362,6 @@ export class CursorAcpLane implements RuntimeLane {
}
this.activePrompt = null;
this.openToolCalls.clear();
- const usage = record(result.usage);
- if (usage) {
- this.events.emit("runtime_event", {
- kind: "telemetry",
- name: "token_usage",
- source: "cursor.acp",
- attrs: usage,
- } satisfies AdapterEvent);
- }
this.events.emit("runtime_event", {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
index 3eaa794de..cd9d57dce 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -473,14 +473,11 @@ describe("CursorDriver persistent ACP transport", () => {
expect(events).toContainEqual({ kind: "error", message: "Cursor ACP response omitted result" });
await lane.send({ text: "fourth", mode: "idle" });
- respond(process, server.prompts[3]!, { stopReason: "end_turn", usage: { inputTokens: 2, outputTokens: 3 } });
- await settle();
- expect(events).toContainEqual({
- kind: "telemetry",
- name: "token_usage",
- source: "cursor.acp",
- attrs: { inputTokens: 2, outputTokens: 3 },
+ respond(process, server.prompts[3]!, {
+ stopReason: "end_turn",
});
+ await settle();
+ expect(events.filter((event) => event.kind === "telemetry")).toEqual([]);
expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(4);
});
diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
index 797650c03..8e1dd0515 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts
@@ -848,12 +848,26 @@ export class OpenCodeServiceLane implements RuntimeLane {
});
}
const tokens = record(data.tokens);
- if (tokens) {
+ if (tokens && data.finish !== "tool-calls") {
+ const cache = record(tokens.cache);
+ const metric = (value: unknown) =>
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0
+ ? value
+ : null;
+ const cacheParts = [cache?.read, cache?.write]
+ .filter((value): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
+ const cacheTotal = cacheParts.reduce((sum, value) => sum + value, 0);
this.events.emit("runtime_event", {
kind: "telemetry",
name: "token_usage",
source: "opencode.v2",
- attrs: tokens,
+ usage: {
+ input: metric(tokens.input),
+ output: metric(tokens.output),
+ cache: cacheParts.length > 0 && Number.isSafeInteger(cacheTotal)
+ ? cacheTotal
+ : null,
+ },
} satisfies AdapterEvent);
}
break;
diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.ts
index 665fe734d..879dfba65 100644
--- a/src/daemon/agent-driver/src/contract.ts
+++ b/src/daemon/agent-driver/src/contract.ts
@@ -293,14 +293,66 @@ export type AgentTurnResult =
| { readonly outcome: "interrupted"; readonly backendSessionId?: string }
| { readonly outcome: "failed"; readonly backendSessionId?: string; readonly error: AgentDriverError };
-export interface TokenUsage {
- readonly inputTokens?: number;
- readonly cachedInputTokens?: number;
- readonly outputTokens?: number;
- readonly reasoningTokens?: number;
- readonly totalTokens?: number;
+export type TokenMetricDelta = number | null;
+
+export interface TokenUsageDelta {
+ readonly input: TokenMetricDelta;
+ readonly output: TokenMetricDelta;
+ readonly cache: TokenMetricDelta;
+}
+
+export type QuotaErrorCode =
+ | "unavailable"
+ | "unauthorized"
+ | "network"
+ | "provider_error"
+ | "invalid_response";
+
+export type QuotaProductIdentity =
+ | { readonly kind: "reported"; readonly id: string; readonly displayName: string }
+ | { readonly kind: "unknown"; readonly displayName: string };
+
+export type QuotaModelIdentity =
+ | { readonly kind: "reported"; readonly id: string }
+ | { readonly kind: "not_applicable" }
+ | { readonly kind: "unknown" };
+
+export type QuotaWindowIdentity =
+ | { readonly kind: "rolling"; readonly durationSeconds: number; readonly displayName: string }
+ | { readonly kind: "calendar"; readonly period: "day" | "week" | "month"; readonly displayName: string }
+ | {
+ readonly kind: "provider_defined";
+ readonly id: string;
+ readonly durationSeconds?: number;
+ readonly displayName: string;
+ };
+
+export interface QuotaLimit {
+ readonly bucket: {
+ readonly limitId: string;
+ readonly product: QuotaProductIdentity;
+ readonly model: QuotaModelIdentity;
+ readonly window: QuotaWindowIdentity;
+ };
+ readonly usedPercent: number;
+ readonly resetsAt?: string;
}
+export type ProviderQuotaObservation =
+ | {
+ readonly status: "available";
+ readonly sourceEpoch: string;
+ readonly planName?: string;
+ readonly freshForSeconds: number;
+ readonly limits: readonly QuotaLimit[];
+ }
+ | {
+ readonly status: "error";
+ readonly sourceEpoch: string;
+ readonly code: QuotaErrorCode;
+ readonly retryable: boolean;
+ };
+
export type CoreAgentEventPayload =
| { readonly type: "session_started"; readonly backendSessionId: string }
| {
@@ -377,14 +429,13 @@ export type CoreAgentEventPayload =
readonly type: "token_usage";
readonly turnId?: string;
readonly source: string;
- readonly usage: TokenUsage;
- readonly details: JsonObject;
+ readonly usage: TokenUsageDelta;
}
| {
readonly type: "rate_limits";
readonly turnId?: string;
readonly source: string;
- readonly details: JsonObject;
+ readonly quota: ProviderQuotaObservation;
}
| {
readonly type: "turn_completed";
diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.ts
index 8a3401b17..11a989e91 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts
@@ -1114,7 +1114,12 @@ describe("closed physical-lane tombstone", () => {
kind: "telemetry",
name: "rate_limits",
source: "tail-telemetry",
- attrs: { remaining: 1 },
+ quota: {
+ status: "error",
+ sourceEpoch: "AAAAAAAAAAAAAAAAAAAAAA",
+ code: "unavailable",
+ retryable: true,
+ },
});
expect(session.snapshot().activeTurn).toBeUndefined();
@@ -1357,7 +1362,17 @@ describe("backend-owned delivery behavior", () => {
await emit(driver, { kind: "internal_progress", source: "pi", itemType: "working", payloadBytes: 12 });
await emit(driver, { kind: "runtime_diagnostic", severity: "notice", source: "pi", message: "heads up" });
await emit(driver, { kind: "telemetry", name: "token_usage", source: "pi", attrs: circular } as never);
- await emit(driver, { kind: "telemetry", name: "rate_limits", source: "pi", attrs: { remaining: 1 } });
+ await emit(driver, {
+ kind: "telemetry",
+ name: "rate_limits",
+ source: "pi",
+ quota: {
+ status: "error",
+ sourceEpoch: "AAAAAAAAAAAAAAAAAAAAAA",
+ code: "unavailable",
+ retryable: false,
+ },
+ });
const events = await take(iterator as never, 7);
expect(events.map((event) => event.type)).toEqual([
"command_accepted",
diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.ts
index 5af7facc0..4ac2dd45a 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.ts
@@ -13,7 +13,6 @@ import type {
ExtensionResult,
HostCleanupResult,
InterruptResult,
- JsonObject,
JsonValue,
PreparedExecutionResource,
StopInput,
@@ -833,11 +832,10 @@ implements AgentSession<Specs, Id> {
}
return;
case "telemetry": {
- const details = jsonValue(event.attrs) as JsonObject;
if (event.name === "token_usage") {
- this.emit({ type: "token_usage", turnId, source: event.source, usage: {}, details });
+ this.emit({ type: "token_usage", turnId, source: event.source, usage: event.usage });
} else {
- this.emit({ type: "rate_limits", turnId, source: event.source, details });
+ this.emit({ type: "rate_limits", turnId, source: event.source, quota: event.quota });
}
return;
}
diff --git a/src/daemon/agent-driver/src/host.ts b/src/daemon/agent-driver/src/host.ts
index 628758272..6d13822c2 100644
--- a/src/daemon/agent-driver/src/host.ts
+++ b/src/daemon/agent-driver/src/host.ts
@@ -2,6 +2,7 @@
export type * from "./public-contract.js";
export { createAgentDriverSdk as createBuiltinAgentDriverSdk } from "./sdk.js";
export { createDefaultAgentDriverHost } from "./host/default-host.js";
+export { readBuiltinProviderQuota } from "./provider-quota.js";
export { scrubDriverErrorMessage as scrubAgentDriverDiagnosticText } from "./internal/errors.js";
export type {
AgentDriverHost,
diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.ts
index 4b61ffe8b..a41139926 100644
--- a/src/daemon/agent-driver/src/internal/adapter.ts
+++ b/src/daemon/agent-driver/src/internal/adapter.ts
@@ -11,6 +11,7 @@ import type {
RuntimeSettingsUpdate,
RuntimeSettingsUpdateResult,
} from "../contract.js";
+import type { ProviderQuotaObservation, TokenUsageDelta } from "../contract.js";
export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | OpenCodeConfig | PiConfig;
@@ -73,7 +74,8 @@ export type AdapterEvent =
| { kind: "turn_owner"; receipt: string; nativeTurnId?: string }
| { kind: "turn_end"; sessionId?: string; turnOwner?: string }
| { kind: "error"; message: string }
- | { kind: "telemetry"; name: "token_usage" | "rate_limits"; source: string; usageKind?: string; attrs: Record<string, unknown> };
+ | { kind: "telemetry"; name: "token_usage"; source: string; usage: TokenUsageDelta }
+ | { kind: "telemetry"; name: "rate_limits"; source: string; quota: ProviderQuotaObservation };
export interface LaneStartInput {
readonly text: string;
diff --git a/src/daemon/agent-driver/src/provider-quota.test.ts b/src/daemon/agent-driver/src/provider-quota.test.ts
new file mode 100644
index 000000000..551be0580
--- /dev/null
+++ b/src/daemon/agent-driver/src/provider-quota.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest";
+import { readBuiltinProviderQuota } from "./provider-quota.js";
+
+describe("readBuiltinProviderQuota", () => {
+ it("maps Claude OAuth usage without exposing credentials in the observation", async () => {
+ const fetchUsage = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer local-secret-token")
+ return Response.json({
+ five_hour: { utilization: 82, resets_at: "2026-08-29T05:00:00Z" },
+ seven_day: { utilization: 41, resets_at: "2026-09-01T00:00:00Z" },
+ seven_day_sonnet: { utilization: 12, resets_at: "2026-09-01T00:00:00Z" },
+ })
+ })
+ const result = await readBuiltinProviderQuota("claude", {
+ platform: "linux",
+ env: {},
+ readCredentialsFile: async () => JSON.stringify({
+ claudeAiOauth: { accessToken: "local-secret-token", subscriptionType: "max" },
+ }),
+ fetchUsage: fetchUsage as typeof fetch,
+ })
+ expect(result).toMatchObject({
+ status: "available",
+ planName: "Max",
+ freshForSeconds: 300,
+ limits: [
+ { bucket: { limitId: "five_hour", window: { durationSeconds: 18_000 } }, usedPercent: 82 },
+ { bucket: { limitId: "seven_day", window: { durationSeconds: 604_800 } }, usedPercent: 41 },
+ { bucket: { limitId: "seven_day_sonnet", model: { id: "claude-sonnet" } }, usedPercent: 12 },
+ ],
+ })
+ expect(result?.sourceEpoch).toMatch(/^[A-Za-z0-9_-]{22}$/)
+ expect(JSON.stringify(result)).not.toContain("local-secret-token")
+ })
+
+ it("returns unsupported for custom Claude providers and non-quota backends", async () => {
+ const readCredentialsFile = vi.fn(async () => "")
+ await expect(readBuiltinProviderQuota("claude", {
+ platform: "linux",
+ env: { ANTHROPIC_API_KEY: "custom" },
+ readCredentialsFile,
+ })).resolves.toBeNull()
+ await expect(readBuiltinProviderQuota("cursor")).resolves.toBeNull()
+ expect(readCredentialsFile).not.toHaveBeenCalled()
+ })
+
+ it("changes the opaque source epoch when the local OAuth source changes", async () => {
+ let token = "first-token"
+ const options = {
+ platform: "linux" as const,
+ env: {},
+ readCredentialsFile: async () => JSON.stringify({ claudeAiOauth: { accessToken: token } }),
+ fetchUsage: (async () => Response.json({
+ five_hour: { utilization: 1, resets_at: "2026-08-29T05:00:00Z" },
+ })) as typeof fetch,
+ }
+ const first = await readBuiltinProviderQuota("claude", options)
+ token = "second-token"
+ const second = await readBuiltinProviderQuota("claude", options)
+ expect(first?.sourceEpoch).not.toBe(second?.sourceEpoch)
+ })
+})
diff --git a/src/daemon/agent-driver/src/provider-quota.ts b/src/daemon/agent-driver/src/provider-quota.ts
new file mode 100644
index 000000000..48110ad8d
--- /dev/null
+++ b/src/daemon/agent-driver/src/provider-quota.ts
@@ -0,0 +1,165 @@
+import { execFile } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { randomBytes } from "node:crypto";
+import type { BuiltinBackendId, ProviderQuotaObservation, QuotaLimit } from "./contract.js";
+
+const execFileAsync = promisify(execFile);
+let claudeAccessToken: string | null = null;
+let claudeSourceEpoch = randomBytes(16).toString("base64url");
+
+type ClaudeCredentials = {
+ claudeAiOauth?: {
+ accessToken?: unknown;
+ subscriptionType?: unknown;
+ };
+};
+
+type QuotaReaderOptions = {
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ home?: string;
+ readCredentialsFile?: (path: string) => Promise<string>;
+ readKeychain?: () => Promise<string>;
+ fetchUsage?: typeof fetch;
+};
+
+function parseCredentials(value: string): ClaudeCredentials | null {
+ try {
+ const parsed = JSON.parse(value) as unknown;
+ return parsed && typeof parsed === "object" ? parsed as ClaudeCredentials : null;
+ } catch {
+ return null;
+ }
+}
+
+async function claudeCredentials(options: QuotaReaderOptions): Promise<ClaudeCredentials | null> {
+ const platform = options.platform ?? process.platform;
+ if (platform === "darwin") {
+ try {
+ const value = options.readKeychain
+ ? await options.readKeychain()
+ : (await execFileAsync("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], {
+ timeout: 3_000,
+ maxBuffer: 256 * 1024,
+ })).stdout;
+ const parsed = parseCredentials(value.trim());
+ if (parsed) return parsed;
+ } catch { }
+ }
+ const env = options.env ?? process.env;
+ const root = env.CLAUDE_CONFIG_DIR || join(options.home ?? homedir(), ".claude");
+ try {
+ const value = options.readCredentialsFile
+ ? await options.readCredentialsFile(join(root, ".credentials.json"))
+ : await readFile(join(root, ".credentials.json"), "utf8");
+ return parseCredentials(value);
+ } catch {
+ return null;
+ }
+}
+
+function mappedPlanName(value: unknown): string | undefined {
+ switch (value) {
+ case "free": return "Free";
+ case "pro": return "Pro";
+ case "max": return "Max";
+ case "team": return "Team";
+ case "enterprise": return "Enterprise";
+ default: return undefined;
+ }
+}
+
+function resetIso(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+}
+
+function claudeLimit(key: string, value: unknown): QuotaLimit | null {
+ if (!value || typeof value !== "object") return null;
+ const row = value as Record<string, unknown>;
+ if (typeof row.utilization !== "number" || !Number.isFinite(row.utilization) || row.utilization < 0 || row.utilization > 100) return null;
+ const model = key.includes("sonnet")
+ ? { kind: "reported" as const, id: "claude-sonnet" }
+ : key.includes("opus")
+ ? { kind: "reported" as const, id: "claude-opus" }
+ : { kind: "not_applicable" as const };
+ const window = key === "five_hour"
+ ? { kind: "rolling" as const, durationSeconds: 18_000, displayName: "5 hour usage limit" }
+ : { kind: "rolling" as const, durationSeconds: 604_800, displayName: "7 day usage limit" };
+ const resetsAt = resetIso(row.resets_at ?? row.resetsAt);
+ return {
+ bucket: {
+ limitId: key,
+ product: { kind: "reported", id: "claude", displayName: "Claude" },
+ model,
+ window,
+ },
+ usedPercent: row.utilization,
+ ...(resetsAt ? { resetsAt } : {}),
+ };
+}
+
+async function readClaudeQuota(options: QuotaReaderOptions): Promise<ProviderQuotaObservation | null> {
+ const env = options.env ?? process.env;
+ if (env.ANTHROPIC_API_KEY || env.ANTHROPIC_BASE_URL) return null;
+ const credentials = await claudeCredentials(options);
+ const token = credentials?.claudeAiOauth?.accessToken;
+ if (typeof token !== "string" || token.length === 0) return null;
+ if (claudeAccessToken !== token) {
+ claudeAccessToken = token;
+ claudeSourceEpoch = randomBytes(16).toString("base64url");
+ }
+ let response: Response;
+ try {
+ response = await (options.fetchUsage ?? fetch)("https://api.anthropic.com/api/oauth/usage", {
+ headers: {
+ authorization: `Bearer ${token}`,
+ "anthropic-beta": "oauth-2025-04-20",
+ },
+ signal: AbortSignal.timeout(5_000),
+ });
+ } catch {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "network", retryable: true };
+ }
+ if (response.status === 401 || response.status === 403) {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "unauthorized", retryable: false };
+ }
+ if (!response.ok) {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "provider_error", retryable: response.status === 429 || response.status >= 500 };
+ }
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
+ }
+ if (!body || typeof body !== "object") {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
+ }
+ const record = body as Record<string, unknown>;
+ const limits = ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_opus"]
+ .map((key) => claudeLimit(key, record[key]))
+ .filter((limit): limit is QuotaLimit => limit !== null);
+ if (limits.length === 0) {
+ return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
+ }
+ const planName = mappedPlanName(credentials?.claudeAiOauth?.subscriptionType);
+ return {
+ status: "available",
+ sourceEpoch: claudeSourceEpoch,
+ ...(planName ? { planName } : {}),
+ freshForSeconds: 300,
+ limits,
+ };
+}
+
+export async function readBuiltinProviderQuota(
+ backend: BuiltinBackendId,
+ options: QuotaReaderOptions = {},
+): Promise<ProviderQuotaObservation | null> {
+ return backend === "claude" ? readClaudeQuota(options) : null;
+}
diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.ts
index 9d250f5f1..885f9bfba 100644
--- a/src/daemon/agent-driver/src/public-contract.ts
+++ b/src/daemon/agent-driver/src/public-contract.ts
@@ -7,7 +7,9 @@ export type {
OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,
FixedCapabilities, ConfigOf, CapabilitiesOf, ExtensionsOf, ExtraEventOf, AgentInstructions, AgentLaunchContext, AgentMessage,
AgentDriverError, OpenSessionResult, DeliveryReceipt, InterruptResult, StopInput, StopReceipt, HostCleanupResult,
- AgentSessionResult, AgentTurnResult, TokenUsage, CoreAgentEventPayload, AgentEventEnvelope, AgentEvent,
+ AgentSessionResult, AgentTurnResult, TokenMetricDelta, TokenUsageDelta, QuotaErrorCode,
+ QuotaProductIdentity, QuotaModelIdentity, QuotaWindowIdentity, QuotaLimit,
+ ProviderQuotaObservation, CoreAgentEventPayload, AgentEventEnvelope, AgentEvent,
AgentSessionSnapshot, AgentEventStream, ExtensionNames, ExtensionInput, ExtensionOutput, ExtensionResult,
AgentSession, ProbeInput, BackendProbe, OpenSessionInput,
AgentDriverSdk,
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index a05ab5b36..7e632cf17 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -285,6 +285,8 @@ function daemonFakeSession(options: {
} else if (runtime.kind === "text") {
emit({ type: "assistant_message_completed", turnId: "daemon-test-turn", text: runtime.text ?? "", truncated: false } as never);
}
+ } else if (event === "agent_event") {
+ emit(args[0] as never);
} else if (event === "exit") {
const result: AgentSessionResult = { outcome: "stopped", requested: true, exitCode: null, signal: null, cleanup: { status: "released" } };
ended = true;
@@ -315,6 +317,112 @@ function factory(sockets: FakeSocket[]) {
}
describe("createDaemon", () => {
+ it("commits terminal usage before idle and attaches the current backend quota", async () => {
+ const sockets: FakeSocket[] = [];
+ const sessions: DaemonFakeSession[] = [];
+ const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-provider-telemetry-"));
+ startupSweepDirs.push(workingDirectoryBase);
+ mkdirSync(join(workingDirectoryBase, "bot_1"), { recursive: true });
+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {
+ const url = String(input);
+ if (url.includes("/enroll-agent")) return Response.json({ runnerKey: "runner_test" });
+ if (url.includes("/daemon/bots")) {
+ return Response.json({ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }] });
+ }
+ return Response.json({ attempted: 0 });
+ }));
+ const daemon = await createDaemon({
+ machineKey: "cmk_telemetry",
+ serverUrl: "http://server.invalid",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as never,
+ runtimeReport: [{ id: "codex" }],
+ driverFor: () => fullFakeDriver("codex"),
+ sessionFactory: () => {
+ const session = daemonFakeSession();
+ sessions.push(session);
+ return session;
+ },
+ capabilities: [],
+ workingDirectoryBase,
+ });
+
+ try {
+ sockets[0]!.emit("open");
+ sockets[0]!.emit("message", JSON.stringify({
+ type: "agent:wake",
+ agentId: "bot_1",
+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "launch_1",
+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },
+ }));
+ await vi.waitFor(() => expect(sessions).toHaveLength(1));
+ await sessions[0]!.fire("agent_event", {
+ type: "token_usage",
+ turnId: "daemon-test-turn",
+ source: "codex_thread_token_usage_updated",
+ usage: {
+ input: 20,
+ output: 5,
+ cache: null,
+ },
+ });
+ await sessions[0]!.fire("agent_event", {
+ type: "rate_limits",
+ source: "codex_account_rate_limits_updated",
+ quota: {
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ freshForSeconds: 300,
+ limits: [{
+ bucket: {
+ limitId: "codex",
+ product: { kind: "reported", id: "codex", displayName: "Codex" },
+ model: { kind: "not_applicable" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ },
+ usedPercent: 30,
+ }],
+ },
+ });
+ await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });
+
+ const frames = () => sockets[0]!.sent.map((frame) => JSON.parse(frame) as any);
+ await vi.waitFor(() => expect(frames().some((frame) =>
+ frame.type === "agent_activity"
+ && frame.agentId === "bot_1"
+ && frame.state === "idle"
+ && frame.dailyUsage?.[0]?.metrics.input === 20
+ && frame.quota?.observation?.limits?.[0]?.usedPercent === 30
+ )).toBe(true));
+ expect(existsSync(join(workingDirectoryBase, ".telemetry", "daily-token-usage.json"))).toBe(true);
+
+ const readyBefore = frames().filter((frame) => frame.type === "ready").length;
+ await sessions[0]!.fire("agent_event", {
+ type: "rate_limits",
+ source: "codex_account_rate_limits_updated",
+ quota: {
+ status: "error",
+ sourceEpoch: "B".repeat(22),
+ code: "unauthorized",
+ retryable: false,
+ },
+ });
+ await vi.waitFor(() => expect(frames().filter((frame) => frame.type === "ready")).toHaveLength(readyBefore + 1));
+ expect(frames().filter((frame) => frame.type === "ready").at(-1)?.providerQuotas).toEqual([{
+ agentBackendId: "codex",
+ observation: {
+ status: "error",
+ sourceEpoch: "B".repeat(22),
+ code: "unauthorized",
+ retryable: false,
+ },
+ }]);
+ } finally {
+ await daemon.stop();
+ }
+ });
+
it("opens the builtin session factory and reports host preparation failures", async () => {
const dir = mkdtempSync(join(tmpdir(), "daemon-builtin-session-"));
try {
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 9f7d3adf3..8252ec412 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -41,7 +41,9 @@ import type { RuntimeConfig } from "../runtimeConfig.js";
import type { HostCommand } from "../server/contract.js";
import { formatHandle } from "@alook/shared/lib/discriminator";
import type { DiagnosticCollectCommand } from "@alook/shared";
-import { createBuiltinAgentDriverSdk } from "@alook/agent-driver/host";
+import { createBuiltinAgentDriverSdk, readBuiltinProviderQuota } from "@alook/agent-driver/host";
+import type { BuiltinBackendId, ProviderQuotaObservation } from "@alook/agent-driver";
+import type { HostAgentActivity, ProviderQuotaSnapshot } from "@alook/shared";
import {
createDiagnosticsCommandListener,
type DiagnosticFailureReport,
@@ -57,6 +59,7 @@ import {
DaemonSelfSleepScheduler,
type DaemonSelfSleepClock,
} from "./daemonSelfSleep.js";
+import { DailyTokenUsageStore } from "../telemetry/index.js";
// Cold-start warmup backoff schedule (ms).
const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;
@@ -325,6 +328,7 @@ export interface CreateDaemonOptions {
reportDiagnosticFailure?: (failure: DiagnosticFailureReport) => void | Promise<void>;
/** Injectable daemon-local reminder clock; tests only, defaults to Node timers. */
messageReminderClock?: Pick<MessageReminderSchedulerOptions, "now" | "setTimer" | "clearTimer">;
+ providerQuotaReader?: (backend: BuiltinBackendId) => Promise<ProviderQuotaObservation | null>;
/** Called after one continuous 15-day window with no new message and no working agent. */
onSelfSleep?: () => void;
/** Injectable self-sleep clock; tests only, defaults to Node timers. */
@@ -391,6 +395,29 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
const fallbackBase = (process.env.ALOOK_PROJECT_ROOT || `${homedir()}/.alook`) + "/daemon";
const workingDirectoryBase = opts.workingDirectoryBase ?? fallbackBase;
const workdirFor = (agentId: string) => `${workingDirectoryBase}/${agentId}`;
+ const dailyTokenUsage = new DailyTokenUsageStore(workingDirectoryBase);
+ const providerQuotaReader = opts.providerQuotaReader
+ ?? (opts.sessionFactory ? async () => null : readBuiltinProviderQuota);
+ const providerQuotaByBackend = new Map<"claude" | "codex", ProviderQuotaSnapshot>();
+ let requestReadyQuotaResend = (): void => {};
+ const recordProviderQuota = (
+ backendId: "claude" | "codex",
+ quota: ProviderQuotaObservation,
+ ): void => {
+ const previous = providerQuotaByBackend.get(backendId);
+ if (
+ previous?.observation.status === "available"
+ && quota.status === "error"
+ && previous.observation.sourceEpoch === quota.sourceEpoch
+ ) return;
+ providerQuotaByBackend.set(backendId, {
+ agentBackendId: backendId,
+ observation: structuredClone(quota) as ProviderQuotaSnapshot["observation"],
+ });
+ if (previous && previous.observation.sourceEpoch !== quota.sourceEpoch) {
+ requestReadyQuotaResend();
+ }
+ };
void sweepTimelineHistory(workingDirectoryBase).catch(() => {
log.warn("timeline startup sweep failed");
});
@@ -415,6 +442,30 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// Populated after `manager` is constructed below. Producer B reads
// `auditContext(agentId)` off it inside `onProxyRequest`.
let managerRef: AgentProcessManager | null = null;
+ const providerQuotaSnapshots = (): ProviderQuotaSnapshot[] =>
+ [...providerQuotaByBackend.values()].map((snapshot) => structuredClone(snapshot));
+ const activityPayload = async (
+ info: { agentId: string; state: HostAgentActivity["state"] },
+ ): Promise<HostAgentActivity> => {
+ if (info.state !== "idle") return info;
+ const backendId = managerRef?.agentBackendId(info.agentId);
+ if (backendId === "claude") {
+ const observed = await providerQuotaReader("claude");
+ if (observed) recordProviderQuota("claude", observed);
+ }
+ const quota = backendId === "claude" || backendId === "codex"
+ ? providerQuotaByBackend.get(backendId)
+ : undefined;
+ const dailyUsage = await dailyTokenUsage.snapshots(info.agentId);
+ return {
+ ...info,
+ ...(dailyUsage.length > 0 ? { dailyUsage } : {}),
+ ...(quota ? { quota: structuredClone(quota) } : {}),
+ };
+ };
+ let reportAgentActivity = (info: { agentId: string; state: HostAgentActivity["state"] }): void => {
+ void channelRef?.reportAgentActivity?.(info);
+ };
let reminderSchedulerRef: MessageReminderScheduler | null = null;
const selfSleepScheduler = opts.onSelfSleep
? new DaemonSelfSleepScheduler({
@@ -538,7 +589,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
// idle agent. Idempotent on the ws-do side (rewrites the same preset).
function reassertAgentActivity(agentId: string): void {
const state = managerRef?.agentActivity(agentId);
- if (state) channel.reportAgentActivity?.({ agentId, state });
+ if (state) reportAgentActivity({ agentId, state });
}
function startTypingHeartbeat(agentId: string): void {
stopTypingHeartbeat(agentId);
@@ -747,6 +798,21 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
logger: log.child("ws"),
});
channelRef = channel;
+ const activityReportTails = new Map<string, Promise<void>>();
+ reportAgentActivity = (info): void => {
+ const prior = activityReportTails.get(info.agentId) ?? Promise.resolve();
+ const next = prior
+ .then(async () => {
+ await channel.reportAgentActivity(await activityPayload(info));
+ })
+ .catch(() => {
+ log.warn("agent activity telemetry report failed", { agentId: info.agentId, state: info.state });
+ });
+ activityReportTails.set(info.agentId, next);
+ void next.finally(() => {
+ if (activityReportTails.get(info.agentId) === next) activityReportTails.delete(info.agentId);
+ });
+ };
function restorePendingIdleResetEvents(agentId: string): void {
for (const pending of timeline.pendingIdleResetEvents(agentId)) {
@@ -898,7 +964,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
onAgentSession: (info) => void channel.reportAgentSession(info),
onAgentActivity: (info) => {
selfSleepScheduler?.observeAgentActivity(info.agentId, info.state === "running");
- void channel.reportAgentActivity?.(info);
+ reportAgentActivity(info);
// Bot typing indicator (DM-only) — install / tear down the daemon-metered
// heartbeat off the derived FSM activity, so the pill lifecycle exactly
// mirrors "is this bot actively working."
@@ -916,6 +982,15 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
emitTypingStopsAndClear(info.agentId);
}
},
+ onTokenUsage: ({ agentId, usage }) => {
+ void dailyTokenUsage.record(agentId, usage).catch(() => {
+ log.warn("daily token usage persistence failed", { agentId });
+ });
+ },
+ onProviderQuota: ({ backendId, quota }) => {
+ if (backendId !== "claude" && backendId !== "codex") return;
+ recordProviderQuota(backendId, quota);
+ },
// Bot audit log — Producer A (runtime thinking + non-Bash tool_call).
// Bash suppression + thinking truncation happen inside managerRuntime.
onBotAuditEvent: (agentId, event, context) => emitBotAuditEvent(agentId, event, context),
@@ -987,6 +1062,18 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
arch: opts.arch,
osRelease: opts.osRelease,
daemonVersion: opts.daemonVersion,
+ providerQuotas: providerQuotaSnapshots,
+ resyncActivities: async () => {
+ const activities = await Promise.all(
+ manager.liveAgentActivities().map((info) => activityPayload(info)),
+ );
+ // Telemetry enrichment can await local I/O (and Claude quota refresh).
+ // Do not let an activity snapshot captured at connect overwrite a newer
+ // live state transition that was sent while that work was in flight.
+ return activities.filter(
+ (activity) => manager.agentActivity(activity.agentId) === activity.state,
+ );
+ },
typingTracker,
logger: log.child("router"),
// onBeforeAgent gate — reject unknown bots BEFORE enroll to keep the
@@ -1009,6 +1096,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
await enrollAgent(agentId);
},
});
+ requestReadyQuotaResend = () => {
+ if (router) channel.sendReady?.(router.buildReady());
+ };
// Machine lifecycle commands are claimed before diagnostics, bot observers,
// and AgentRouter; updates never enter agent lifecycle routing.
@@ -1049,6 +1139,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
void resyncPendingDiagnostics();
});
+ if (opts.runtimeReport.some((runtime) => runtime.id === "claude")) {
+ const observed = await providerQuotaReader("claude");
+ if (observed) recordProviderQuota("claude", observed);
+ }
channel.connect();
await router!.start();
selfSleepScheduler?.start();
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index bdc1bf9ae..d282ff211 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -18,7 +18,8 @@
* `agent:wake`/`agent:stop` outcomes, and supplies a resync snapshot so the
* server recovers this host's state after a dropped control connection.
*/
-import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame, AgentId } from "../server/contract.js";
+import type { HostCommand, HostControlChannel, HostReady, HostReadyRuntime, UnreadNotice, AgentSessionReport, SessionErrorFrame, AgentId, HostAgentActivity } from "../server/contract.js";
+import type { ProviderQuotaSnapshot } from "@alook/shared";
import { CONTROL_HEARTBEAT_CAPABILITY } from "../server/contract.js";
import type { AgentProcessManager } from "./managerRuntime.js";
import type { TypingScopeTracker } from "./typingScopeTracker.js";
@@ -83,6 +84,8 @@ export interface AgentRouterOpts {
arch?: string;
osRelease?: string;
daemonVersion?: string;
+ providerQuotas?: () => ProviderQuotaSnapshot[];
+ resyncActivities?: () => HostAgentActivity[] | Promise<HostAgentActivity[]>;
/**
* Called before registering/delivering to an agent. The daemon uses this to
* enroll the agent (fetch its runner key) so the credential proxy can swap
@@ -211,7 +214,9 @@ export class AgentRouter {
this.opts.channel.onResync?.(() => ({
ready: this.buildReady(),
sessions: this.opts.manager.liveSessionReports() as AgentSessionReport[],
- activities: this.opts.manager.liveAgentActivities(),
+ activities: this.opts.resyncActivities
+ ? this.opts.resyncActivities()
+ : this.opts.manager.liveAgentActivities(),
}));
await this.opts.channel.reportReady(this.buildReady());
}
@@ -230,6 +235,7 @@ export class AgentRouter {
arch: this.opts.arch,
osRelease: this.opts.osRelease,
daemonVersion: this.opts.daemonVersion,
+ ...(this.opts.providerQuotas ? { providerQuotas: this.opts.providerQuotas() } : {}),
};
}
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index e3b27dac6..74f1715af 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -23,6 +23,8 @@ import type {
BuiltinBackendSpecs,
DeliveryReceipt,
RuntimeSettingsUpdateResult,
+ ProviderQuotaObservation,
+ TokenUsageDelta,
} from "@alook/agent-driver";
import type { HostLaunchContext } from "./hostContext.js";
import { runtimeModelName, type RuntimeConfig } from "../runtimeConfig.js";
@@ -226,6 +228,8 @@ export interface ManagerRuntimeOpts {
now?: () => number;
onAgentSession?: (info: { agentId: string; sessionId: string; launchId: string }) => void;
onAgentActivity?: (info: { agentId: string; state: AgentActivityState }) => void;
+ onTokenUsage?: (info: { agentId: string; backendId: BuiltinBackendId; usage: TokenUsageDelta }) => void;
+ onProviderQuota?: (info: { agentId: string; backendId: BuiltinBackendId; quota: ProviderQuotaObservation }) => void;
onBotAuditEvent?: (
agentId: string,
event:
@@ -447,6 +451,7 @@ export class AgentProcessManager {
private readonly resumeSessions = new Map<string, string>();
private readonly launchIds = new Map<string, string>();
private readonly liveSessions = new Map<string, string>();
+ private readonly liveBackendIds = new Map<string, BuiltinBackendId>();
private readonly activeSpawnState = new Map<string, ActiveSpawnState>();
private readonly publishedAgentActivity = new Map<string, AgentActivityState>();
private readonly traceProcessNonce = randomUUID();
@@ -465,6 +470,8 @@ export class AgentProcessManager {
| "credentialProxy"
| "onAgentSession"
| "onAgentActivity"
+ | "onTokenUsage"
+ | "onProviderQuota"
| "onBotAuditEvent"
| "onAgentLocallyStopped"
| "onRuntimeRawLine"
@@ -483,6 +490,8 @@ export class AgentProcessManager {
| "credentialProxy"
| "onAgentSession"
| "onAgentActivity"
+ | "onTokenUsage"
+ | "onProviderQuota"
| "onBotAuditEvent"
| "onAgentLocallyStopped"
| "onRuntimeRawLine"
@@ -874,6 +883,9 @@ export class AgentProcessManager {
const agent = this.state.agents[agentId];
return agent ? this.deriveActivity(agent) : null;
}
+ agentBackendId(agentId: string): BuiltinBackendId | null {
+ return this.liveBackendIds.get(agentId) ?? null;
+ }
statusProjection(nowMs: number): Array<{
agentId: string;
status: AgentStatus;
@@ -1502,6 +1514,7 @@ export class AgentProcessManager {
if (!first) throw new Error(`AgentProcessManager: spawn for ${agentId} has no command`);
const prompt = this.withFooter(first.text);
const driver = this.opts.driverFor(agentId, this.runtimeConfigs.get(agentId));
+ this.liveBackendIds.set(agentId, driver.id);
const base = this.opts.baseContextFor(agentId);
const configuredRuntime = this.runtimeConfigs.get(agentId) ?? base.config?.runtimeConfig;
this.log.info("spawning agent", {
@@ -1642,6 +1655,7 @@ export class AgentProcessManager {
state.pendingDeliverySpans.clear();
if (state.session && this.sessions.get(agentId) === state.session) this.sessions.delete(agentId);
this.liveSessions.delete(agentId);
+ if (this.activeSpawnState.get(agentId) === state) this.liveBackendIds.delete(agentId);
if (this.activeSpawnState.get(agentId) === state) {
this.appliedRuntimeConfigs.delete(agentId);
this.activeSpawnState.delete(agentId);
@@ -1955,6 +1969,12 @@ export class AgentProcessManager {
runtime: runtimeId,
});
}
+ if (event.type === "token_usage") {
+ this.opts.onTokenUsage?.({ agentId, backendId: runtimeId, usage: event.usage });
+ }
+ if (event.type === "rate_limits") {
+ this.opts.onProviderQuota?.({ agentId, backendId: runtimeId, quota: event.quota });
+ }
if (event.type === "turn_started") {
const timelineTurnOwner: TimelineTurnOwner = {
sessionInstanceId: event.sessionInstanceId,
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 2d679028e..be19bd5b2 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -71,6 +71,7 @@ export type {
HostControlChannel,
AgentSessionReport,
AgentActivityState,
+ HostAgentActivity,
HostBotAuditEventFrame,
BotAuditEventPayload,
WebSocketLike,
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index 74a00aa83..d2df9d206 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -129,6 +129,79 @@ describe("WsControlChannel — resync on (re)connect", () => {
expect(readyIdx).toBeLessThan(activityIdx);
});
+ it("replays asynchronously enriched usage and quota after sending ready immediately", async () => {
+ const { ch, sockets } = makeChannel();
+ let resolveActivities!: (activities: Array<{
+ agentId: string;
+ state: "idle";
+ dailyUsage: Array<{
+ botId: string;
+ day: string;
+ metrics: {
+ input: number;
+ output: number;
+ cache: null;
+ };
+ }>;
+ quota: {
+ agentBackendId: "codex";
+ observation: {
+ status: "error";
+ sourceEpoch: string;
+ code: "network";
+ retryable: true;
+ };
+ };
+ }>) => void;
+ const activities = new Promise<Parameters<typeof resolveActivities>[0]>((resolve) => {
+ resolveActivities = resolve;
+ });
+ ch.onResync(() => ({
+ ready: { runtimeReport: [{ id: "codex" }], runningAgents: [] },
+ sessions: [],
+ activities,
+ }));
+
+ ch.connect();
+ sockets[0].emit("open");
+ expect(sockets[0].frames()).toEqual([
+ expect.objectContaining({ type: "ready", runtimeReport: [{ id: "codex" }] }),
+ ]);
+
+ resolveActivities([{
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: [{
+ botId: "bot_1",
+ day: "2026-08-29",
+ metrics: {
+ input: 8,
+ output: 3,
+ cache: null,
+ },
+ }],
+ quota: {
+ agentBackendId: "codex",
+ observation: {
+ status: "error",
+ sourceEpoch: "Q".repeat(22),
+ code: "network",
+ retryable: true,
+ },
+ },
+ }]);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(sockets[0].frames().at(-1)).toMatchObject({
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: [{ botId: "bot_1", metrics: { input: 8 } }],
+ quota: { agentBackendId: "codex", observation: { code: "network" } },
+ });
+ });
+
it("2b — tolerates a resync provider that omits `activities` (no crash, still sends ready + sessions)", async () => {
// Regression: `activities` is optional on ResyncProvider. A provider that
// returns only { ready, sessions } must not throw "activities is not
diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.ts
index c9d913d4c..ad2391caa 100644
--- a/src/daemon/src/server/wsControlChannel.ts
+++ b/src/daemon/src/server/wsControlChannel.ts
@@ -32,7 +32,7 @@ import type {
SessionErrorFrame,
WebSocketLike,
WebSocketFactory,
- AgentActivityState,
+ HostAgentActivity,
HostBotAuditEventFrame,
} from "./contract.js";
import { HostCommandSchema } from "./contract.js";
@@ -125,7 +125,7 @@ export type AgentCommandAckError = { code: string; message: string };
type OutboundFrame =
| ({ type: "ready" } & HostReady)
| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }
- | { type: "agent_activity"; agentId: AgentId; state: AgentActivityState }
+ | ({ type: "agent_activity" } & HostAgentActivity)
| { type: "agent_typing"; agentId: AgentId; channelId: string }
| { type: "agent_typing_stop"; agentId: AgentId; channelId: string }
| {
@@ -146,11 +146,10 @@ type OutboundFrame =
| HostBotAuditEventFrame
| SessionErrorFrame;
-type AgentActivityReport = { agentId: AgentId; state: AgentActivityState };
type ResyncProvider = () => {
ready: HostReady;
sessions: AgentSessionReport[];
- activities?: AgentActivityReport[];
+ activities?: HostAgentActivity[] | Promise<HostAgentActivity[]>;
};
function describeErr(err: unknown): string {
@@ -292,7 +291,7 @@ export class WsControlChannel implements HostControlChannel {
this.sendFrame({ type: "agent_session", ...info });
}
- async reportAgentActivity(info: { agentId: AgentId; state: AgentActivityState }): Promise<void> {
+ async reportAgentActivity(info: HostAgentActivity): Promise<void> {
this.wakeCoordinator.recordAgentActivity(info.agentId, info.state);
this.sendFrame({ type: "agent_activity", ...info });
}
@@ -401,23 +400,49 @@ export class WsControlChannel implements HostControlChannel {
* what lets the server recover this host after a dropped connection.
*/
private resyncOnConnect(): void {
+ const sendActivities = (
+ activities: HostAgentActivity[],
+ counts: { ready: number; sessions: number },
+ ): void => {
+ for (const activity of activities) {
+ this.sendFrame({ type: "agent_activity", ...activity });
+ }
+ this.log.info("resync sent", {
+ ready: counts.ready,
+ sessions: counts.sessions,
+ activities: activities.length,
+ pendingAuditEvents: this.pendingBotAuditEvents.size,
+ });
+ };
+
if (this.resyncProvider) {
- const { ready, sessions, activities } = this.resyncProvider();
- this.sendFrame({ type: "ready", ...ready });
- for (const s of sessions) this.sendFrame({ type: "agent_session", ...s });
+ const socketAtStart = this.ws;
+ const snapshot = this.resyncProvider();
+ this.sendFrame({ type: "ready", ...snapshot.ready });
+ for (const session of snapshot.sessions) {
+ this.sendFrame({ type: "agent_session", ...session });
+ }
// Re-assert each live agent's current activity: `agent_activity` is
// edge-triggered, so a frame dropped during the disconnect window is
// otherwise lost forever, stranding the pill on a stale state.
- const liveActivities = activities ?? [];
- for (const a of liveActivities) this.sendFrame({ type: "agent_activity", ...a });
for (const frame of this.pendingBotAuditEvents.values()) this.sendFrame(frame);
this.scheduleAuditRetry();
- this.log.info("resync sent", {
- ready: ready.runtimeReport.length,
- sessions: sessions.length,
- activities: liveActivities.length,
- pendingAuditEvents: this.pendingBotAuditEvents.size,
- });
+ const activities = snapshot.activities ?? [];
+ const counts = {
+ ready: snapshot.ready.runtimeReport.length,
+ sessions: snapshot.sessions.length,
+ };
+ if (activities instanceof Promise) {
+ void activities.then((resolved) => {
+ if (this.ws === socketAtStart && this.statusValue === "open") {
+ sendActivities(resolved, counts);
+ }
+ }).catch((err: unknown) => {
+ this.log.warn("resync provider failed", { err: describeErr(err) });
+ });
+ } else {
+ sendActivities(activities, counts);
+ }
}
for (const hook of this.resyncHooks) {
try {
diff --git a/src/daemon/src/telemetry/dailyTokenUsage.test.ts b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
new file mode 100644
index 000000000..8f2e1db30
--- /dev/null
+++ b/src/daemon/src/telemetry/dailyTokenUsage.test.ts
@@ -0,0 +1,149 @@
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { DailyTokenUsageStore } from "./dailyTokenUsage.js";
+
+const roots: string[] = [];
+const delta = (input: number, output: number, cache: number) => ({
+ input,
+ output,
+ cache,
+});
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe("DailyTokenUsageStore", () => {
+ it("serializes concurrent bot updates into one atomic file", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-usage-"));
+ roots.push(root);
+ const now = new Date("2026-08-29T01:00:00Z");
+ const store = new DailyTokenUsageStore(root, () => now);
+ await Promise.all([
+ store.record("bot-a", delta(10, 3, 2)),
+ store.record("bot-b", delta(20, 4, 5)),
+ store.record("bot-a", delta(7, 6, 1)),
+ ]);
+ expect(await store.snapshots("bot-a")).toEqual([{
+ botId: "bot-a",
+ day: "2026-08-29",
+ metrics: {
+ input: 17,
+ output: 9,
+ cache: 3,
+ },
+ }]);
+ expect(readdirSync(join(root, ".telemetry"))).toEqual(["daily-token-usage.json"]);
+ });
+
+ it.skipIf(process.platform === "win32")("writes the atomic file with 0600 permissions", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-usage-mode-"));
+ roots.push(root);
+ const store = new DailyTokenUsageStore(root, () => new Date("2026-08-29T01:00:00Z"));
+ await store.record("bot", delta(1, 2, 3));
+ expect(statSync(join(root, ".telemetry", "daily-token-usage.json")).mode & 0o777).toBe(0o600);
+ });
+
+ it("retains complete snapshots across restart and UTC rollover", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-rollover-"));
+ roots.push(root);
+ let now = new Date("2026-08-29T23:59:59Z");
+ const first = new DailyTokenUsageStore(root, () => now);
+ await first.record("bot", delta(10, 0, 0));
+
+ const restarted = new DailyTokenUsageStore(root, () => now);
+ await restarted.record("bot", {
+ input: 2,
+ output: null,
+ cache: 0,
+ });
+ await restarted.record("bot", { input: 0, output: 5, cache: 0 });
+ now = new Date("2026-08-30T00:00:01Z");
+ await restarted.record("bot", delta(5, 1, 0));
+ expect(await restarted.snapshots("bot")).toEqual([
+ {
+ botId: "bot",
+ day: "2026-08-29",
+ metrics: {
+ input: 12,
+ output: null,
+ cache: 0,
+ },
+ },
+ {
+ botId: "bot",
+ day: "2026-08-30",
+ metrics: {
+ input: 5,
+ output: 1,
+ cache: 0,
+ },
+ },
+ ]);
+ });
+
+ it("keeps only today and the previous six UTC days", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-retention-"));
+ roots.push(root);
+ let now = new Date("2026-08-20T12:00:00Z");
+ const store = new DailyTokenUsageStore(root, () => now);
+ for (let day = 0; day < 9; day += 1) {
+ await store.record("bot", delta(day, day, day));
+ now = new Date(now.getTime() + 86_400_000);
+ }
+ now = new Date("2026-08-28T12:00:00Z");
+ const snapshots = await store.snapshots("bot");
+ expect(snapshots).toHaveLength(7);
+ expect(snapshots.map((snapshot) => snapshot.day)).toEqual([
+ "2026-08-22",
+ "2026-08-23",
+ "2026-08-24",
+ "2026-08-25",
+ "2026-08-26",
+ "2026-08-27",
+ "2026-08-28",
+ ]);
+ });
+
+ it("persists retention pruning even when a quiet bot only reconnects", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-quiet-prune-"));
+ roots.push(root);
+ let now = new Date("2026-08-20T12:00:00Z");
+ const store = new DailyTokenUsageStore(root, () => now);
+ await store.record("bot", delta(1, 1, 1));
+
+ now = new Date("2026-08-29T12:00:00Z");
+ expect(await store.snapshots("bot")).toEqual([]);
+
+ const persisted = JSON.parse(readFileSync(
+ join(root, ".telemetry", "daily-token-usage.json"),
+ "utf8",
+ ));
+ expect(persisted).toEqual({ version: 1, bots: {} });
+ });
+
+ it("does not replace malformed authoritative history", async () => {
+ const root = mkdtempSync(join(tmpdir(), "alook-token-malformed-"));
+ roots.push(root);
+ const directory = join(root, ".telemetry");
+ const filePath = join(directory, "daily-token-usage.json");
+ mkdirSync(directory, { recursive: true });
+ writeFileSync(filePath, "{not-json", "utf8");
+
+ const store = new DailyTokenUsageStore(root);
+ await expect(store.record("bot", delta(1, 2, 3))).rejects.toThrow();
+
+ expect(readFileSync(filePath, "utf8")).toBe("{not-json");
+ expect(readdirSync(directory)).toEqual(["daily-token-usage.json"]);
+ });
+});
diff --git a/src/daemon/src/telemetry/dailyTokenUsage.ts b/src/daemon/src/telemetry/dailyTokenUsage.ts
new file mode 100644
index 000000000..40f02ca8f
--- /dev/null
+++ b/src/daemon/src/telemetry/dailyTokenUsage.ts
@@ -0,0 +1,217 @@
+import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { randomUUID } from "node:crypto";
+import type { TokenUsageDelta } from "@alook/agent-driver";
+
+export type DailyUsageMetric = number | null;
+
+export interface DailyUsageSnapshot {
+ botId: string;
+ day: string;
+ metrics: {
+ input: DailyUsageMetric;
+ output: DailyUsageMetric;
+ cache: DailyUsageMetric;
+ };
+}
+
+type UsageFile = {
+ version: 1;
+ bots: Record<string, DailyUsageSnapshot[]>;
+};
+
+function dayKey(at: Date): string {
+ return at.toISOString().slice(0, 10);
+}
+
+function retainedDays(at: Date): Set<string> {
+ const days = new Set<string>();
+ for (let offset = 0; offset < 7; offset += 1) {
+ days.add(dayKey(new Date(at.getTime() - offset * 86_400_000)));
+ }
+ return days;
+}
+
+function isMetric(value: unknown): value is DailyUsageMetric {
+ return value === null
+ || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
+}
+
+function isSnapshot(value: unknown): value is DailyUsageSnapshot {
+ if (!value || typeof value !== "object") return false;
+ const snapshot = value as Record<string, unknown>;
+ const metrics = snapshot.metrics as Record<string, unknown> | undefined;
+ return typeof snapshot.botId === "string"
+ && snapshot.botId.length > 0
+ && typeof snapshot.day === "string"
+ && /^\d{4}-\d{2}-\d{2}$/.test(snapshot.day)
+ && !!metrics
+ && isMetric(metrics.input)
+ && isMetric(metrics.output)
+ && isMetric(metrics.cache);
+}
+
+function mergeMetric(
+ existing: DailyUsageMetric,
+ delta: TokenUsageDelta["input"],
+ hasExistingSnapshot: boolean,
+): DailyUsageMetric {
+ if (delta === null) return null;
+ if (!Number.isSafeInteger(delta) || delta < 0) {
+ throw new RangeError("token usage delta must be a non-negative safe integer");
+ }
+ if (!hasExistingSnapshot) return delta;
+ if (existing === null) return null;
+ const sum = existing + delta;
+ if (!Number.isSafeInteger(sum)) throw new RangeError("daily token usage exceeds safe integer range");
+ return sum;
+}
+
+function emptySnapshot(botId: string, day: string): DailyUsageSnapshot {
+ return {
+ botId,
+ day,
+ metrics: {
+ input: null,
+ output: null,
+ cache: null,
+ },
+ };
+}
+
+export class DailyTokenUsageStore {
+ private tail: Promise<void> = Promise.resolve();
+ private loaded = false;
+ private data: UsageFile = { version: 1, bots: {} };
+ private readonly filePath: string;
+
+ constructor(workingDirectoryBase: string, private readonly now: () => Date = () => new Date()) {
+ this.filePath = join(workingDirectoryBase, ".telemetry", "daily-token-usage.json");
+ }
+
+ record(botId: string, delta: TokenUsageDelta): Promise<void> {
+ return this.enqueue(async () => {
+ await this.load();
+ const at = this.now();
+ this.prune(at);
+ const day = dayKey(at);
+ const snapshots = this.data.bots[botId] ?? [];
+ const existing = snapshots.find((snapshot) => snapshot.day === day);
+ const next = existing ?? emptySnapshot(botId, day);
+ next.metrics = {
+ input: mergeMetric(next.metrics.input, delta.input, existing !== undefined),
+ output: mergeMetric(next.metrics.output, delta.output, existing !== undefined),
+ cache: mergeMetric(next.metrics.cache, delta.cache, existing !== undefined),
+ };
+ if (!existing) snapshots.push(next);
+ snapshots.sort((a, b) => a.day.localeCompare(b.day));
+ this.data.bots[botId] = snapshots;
+ await this.persist();
+ });
+ }
+
+ snapshots(botId: string): Promise<DailyUsageSnapshot[]> {
+ let result: DailyUsageSnapshot[] = [];
+ return this.enqueue(async () => {
+ await this.load();
+ if (this.prune(this.now())) await this.persist();
+ result = (this.data.bots[botId] ?? []).map((snapshot) => structuredClone(snapshot));
+ }).then(() => result);
+ }
+
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.tail.then(operation, operation);
+ this.tail = result.then(() => undefined, () => undefined);
+ return result;
+ }
+
+ private async load(): Promise<void> {
+ if (this.loaded) return;
+ let source: string;
+ try {
+ source = await readFile(this.filePath, "utf8");
+ } catch (error) {
+ if (
+ !error
+ || typeof error !== "object"
+ || !("code" in error)
+ || error.code !== "ENOENT"
+ ) {
+ throw error;
+ }
+ this.data = { version: 1, bots: {} };
+ this.loaded = true;
+ return;
+ }
+
+ const parsed = JSON.parse(source) as unknown;
+ if (!parsed || typeof parsed !== "object" || (parsed as { version?: unknown }).version !== 1) {
+ throw new Error("invalid daily token usage file version");
+ }
+ const bots = (parsed as { bots?: unknown }).bots;
+ if (!bots || typeof bots !== "object" || Array.isArray(bots)) {
+ throw new Error("invalid daily token usage bots map");
+ }
+ const valid: Record<string, DailyUsageSnapshot[]> = {};
+ for (const [botId, value] of Object.entries(bots)) {
+ if (
+ !Array.isArray(value)
+ || !value.every(isSnapshot)
+ || value.some((snapshot) => snapshot.botId !== botId)
+ ) {
+ throw new Error(`invalid daily token usage snapshots for bot ${botId}`);
+ }
+ if (value.length > 0) {
+ valid[botId] = value;
+ }
+ }
+ this.data = { version: 1, bots: valid };
+ this.loaded = true;
+ }
+
+ private prune(at: Date): boolean {
+ const keep = retainedDays(at);
+ let changed = false;
+ for (const [botId, snapshots] of Object.entries(this.data.bots)) {
+ const retained = snapshots
+ .filter((snapshot) => keep.has(snapshot.day))
+ .sort((a, b) => a.day.localeCompare(b.day))
+ .slice(-7);
+ if (
+ retained.length !== snapshots.length
+ || retained.some((snapshot, index) => snapshot !== snapshots[index])
+ ) changed = true;
+ if (retained.length === 0) delete this.data.bots[botId];
+ else this.data.bots[botId] = retained;
+ }
+ return changed;
+ }
+
+ private async persist(): Promise<void> {
+ const directory = dirname(this.filePath);
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ const temporary = `${this.filePath}.${randomUUID()}.tmp`;
+ try {
+ const file = await open(temporary, "wx", 0o600);
+ try {
+ await file.writeFile(JSON.stringify(this.data), { encoding: "utf8" });
+ await file.sync();
+ } finally {
+ await file.close();
+ }
+ await rename(temporary, this.filePath);
+ await chmod(this.filePath, 0o600);
+ try {
+ const directoryHandle = await open(directory, "r");
+ try {
+ await directoryHandle.sync();
+ } finally {
+ await directoryHandle.close();
+ }
+ } catch { }
+ } catch (error) {
+ await rm(temporary, { force: true }).catch(() => {});
+ throw error;
+ }
+ }
+}
diff --git a/src/daemon/src/telemetry/index.ts b/src/daemon/src/telemetry/index.ts
new file mode 100644
index 000000000..5bb7e8a13
--- /dev/null
+++ b/src/daemon/src/telemetry/index.ts
@@ -0,0 +1 @@
+export * from "./dailyTokenUsage.js";
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 01047a05c..09f8152b1 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -29,6 +29,10 @@ import { CHANNEL_TRAITS } from "./utils/community-roles";
import { parseNameAndTag } from "./lib/discriminator";
import { DiagnosticCollectCommandSchema } from "./diagnostics-contract";
import type { DiagnosticCollectCommand } from "./diagnostics-contract";
+import type {
+ DailyUsageSnapshot,
+ ProviderQuotaSnapshot,
+} from "./provider-telemetry";
/* ------------------------------------------------------------------ */
/* Identifiers */
@@ -861,6 +865,7 @@ export interface HostReady {
arch?: string;
osRelease?: string;
daemonVersion?: string;
+ providerQuotas?: ProviderQuotaSnapshot[];
}
/**
@@ -870,6 +875,13 @@ export interface HostReady {
*/
export type AgentActivityState = "idle" | "starting" | "running" | "stopping";
+export interface HostAgentActivity {
+ agentId: AgentId;
+ state: AgentActivityState;
+ dailyUsage?: DailyUsageSnapshot[];
+ quota?: ProviderQuotaSnapshot;
+}
+
/**
* Bot audit-log event kinds/payloads mirrored from the wire zod schema
* (`BotAuditEventSchema` in `./schemas.ts`). The daemon emits these upward
@@ -983,7 +995,7 @@ export interface HostControlChannel {
* Report a bot's derived activity state after it changes. Optional so the
* local mock channel can omit it.
*/
- reportAgentActivity?(info: { agentId: AgentId; state: AgentActivityState }): Promise<void>;
+ reportAgentActivity?(info: HostAgentActivity): Promise<void>;
/**
* Emit an `agent_typing` frame for the given (agentId, channelId) scope —
* the daemon-metered heartbeat that keeps the "bot is typing…" pill lit for
@@ -1016,7 +1028,7 @@ export interface HostControlChannel {
onResync?(provider: () => {
ready: HostReady;
sessions: AgentSessionReport[];
- activities: Array<{ agentId: AgentId; state: AgentActivityState }>;
+ activities: HostAgentActivity[] | Promise<HostAgentActivity[]>;
}): void;
}
diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.ts
index 646527d11..d3f54adb7 100644
--- a/src/shared/src/db/community-machine-schema.ts
+++ b/src/shared/src/db/community-machine-schema.ts
@@ -1,8 +1,9 @@
-import { check, index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { check, index, integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
import { sql } from "drizzle-orm";
import { nanoid } from "nanoid";
import { user } from "./schema";
import type { CommunityMachineRuntime } from "../community-ws-events";
+import type { QuotaLimit } from "../provider-telemetry";
export const DIAGNOSTIC_REPORT_FAILURE_CODES = [
"offline",
@@ -271,6 +272,28 @@ export const communityBotBinding = sqliteTable(
(t) => [index("idx_community_bot_binding_machine").on(t.machineId)]
);
+export type MachineBackendQuotaStatus = "available" | "error";
+
+export const communityMachineBackendQuota = sqliteTable(
+ "community_machine_backend_quota",
+ {
+ machineId: text("machine_id")
+ .notNull()
+ .references(() => communityMachine.id, { onDelete: "cascade" }),
+ agentBackendId: text("agent_backend_id").$type<"claude" | "codex">().notNull(),
+ sourceEpoch: text("source_epoch").notNull(),
+ status: text("status").$type<MachineBackendQuotaStatus>().notNull(),
+ planName: text("plan_name"),
+ freshForSeconds: integer("fresh_for_seconds"),
+ limits: text("limits", { mode: "json" }).$type<QuotaLimit[]>(),
+ errorCode: text("error_code"),
+ retryable: integer("retryable", { mode: "boolean" }),
+ observedAt: text("observed_at").notNull(),
+ updatedAt: text("updated_at").notNull(),
+ },
+ (t) => [primaryKey({ columns: [t.machineId, t.agentBackendId] })]
+);
+
// community_agent_runner_key — per-agent runner key. Same hashing shape
// as community_machine_credential; no data-plane consumer in v1.
export const communityAgentRunnerKey = sqliteTable(
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index cae92e312..88e865fe1 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -602,6 +602,24 @@ export const communityBotDailyActivity = sqliteTable(
(t) => [primaryKey({ columns: [t.botId, t.day] })]
);
+export const communityBotDailyTokenUsage = sqliteTable(
+ "community_bot_daily_token_usage",
+ {
+ botId: text("bot_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ day: text("day").notNull(),
+ inputTokens: integer("input_tokens"),
+ outputTokens: integer("output_tokens"),
+ cacheTokens: integer("cache_tokens"),
+ updatedAt: text("updated_at").notNull(),
+ },
+ (t) => [
+ primaryKey({ columns: [t.botId, t.day] }),
+ index("idx_community_bot_daily_token_usage_day").on(t.day),
+ ]
+);
+
// 23. community_message_mark
// Per-user private bookmark ("mark") on a message. Unlike community_pin (15),
// which is channel-shared (everyone sees the same set), a mark is keyed by the
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index 3256387c9..dd1b060b6 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -30,8 +30,10 @@ import {
communityUserProfile,
communityReadState,
communityBotDailyActivity,
+ communityBotDailyTokenUsage,
communityBotActivityEvent,
} from "../../community-schema";
+import type { DailyUsageSnapshot } from "../../../provider-telemetry";
import { communityMachine } from "../../community-machine-schema";
import type { Database } from "../../index";
import { communityBotSyntheticEmail } from "../../../constants";
@@ -138,6 +140,45 @@ export async function listBotsForOwner(
}));
}
+export async function getBotDailyTokenUsageForOwner(
+ db: Database,
+ ownerId: string,
+ sinceDay: string,
+): Promise<Map<string, DailyUsageSnapshot[]>> {
+ const rows = await db
+ .select({
+ botId: communityBotDailyTokenUsage.botId,
+ day: communityBotDailyTokenUsage.day,
+ inputTokens: communityBotDailyTokenUsage.inputTokens,
+ outputTokens: communityBotDailyTokenUsage.outputTokens,
+ cacheTokens: communityBotDailyTokenUsage.cacheTokens,
+ })
+ .from(communityBotDailyTokenUsage)
+ .innerJoin(user, eq(user.id, communityBotDailyTokenUsage.botId))
+ .where(and(
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ gte(communityBotDailyTokenUsage.day, sinceDay),
+ ));
+ const byBot = new Map<string, DailyUsageSnapshot[]>();
+ for (const row of rows) {
+ const snapshots = byBot.get(row.botId) ?? [];
+ snapshots.push({
+ botId: row.botId,
+ day: row.day,
+ metrics: {
+ input: row.inputTokens,
+ output: row.outputTokens,
+ cache: row.cacheTokens,
+ },
+ });
+ byBot.set(row.botId, snapshots);
+ }
+ for (const snapshots of byBot.values()) snapshots.sort((a, b) => a.day.localeCompare(b.day));
+ return byBot;
+}
+
/**
* Get a bot iff it's owned by `ownerId`. Returns null on any mismatch — this
* is the ownership-scoping gate for every bot-mutating route.
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index 271cec2fc..ba357b546 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -5,6 +5,7 @@ import {
communityMachineCredential,
communityAgentRunnerKey,
communityBotBinding,
+ communityMachineBackendQuota,
} from "../../community-machine-schema";
import { user } from "../../schema";
import { communityUserProfile } from "../../community-schema";
@@ -16,6 +17,7 @@ import type {
CommunityMachineRuntime,
CommunityMachineSummary,
} from "../../../community-ws-events";
+import type { ProviderQuotaObservation, ProviderQuotaSnapshot } from "../../../provider-telemetry";
// ---------------------------------------------------------------------------
// Credential hashing
@@ -239,6 +241,49 @@ export interface MachineRow {
updatedAt: string;
}
+export async function listMachineBackendQuotasForUser(
+ db: Database,
+ userId: string,
+): Promise<Map<string, Array<{ quota: ProviderQuotaSnapshot; observedAt: string }>>> {
+ const rows = await db
+ .select({
+ machineId: communityMachineBackendQuota.machineId,
+ agentBackendId: communityMachineBackendQuota.agentBackendId,
+ status: communityMachineBackendQuota.status,
+ sourceEpoch: communityMachineBackendQuota.sourceEpoch,
+ planName: communityMachineBackendQuota.planName,
+ freshForSeconds: communityMachineBackendQuota.freshForSeconds,
+ limits: communityMachineBackendQuota.limits,
+ errorCode: communityMachineBackendQuota.errorCode,
+ retryable: communityMachineBackendQuota.retryable,
+ observedAt: communityMachineBackendQuota.observedAt,
+ })
+ .from(communityMachineBackendQuota)
+ .innerJoin(communityMachine, eq(communityMachine.id, communityMachineBackendQuota.machineId))
+ .where(eq(communityMachine.userId, userId));
+ const byMachine = new Map<string, Array<{ quota: ProviderQuotaSnapshot; observedAt: string }>>();
+ for (const row of rows) {
+ const observation: ProviderQuotaObservation = row.status === "available"
+ ? {
+ status: "available",
+ sourceEpoch: row.sourceEpoch,
+ ...(row.planName ? { planName: row.planName } : {}),
+ freshForSeconds: row.freshForSeconds ?? 1,
+ limits: row.limits ?? [],
+ }
+ : {
+ status: "error",
+ sourceEpoch: row.sourceEpoch,
+ code: (row.errorCode ?? "unavailable") as Extract<ProviderQuotaObservation, { status: "error" }>["code"],
+ retryable: row.retryable ?? false,
+ };
+ const snapshots = byMachine.get(row.machineId) ?? [];
+ snapshots.push({ quota: { agentBackendId: row.agentBackendId, observation }, observedAt: row.observedAt });
+ byMachine.set(row.machineId, snapshots);
+ }
+ return byMachine;
+}
+
// ---------------------------------------------------------------------------
// Bot activity telemetry — see plans/community-bot-status-telemetry.md.
//
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 5c0edbc76..72fc9da39 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -186,6 +186,7 @@ export {
CACHE_REVALIDATE,
} from "./constants/community";
export type { NotifLevel, NotificationLevelValue, ParticipantSource, MentionKind } from "./constants/community";
+export * from "./provider-telemetry";
export type {
AgentStatusType,
@@ -475,6 +476,7 @@ export type {
AgentSessionReport,
ParsedRef as CommunityCliParsedRef,
AgentActivityState,
+ HostAgentActivity,
HostBotAuditEventFrame,
BotAuditEventPayload,
} from "./community-cli-contract";
diff --git a/src/shared/src/provider-telemetry.test.ts b/src/shared/src/provider-telemetry.test.ts
new file mode 100644
index 000000000..1ab254040
--- /dev/null
+++ b/src/shared/src/provider-telemetry.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vitest"
+import {
+ DailyUsageSnapshotSchema,
+ ProviderQuotaObservationSchema,
+} from "./provider-telemetry.js"
+
+function quotaLimit() {
+ return {
+ bucket: {
+ limitId: "primary",
+ product: { kind: "reported" as const, id: "codex", displayName: "Codex" },
+ model: { kind: "reported" as const, id: "gpt-5.3-codex-spark" },
+ window: { kind: "rolling" as const, durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ },
+ usedPercent: 42.5,
+ resetsAt: "2026-08-29T01:00:00.000Z",
+ }
+}
+
+describe("provider telemetry schemas", () => {
+ it("accepts exact zero and unavailable usage without conflating them", () => {
+ expect(DailyUsageSnapshotSchema.parse({
+ botId: "bot_1",
+ day: "2026-08-29",
+ metrics: {
+ input: 0,
+ output: 0,
+ cache: null,
+ },
+ })).toEqual(expect.objectContaining({
+ metrics: {
+ input: 0,
+ output: 0,
+ cache: null,
+ },
+ }))
+ })
+
+ it("rejects unsafe token values", () => {
+ const base = {
+ botId: "bot_1",
+ day: "2026-08-29",
+ metrics: {
+ input: Number.MAX_SAFE_INTEGER + 1,
+ output: null,
+ cache: null,
+ },
+ }
+ expect(DailyUsageSnapshotSchema.safeParse(base).success).toBe(false)
+ })
+
+ it("accepts the Spark two-window fixture as two distinct bucket identities", () => {
+ const primary = quotaLimit()
+ const weekly = {
+ ...quotaLimit(),
+ bucket: {
+ ...quotaLimit().bucket,
+ limitId: "secondary",
+ window: { kind: "calendar" as const, period: "week" as const, displayName: "Weekly usage limit" },
+ },
+ }
+ expect(ProviderQuotaObservationSchema.safeParse({
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ freshForSeconds: 300,
+ limits: [primary, weekly],
+ }).success).toBe(true)
+ })
+
+ it("rejects duplicate identities, out-of-range percentages, and labels over 64 UTF-8 bytes", () => {
+ const duplicate = quotaLimit()
+ expect(ProviderQuotaObservationSchema.safeParse({
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ freshForSeconds: 300,
+ limits: [duplicate, { ...duplicate, usedPercent: 12 }],
+ }).success).toBe(false)
+ expect(ProviderQuotaObservationSchema.safeParse({
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ freshForSeconds: 300,
+ limits: [{ ...quotaLimit(), usedPercent: 101 }],
+ }).success).toBe(false)
+ expect(ProviderQuotaObservationSchema.safeParse({
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ planName: "🙂".repeat(17),
+ freshForSeconds: 300,
+ limits: [quotaLimit()],
+ }).success).toBe(false)
+ })
+})
diff --git a/src/shared/src/provider-telemetry.ts b/src/shared/src/provider-telemetry.ts
new file mode 100644
index 000000000..47657ec2b
--- /dev/null
+++ b/src/shared/src/provider-telemetry.ts
@@ -0,0 +1,112 @@
+import { z } from "zod";
+
+const safeToken = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
+const boundedText = z.string().min(1).refine(
+ (value) => new TextEncoder().encode(value).length <= 64,
+ { message: "must be at most 64 UTF-8 bytes" },
+);
+
+export const DailyUsageMetricSchema = safeToken.nullable();
+export type DailyUsageMetric = z.infer<typeof DailyUsageMetricSchema>;
+
+export const DailyUsageSnapshotSchema = z.object({
+ botId: z.string().min(1),
+ day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
+ metrics: z.object({
+ input: DailyUsageMetricSchema,
+ output: DailyUsageMetricSchema,
+ cache: DailyUsageMetricSchema,
+ }).strict(),
+}).strict();
+export type DailyUsageSnapshot = z.infer<typeof DailyUsageSnapshotSchema>;
+
+export const QuotaProductIdentitySchema = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("reported"), id: boundedText, displayName: boundedText }).strict(),
+ z.object({ kind: z.literal("unknown"), displayName: boundedText }).strict(),
+]);
+export type QuotaProductIdentity = z.infer<typeof QuotaProductIdentitySchema>;
+
+export const QuotaModelIdentitySchema = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("reported"), id: boundedText }).strict(),
+ z.object({ kind: z.literal("not_applicable") }).strict(),
+ z.object({ kind: z.literal("unknown") }).strict(),
+]);
+export type QuotaModelIdentity = z.infer<typeof QuotaModelIdentitySchema>;
+
+export const QuotaWindowIdentitySchema = z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("rolling"),
+ durationSeconds: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ displayName: boundedText,
+ }).strict(),
+ z.object({
+ kind: z.literal("calendar"),
+ period: z.enum(["day", "week", "month"]),
+ displayName: boundedText,
+ }).strict(),
+ z.object({
+ kind: z.literal("provider_defined"),
+ id: boundedText,
+ durationSeconds: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
+ displayName: boundedText,
+ }).strict(),
+]);
+export type QuotaWindowIdentity = z.infer<typeof QuotaWindowIdentitySchema>;
+
+export const QuotaLimitSchema = z.object({
+ bucket: z.object({
+ limitId: boundedText,
+ product: QuotaProductIdentitySchema,
+ model: QuotaModelIdentitySchema,
+ window: QuotaWindowIdentitySchema,
+ }).strict(),
+ usedPercent: z.number().finite().min(0).max(100),
+ resetsAt: z.string().datetime({ offset: true }).optional(),
+}).strict();
+export type QuotaLimit = z.infer<typeof QuotaLimitSchema>;
+
+function quotaIdentity(limit: QuotaLimit): string {
+ const { product, model, window, limitId } = limit.bucket;
+ const productKey = product.kind === "reported" ? `reported:${product.id}` : "unknown";
+ const modelKey = model.kind === "reported" ? `reported:${model.id}` : model.kind;
+ const windowKey = window.kind === "rolling"
+ ? `rolling:${window.durationSeconds}`
+ : window.kind === "calendar"
+ ? `calendar:${window.period}`
+ : `provider_defined:${window.id}:${window.durationSeconds === undefined ? "absent" : window.durationSeconds}`;
+ return `${productKey}\u0000${modelKey}\u0000${windowKey}\u0000${limitId}`;
+}
+
+const AvailableQuotaObservationSchema = z.object({
+ status: z.literal("available"),
+ sourceEpoch: z.string().regex(/^[A-Za-z0-9_-]{22}$/),
+ planName: boundedText.optional(),
+ freshForSeconds: z.number().int().positive().max(86_400),
+ limits: z.array(QuotaLimitSchema).min(1).max(8),
+}).strict().superRefine((value, ctx) => {
+ const identities = new Set<string>();
+ for (const [index, limit] of value.limits.entries()) {
+ const identity = quotaIdentity(limit);
+ if (identities.has(identity)) {
+ ctx.addIssue({ code: "custom", message: "duplicate quota bucket identity", path: ["limits", index] });
+ }
+ identities.add(identity);
+ }
+});
+
+export const ProviderQuotaObservationSchema = z.union([
+ AvailableQuotaObservationSchema,
+ z.object({
+ status: z.literal("error"),
+ sourceEpoch: z.string().regex(/^[A-Za-z0-9_-]{22}$/),
+ code: z.enum(["unavailable", "unauthorized", "network", "provider_error", "invalid_response"]),
+ retryable: z.boolean(),
+ }).strict(),
+]);
+export type ProviderQuotaObservation = z.infer<typeof ProviderQuotaObservationSchema>;
+
+export const ProviderQuotaSnapshotSchema = z.object({
+ agentBackendId: z.enum(["claude", "codex"]),
+ observation: ProviderQuotaObservationSchema,
+}).strict();
+export type ProviderQuotaSnapshot = z.infer<typeof ProviderQuotaSnapshotSchema>;
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 5bdc61fc3..117b81546 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -2,6 +2,10 @@ import { z } from "zod";
import { IssueStatus, TASK_TYPES } from "./constants";
import { sanitizeSlug } from "./utils/slug";
import { DiagnosticReportIdSchema } from "./diagnostics-contract";
+import {
+ DailyUsageSnapshotSchema,
+ ProviderQuotaSnapshotSchema,
+} from "./provider-telemetry";
import {
ALLOWED_ICON_MIME_TYPES,
MAX_ATTACHMENTS_PER_MESSAGE,
@@ -982,6 +986,7 @@ export const HostReadyMessageSchema = z.object({
arch: z.string().optional(),
osRelease: z.string().optional(),
daemonVersion: z.string().optional(),
+ providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(2).optional().default([]),
});
export type HostReadyMessage = z.infer<typeof HostReadyMessageSchema>;
@@ -1022,6 +1027,8 @@ export const AgentActivityMessageSchema = z.object({
type: z.literal("agent_activity"),
agentId: z.string(),
state: z.enum(["idle", "starting", "running", "stopping"]),
+ dailyUsage: z.array(DailyUsageSnapshotSchema).max(7).optional(),
+ quota: ProviderQuotaSnapshotSchema.optional(),
});
export type AgentActivityMessage = z.infer<typeof AgentActivityMessageSchema>;
diff --git a/src/web/migrations/0092_community_token_usage_quota.sql b/src/web/migrations/0092_community_token_usage_quota.sql
new file mode 100644
index 000000000..31e4f00c3
--- /dev/null
+++ b/src/web/migrations/0092_community_token_usage_quota.sql
@@ -0,0 +1,33 @@
+CREATE TABLE community_bot_daily_token_usage (
+ bot_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ day TEXT NOT NULL,
+ input_tokens INTEGER CHECK (input_tokens IS NULL OR (typeof(input_tokens) = 'integer' AND input_tokens >= 0)),
+ output_tokens INTEGER CHECK (output_tokens IS NULL OR (typeof(output_tokens) = 'integer' AND output_tokens >= 0)),
+ cache_tokens INTEGER CHECK (cache_tokens IS NULL OR (typeof(cache_tokens) = 'integer' AND cache_tokens >= 0)),
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (bot_id, day),
+ CHECK (day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]')
+);
+
+CREATE INDEX idx_community_bot_daily_token_usage_day
+ ON community_bot_daily_token_usage(day);
+
+CREATE TABLE community_machine_backend_quota (
+ machine_id TEXT NOT NULL REFERENCES community_machine(id) ON DELETE CASCADE,
+ agent_backend_id TEXT NOT NULL CHECK (agent_backend_id IN ('claude', 'codex')),
+ source_epoch TEXT NOT NULL CHECK (length(source_epoch) = 22 AND source_epoch NOT GLOB '*[^A-Za-z0-9_-]*'),
+ status TEXT NOT NULL CHECK (status IN ('available', 'error')),
+ plan_name TEXT,
+ fresh_for_seconds INTEGER,
+ limits TEXT,
+ error_code TEXT,
+ retryable INTEGER,
+ observed_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (machine_id, agent_backend_id),
+ CHECK (
+ (status = 'available' AND fresh_for_seconds BETWEEN 1 AND 86400 AND json_valid(limits) AND json_array_length(limits) BETWEEN 1 AND 8 AND error_code IS NULL AND retryable IS NULL)
+ OR
+ (status = 'error' AND plan_name IS NULL AND fresh_for_seconds IS NULL AND limits IS NULL AND error_code IN ('unavailable', 'unauthorized', 'network', 'provider_error', 'invalid_response') AND retryable IN (0, 1))
+ )
+);
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index f64e89439..06e2646cc 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -8,6 +8,7 @@ const mockGetUserPublic = vi.fn()
const mockPushBotEventToMachine = vi.fn()
const mockListBotsForOwner = vi.fn()
const mockGetBotDailyActivityForOwner = vi.fn()
+const mockGetBotDailyTokenUsageForOwner = vi.fn()
const mockEnsureSiblingBotFriendship = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
@@ -27,6 +28,7 @@ vi.mock("@alook/shared", async () => {
createBot: (...a: unknown[]) => mockCreateBot(...a),
listBotsForOwner: (...a: unknown[]) => mockListBotsForOwner(...a),
getBotDailyActivityForOwner: (...a: unknown[]) => mockGetBotDailyActivityForOwner(...a),
+ getBotDailyTokenUsageForOwner: (...a: unknown[]) => mockGetBotDailyTokenUsageForOwner(...a),
},
communityFriendship: {
ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSiblingBotFriendship(...a),
@@ -202,6 +204,7 @@ describe("POST /api/community/bots — model", () => {
describe("GET /api/community/bots — heatmap activity", () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map())
})
it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {
@@ -238,4 +241,60 @@ describe("GET /api/community/bots — heatmap activity", () => {
expect(res.status).toBe(200)
expect((await res.json()) as { bots: unknown[] }).toEqual({ bots: [] })
})
+
+ it("returns seven oldest-to-newest usage days with nullable metrics and capability", async () => {
+ const today = new Date().toISOString().slice(0, 10)
+ mockListBotsForOwner.mockResolvedValue([
+ { id: "bot_claude", runtime: "claude" },
+ { id: "bot_codex", runtime: "codex" },
+ { id: "bot_cursor", runtime: "cursor" },
+ { id: "bot_opencode", runtime: "opencode" },
+ { id: "bot_pi", runtime: "pi" },
+ ])
+ mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
+ mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map([
+ ["bot_codex", [{
+ botId: "bot_codex",
+ day: today,
+ metrics: {
+ input: 8,
+ output: 3,
+ cache: null,
+ },
+ }]],
+ ]))
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json() as {
+ bots: Array<{
+ id: string
+ usage: { capability: string; days: Array<{ day: string; period: string; metrics: unknown }> }
+ }>
+ }
+ const supported = body.bots.find((bot) => bot.id === "bot_codex")!
+ expect(supported.usage.capability).toBe("supported")
+ expect(supported.usage.days).toHaveLength(7)
+ expect(supported.usage.days.at(-1)).toEqual({
+ day: today,
+ period: "in_progress",
+ metrics: {
+ input: 8,
+ output: 3,
+ cache: null,
+ },
+ })
+ expect(supported.usage.days.slice(0, -1).every((day) => day.period === "closed")).toBe(true)
+ expect(Object.fromEntries(body.bots.map((bot) => [bot.id, bot.usage.capability]))).toEqual({
+ bot_claude: "supported",
+ bot_codex: "supported",
+ bot_cursor: "unsupported",
+ bot_opencode: "supported",
+ bot_pi: "unsupported",
+ })
+ expect(mockGetBotDailyTokenUsageForOwner).toHaveBeenCalledWith(
+ expect.anything(),
+ "u1",
+ expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),
+ )
+ })
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 959472600..be6aed441 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -24,9 +24,38 @@ export const GET = withAuth(async (_req, ctx) => {
ctx.userId,
sinceDay,
)
+ const usageSinceDay = utcDayKeyDaysAgo(new Date(), 6)
+ const usageByBot = await queries.communityBot.getBotDailyTokenUsageForOwner(
+ db,
+ ctx.userId,
+ usageSinceDay,
+ )
+ const now = new Date()
+ const usageDays = Array.from({ length: 7 }, (_, index) =>
+ utcDayKeyDaysAgo(now, 6 - index)
+ )
const withActivity = bots.map((bot) => ({
...bot,
dailyActivity: activityByBot.get(bot.id) ?? [],
+ usage: {
+ capability: (["claude", "codex", "opencode"] as string[]).includes(bot.runtime)
+ ? "supported" as const
+ : bot.runtime === "cursor" || bot.runtime === "pi"
+ ? "unsupported" as const
+ : "unknown" as const,
+ days: usageDays.map((day, index) => {
+ const stored = usageByBot.get(bot.id)?.find((snapshot) => snapshot.day === day)
+ return {
+ day,
+ period: index === usageDays.length - 1 ? "in_progress" as const : "closed" as const,
+ metrics: stored?.metrics ?? {
+ input: null,
+ output: null,
+ cache: null,
+ },
+ }
+ }),
+ },
}))
return writeJSON({ bots: withActivity })
})
diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.ts
new file mode 100644
index 000000000..4c4c739a6
--- /dev/null
+++ b/src/web/src/app/api/community/machines/route.test.ts
@@ -0,0 +1,162 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockListMachinesForUser = vi.fn()
+const mockListMachineBackendQuotasForUser = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMachine: {
+ listMachinesForUser: (...args: unknown[]) => mockListMachinesForUser(...args),
+ listMachineBackendQuotasForUser: (...args: unknown[]) =>
+ mockListMachineBackendQuotasForUser(...args),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (request: any) =>
+ handler(request, { env: { DB: {} }, userId: "u1", email: "[email protected]" }),
+}))
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ }
+})
+
+import { GET } from "./route"
+
+describe("GET /api/community/machines — provider quota", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("projects one safe machine/backend quota entry per reported runtime", async () => {
+ const observedAt = new Date().toISOString()
+ mockListMachinesForUser.mockResolvedValue([{
+ id: "cm_1",
+ status: "online",
+ availableRuntimes: [
+ { id: "codex", status: "healthy" },
+ { id: "claude", status: "unhealthy" },
+ { id: "cursor", status: "healthy" },
+ ],
+ }])
+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map([[
+ "cm_1",
+ [
+ {
+ observedAt,
+ quota: {
+ agentBackendId: "codex",
+ observation: {
+ status: "available",
+ sourceEpoch: "S".repeat(22),
+ planName: "Plus",
+ freshForSeconds: 300,
+ limits: [{
+ bucket: {
+ limitId: "primary",
+ product: { kind: "reported", id: "codex", displayName: "Codex" },
+ model: { kind: "not_applicable" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ },
+ usedPercent: 37.5,
+ }],
+ },
+ },
+ },
+ {
+ observedAt,
+ quota: {
+ agentBackendId: "claude",
+ observation: {
+ status: "error",
+ sourceEpoch: "T".repeat(22),
+ code: "unauthorized",
+ retryable: false,
+ },
+ },
+ },
+ ],
+ ]]))
+
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ const body = await response.json() as { machines: Array<{ quota: any[] }> }
+ expect(response.status).toBe(200)
+ expect(body.machines[0]!.quota).toEqual([
+ {
+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "codex" },
+ capability: "supported",
+ runtimeState: "healthy",
+ snapshot: {
+ status: "available",
+ observedAt,
+ planName: "Plus",
+ limits: [expect.objectContaining({ usedPercent: 37.5 })],
+ },
+ },
+ {
+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "claude" },
+ capability: "supported",
+ runtimeState: "unhealthy",
+ snapshot: { status: "error", code: "unauthorized" },
+ },
+ {
+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "cursor" },
+ capability: "unsupported",
+ runtimeState: "healthy",
+ snapshot: { status: "pending" },
+ },
+ ])
+ expect(JSON.stringify(body)).not.toContain("sourceEpoch")
+ expect(JSON.stringify(body)).not.toContain("retryable")
+ expect(mockListMachineBackendQuotasForUser).toHaveBeenCalledWith(expect.anything(), "u1")
+ })
+
+ it("marks an expired available observation stale and machine runtimes offline", async () => {
+ mockListMachinesForUser.mockResolvedValue([{
+ id: "cm_1",
+ status: "offline",
+ availableRuntimes: [{ id: "codex", status: "healthy" }],
+ }])
+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map([[
+ "cm_1",
+ [{
+ observedAt: "2020-01-01T00:00:00.000Z",
+ quota: {
+ agentBackendId: "codex",
+ observation: {
+ status: "available",
+ sourceEpoch: "U".repeat(22),
+ freshForSeconds: 60,
+ limits: [{
+ bucket: {
+ limitId: "primary",
+ product: { kind: "unknown", displayName: "Codex" },
+ model: { kind: "unknown" },
+ window: { kind: "provider_defined", id: "primary", displayName: "Primary" },
+ },
+ usedPercent: 50,
+ }],
+ },
+ },
+ }],
+ ]]))
+
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ const body = await response.json() as { machines: Array<{ quota: any[] }> }
+ expect(body.machines[0]!.quota[0]).toMatchObject({
+ runtimeState: "offline",
+ snapshot: { status: "stale", observedAt: "2020-01-01T00:00:00.000Z" },
+ })
+ })
+})
diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.ts
index 70676d3f3..b10d99374 100644
--- a/src/web/src/app/api/community/machines/route.ts
+++ b/src/web/src/app/api/community/machines/route.ts
@@ -6,5 +6,43 @@ import { writeJSON } from "@/lib/middleware/helpers"
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const machines = await queries.communityMachine.listMachinesForUser(db, ctx.userId)
- return writeJSON({ machines })
+ const quotaByMachine = await queries.communityMachine.listMachineBackendQuotasForUser(db, ctx.userId)
+ const now = Date.now()
+ const withQuota = machines.map((machine) => {
+ const stored = quotaByMachine.get(machine.id) ?? []
+ const quota = machine.availableRuntimes.map((runtime) => {
+ const capability = runtime.id === "claude" || runtime.id === "codex"
+ ? "supported" as const
+ : runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi"
+ ? "unsupported" as const
+ : "unknown" as const
+ const runtimeState = machine.status === "offline"
+ ? "offline" as const
+ : runtime.status === "unhealthy"
+ ? "unhealthy" as const
+ : "healthy" as const
+ const current = stored.find((entry) => entry.quota.agentBackendId === runtime.id)
+ const observation = current?.quota.observation
+ const snapshot = !current || !observation
+ ? { status: "pending" as const }
+ : observation.status === "error"
+ ? { status: "error" as const, code: observation.code }
+ : {
+ status: now <= Date.parse(current.observedAt) + observation.freshForSeconds * 1_000
+ ? "available" as const
+ : "stale" as const,
+ observedAt: current.observedAt,
+ ...(observation.planName ? { planName: observation.planName } : {}),
+ limits: observation.limits,
+ }
+ return {
+ scope: { kind: "machine_backend" as const, machineId: machine.id, agentBackendId: runtime.id },
+ capability,
+ runtimeState,
+ snapshot,
+ }
+ })
+ return { ...machine, quota }
+ })
+ return writeJSON({ machines: withQuota })
})
diff --git a/src/web/src/components/community/bots/bot-list-card.test.ts b/src/web/src/components/community/bots/bot-list-card.test.ts
index 6607c5575..cd94e68e2 100644
--- a/src/web/src/components/community/bots/bot-list-card.test.ts
+++ b/src/web/src/components/community/bots/bot-list-card.test.ts
@@ -2,10 +2,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import type { BotSummary } from "@/hooks/community/use-bots"
+import { tid } from "@/lib/community/testids"
// BotList pulls in many hooks + portal-heavy children. Mock them to passthroughs
// so we can render just the card meta row and assert the model segment. What we
-// assert is the presence/absence of `data-testid="bot-card-model"` and its text.
+// assert is the presence/absence of the canonical model test ID and its text.
const useBotsMock = vi.fn()
const bugReportDialogMock = vi.fn()
@@ -98,7 +99,7 @@ function render(): TestRenderer.ReactTestRenderer {
function modelSegments(renderer: TestRenderer.ReactTestRenderer): string[] {
return renderer.root
- .findAll((n) => n.props?.["data-testid"] === "bot-card-model")
+ .findAll((n) => n.props?.["data-testid"] === tid.botCardModel)
.map((n) => {
const c = n.props.children
return typeof c === "string" ? c : Array.isArray(c) ? c.join("") : String(c)
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
index bce270ca8..9666ab017 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.test.ts
+++ b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
@@ -2,9 +2,10 @@ import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { beforeEach, describe, expect, it, vi } from "vitest"
import type { BotSummary } from "@/hooks/community/use-bots"
+import { tid } from "@/lib/community/testids"
import type { BotListController, BotMachineGroup } from "./bot-list-types"
-const mocks = vi.hoisted(() => ({ heatmap: vi.fn() }))
+const mocks = vi.hoisted(() => ({ usage: vi.fn(), quota: vi.fn() }))
vi.mock("lucide-react", () => ({
Activity: "activity-icon",
@@ -19,10 +20,22 @@ vi.mock("@/components/avatar", () => ({
vi.mock("@/components/provider-logo", () => ({
ProviderLogo: (props: unknown) => React.createElement("provider", props as Record<string, unknown>),
}))
-vi.mock("./bot-activity-heatmap", () => ({
- BotActivityHeatmap: (props: unknown) => {
- mocks.heatmap(props)
- return React.createElement("heatmap", props as Record<string, unknown>)
+vi.mock("./bot-token-usage-chart", () => ({
+ usageDayPresentation: (day: NonNullable<BotSummary["usage"]>["days"][number]) => ({
+ knownTotal: Object.values(day.metrics).reduce(
+ (sum, metric) => sum + (metric ?? 0),
+ 0,
+ ),
+ }),
+ BotTokenUsageChart: (props: unknown) => {
+ mocks.usage(props)
+ return React.createElement("usage-chart", props as Record<string, unknown>)
+ },
+}))
+vi.mock("./bot-quota-summary", () => ({
+ MachineQuotaSummary: (props: unknown) => {
+ mocks.quota(props)
+ return React.createElement("quota-summary", props as Record<string, unknown>)
},
}))
vi.mock("@/components/ui/card", () => ({
@@ -108,13 +121,18 @@ describe("renderBotMachineGroup", () => {
expect(element.props.className).toBe(
"flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500 ",
)
- expect(renderer.root.findAllByProps({ className: "flex items-center gap-2 px-1" }))
+ expect(renderer.root.findAllByProps({ className: "flex flex-col gap-1 px-1" }))
.toHaveLength(1)
expect(renderer.root.findAllByProps({ className: "flex flex-col gap-3" }))
.toHaveLength(1)
expect(renderer.root.findByType("card").props.className).toBe("flex flex-col gap-3 p-4")
expect(renderer.root.findAllByProps({ className: "flex items-start justify-between gap-3" }))
.toHaveLength(1)
+ expect(renderer.root.findAllByProps({
+ className: "flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end",
+ })).toHaveLength(1)
+ expect(renderer.root.findAllByProps({ className: "basis-full sm:ml-auto sm:basis-auto" }))
+ .toHaveLength(0)
expect(renderer.root.findByProps({ "aria-label": "Collapse My Mac" }).props["aria-expanded"])
.toBe(true)
expect(renderer.root.findByType("avatar").props).toEqual(expect.objectContaining({
@@ -124,8 +142,9 @@ describe("renderBotMachineGroup", () => {
size: 40,
}))
expect(renderer.root.findByType("provider").props.provider).toBe("claude")
- expect(renderer.root.findByProps({ "data-testid": "bot-card-model" }).children).toEqual(["opus-4-6"])
- expect(mocks.heatmap).toHaveBeenCalledWith({ days: [], className: "self-center" })
+ expect(renderer.root.findByProps({ "data-testid": tid.botCardModel }).children).toEqual(["opus-4-6"])
+ expect(mocks.usage).not.toHaveBeenCalled()
+ expect(mocks.quota).toHaveBeenCalledWith({ machineId: "mac1", entries: undefined })
const reconnect = renderer.root.findAllByType("button").find((node) =>
node.children.includes("Bring online"))!
@@ -164,6 +183,80 @@ describe("renderBotMachineGroup", () => {
.toHaveLength(1)
})
+ it("projects bot-owned usage on one machine scale and machine-scoped quota once", () => {
+ const usage = {
+ capability: "supported" as const,
+ days: [{
+ day: "2026-08-29",
+ period: "closed" as const,
+ metrics: {
+ input: 20,
+ output: 10,
+ cache: 0,
+ },
+ }],
+ }
+ const largerUsage = {
+ capability: "supported" as const,
+ days: [{
+ day: "2026-08-29",
+ period: "closed" as const,
+ metrics: {
+ input: 50,
+ output: 20,
+ cache: 30,
+ },
+ }],
+ }
+ const codexQuota = {
+ scope: { kind: "machine_backend" as const, machineId: "mac1", agentBackendId: "codex" },
+ capability: "supported" as const,
+ runtimeState: "healthy" as const,
+ snapshot: { status: "pending" as const },
+ }
+ const claudeQuota = {
+ scope: { kind: "machine_backend" as const, machineId: "mac1", agentBackendId: "claude" },
+ capability: "supported" as const,
+ runtimeState: "healthy" as const,
+ snapshot: { status: "pending" as const },
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(renderBotMachineGroup(
+ group({
+ machine: {
+ id: "mac1",
+ displayName: "My Mac",
+ status: "online",
+ quota: [codexQuota, claudeQuota],
+ } as BotMachineGroup["machine"],
+ bots: [
+ bot({ id: "smaller", runtime: "codex", usage }),
+ bot({ id: "larger", runtime: "claude", usage: largerUsage }),
+ ],
+ }),
+ controller(),
+ ))
+ })
+ expect(mocks.usage).toHaveBeenNthCalledWith(1, {
+ botId: "smaller",
+ usage,
+ scaleMaxTokens: 100,
+ })
+ expect(mocks.usage).toHaveBeenNthCalledWith(2, {
+ botId: "larger",
+ usage: largerUsage,
+ scaleMaxTokens: 100,
+ })
+ expect(renderer.root.findAllByProps({ className: "basis-full sm:ml-auto sm:basis-auto" }))
+ .toHaveLength(2)
+ expect(mocks.quota).toHaveBeenCalledTimes(1)
+ expect(mocks.quota).toHaveBeenCalledWith({
+ machineId: "mac1",
+ entries: [codexQuota, claudeQuota],
+ })
+ })
+
it("omits reconnect for an online bot even when its machine resolves", () => {
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsx
index 749dca706..5ca9953c2 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx
+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx
@@ -12,7 +12,8 @@ import {
} from "@/components/ui/dropdown-menu"
import { formatAwakeDuration } from "@/lib/community/format-time"
import { tid } from "@/lib/community/testids"
-import { BotActivityHeatmap } from "./bot-activity-heatmap"
+import { MachineQuotaSummary } from "./bot-quota-summary"
+import { BotTokenUsageChart, usageDayPresentation } from "./bot-token-usage-chart"
import type { BotListController, BotMachineGroup } from "./bot-list-types"
export function renderBotMachineGroup(
@@ -22,6 +23,11 @@ export function renderBotMachineGroup(
const machineOnline = isPresenceOnline(machine?.status)
const collapsed = controller.collapsedMachines.has(machineId)
const label = controller.machineName(machineId)
+ const usageScaleMax = Math.max(0, ...bots.flatMap((bot) => (
+ bot.usage?.capability === "supported"
+ ? bot.usage.days.map((day) => usageDayPresentation(day).knownTotal)
+ : []
+ )))
return (
<div
key={machineId}
@@ -33,44 +39,49 @@ export function renderBotMachineGroup(
controller.highlightId === machineId ? "bg-primary/5 ring-2 ring-primary/40" : "",
].join(" ")}
>
- <div className="flex items-center gap-2 px-1">
- <button
- type="button"
- className="flex min-w-0 items-center gap-2 rounded-md text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- aria-expanded={!collapsed}
- aria-label={`${collapsed ? "Expand" : "Collapse"} ${label}`}
- onClick={() => {
- controller.setCollapsedMachines((current) => {
- const next = new Set(current)
- if (next.has(machineId)) next.delete(machineId)
- else next.add(machineId)
- return next
- })
- }}
- >
- <ChevronDown
- className={`size-3 shrink-0 text-muted-foreground transition-transform ${collapsed ? "-rotate-90" : ""}`}
- />
- <Monitor className="size-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate font-mono text-xs font-medium text-muted-foreground">
- {label}
- </span>
- <span
- className={[
- "inline-block size-1.5 shrink-0 rounded-full",
- machineOnline ? "bg-status-online" : "bg-muted-foreground",
- ].join(" ")}
- />
- </button>
- <Button
- variant="ghost"
- size="sm"
- className="ml-auto h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"
- onClick={() => controller.setConfirmResetMachine(machineId)}
- >
- <RotateCcw className="size-3.5" />
- Reset all
- </Button>
+ <div className="flex flex-col gap-1 px-1">
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ className="flex min-w-0 items-center gap-2 rounded-md text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ aria-expanded={!collapsed}
+ aria-label={`${collapsed ? "Expand" : "Collapse"} ${label}`}
+ onClick={() => {
+ controller.setCollapsedMachines((current) => {
+ const next = new Set(current)
+ if (next.has(machineId)) next.delete(machineId)
+ else next.add(machineId)
+ return next
+ })
+ }}
+ >
+ <ChevronDown
+ className={`size-3 shrink-0 text-muted-foreground transition-transform ${collapsed ? "-rotate-90" : ""}`}
+ />
+ <Monitor className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-mono text-xs font-medium text-muted-foreground">
+ {label}
+ </span>
+ <span
+ className={[
+ "inline-block size-1.5 shrink-0 rounded-full",
+ machineOnline ? "bg-status-online" : "bg-muted-foreground",
+ ].join(" ")}
+ />
+ </button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"
+ onClick={() => controller.setConfirmResetMachine(machineId)}
+ >
+ <RotateCcw className="size-3.5" />
+ Reset all
+ </Button>
+ </div>
+ <div className="pl-5">
+ <MachineQuotaSummary machineId={machineId} entries={machine?.quota} />
+ </div>
</div>
<div className="flex flex-col gap-3" hidden={collapsed}>
{bots.map((bot) => {
@@ -79,8 +90,8 @@ export function renderBotMachineGroup(
<Card key={bot.id} className="flex flex-col gap-3 p-4">
<div className="flex items-start justify-between gap-3">
<AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />
- <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5">
- <div className="flex min-w-55 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end">
+ <div className="flex min-w-0 flex-1 flex-col gap-1 sm:min-w-55">
<div className="flex items-center gap-2">
<span className="truncate text-[15px] font-medium text-foreground">
{bot.name}
@@ -122,12 +133,12 @@ export function renderBotMachineGroup(
</span>
<span aria-hidden className="shrink-0">·</span>
{formatModelLabel(bot.runtime, bot.modelName) ? (
- <span data-testid="bot-card-model" className="font-mono">
+ <span data-testid={tid.botCardModel} className="font-mono">
{formatModelLabel(bot.runtime, bot.modelName)}
</span>
) : (
<span
- data-testid="bot-card-model"
+ data-testid={tid.botCardModel}
className="font-mono text-muted-foreground/70"
title="No model set — uses the machine's local default"
>
@@ -144,7 +155,15 @@ export function renderBotMachineGroup(
)}
</span>
</div>
- <BotActivityHeatmap days={bot.dailyActivity} className="self-center" />
+ {bot.usage?.capability === "supported" && (
+ <div className="basis-full sm:ml-auto sm:basis-auto">
+ <BotTokenUsageChart
+ botId={bot.id}
+ usage={bot.usage}
+ scaleMaxTokens={usageScaleMax}
+ />
+ </div>
+ )}
</div>
<DropdownMenu>
<DropdownMenuTrigger
diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.ts
index 65c2681a4..c8db1c9b8 100644
--- a/src/web/src/components/community/bots/bot-list-types.ts
+++ b/src/web/src/components/community/bots/bot-list-types.ts
@@ -1,6 +1,6 @@
import type { Dispatch, SetStateAction } from "react"
-import type { CommunityMachineSummary } from "@alook/shared"
import type { BotSummary } from "@/hooks/community/use-bots"
+import type { MachineSummary } from "@/hooks/community/use-machines"
export type BotListProps = {
onBack?: () => void
@@ -8,14 +8,14 @@ export type BotListProps = {
export type BotMachineGroup = {
machineId: string
- machine: CommunityMachineSummary | null
+ machine: MachineSummary | null
bots: BotSummary[]
}
export type BotListController = {
bots: BotSummary[]
isLoading: boolean
- machines: CommunityMachineSummary[]
+ machines: MachineSummary[]
machinesLoading: boolean
onlineUserIds: ReadonlySet<string>
createOpen: boolean
diff --git a/src/web/src/components/community/bots/bot-list-view.test.ts b/src/web/src/components/community/bots/bot-list-view.test.ts
index 915047469..e6d053b5b 100644
--- a/src/web/src/components/community/bots/bot-list-view.test.ts
+++ b/src/web/src/components/community/bots/bot-list-view.test.ts
@@ -128,11 +128,14 @@ describe("renderBotListView", () => {
})).toHaveLength(1)
expect(renderer.root.findAllByProps({ className: "flex flex-col gap-3 p-4" }))
.toHaveLength(3)
+ expect(renderer.root.findAllByProps({
+ className: "flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end",
+ })).toHaveLength(3)
expect(renderer.root.findAllByProps({ className: "size-10 shrink-0 rounded-full" }))
.toHaveLength(3)
- expect(renderer.root.findAllByProps({ className: "h-3.5 w-28 rounded" }))
+ expect(renderer.root.findAllByProps({ className: "h-6 w-40 max-w-full rounded" }))
.toHaveLength(3)
- expect(renderer.root.findAllByProps({ className: "h-3 w-48 rounded" }))
+ expect(renderer.root.findAllByProps({ className: "h-4 w-48 max-w-full rounded" }))
.toHaveLength(3)
expect(renderer.root.findAllByProps({ className: "size-8 shrink-0 rounded-md" }))
.toHaveLength(3)
diff --git a/src/web/src/components/community/bots/bot-list-view.tsx b/src/web/src/components/community/bots/bot-list-view.tsx
index aba4c831e..4e9d4d8b9 100644
--- a/src/web/src/components/community/bots/bot-list-view.tsx
+++ b/src/web/src/components/community/bots/bot-list-view.tsx
@@ -13,9 +13,11 @@ function BotCardSkeleton() {
<Card className="flex flex-col gap-3 p-4">
<div className="flex items-start justify-between gap-3">
<Skeleton className="size-10 shrink-0 rounded-full" />
- <div className="flex min-w-0 flex-1 flex-col gap-2 py-0.5">
- <Skeleton className="h-3.5 w-28 rounded" />
- <Skeleton className="h-3 w-48 rounded" />
+ <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5 sm:items-end">
+ <div className="flex min-w-0 flex-1 flex-col gap-1 sm:min-w-55">
+ <Skeleton className="h-6 w-40 max-w-full rounded" />
+ <Skeleton className="h-4 w-48 max-w-full rounded" />
+ </div>
</div>
<Skeleton className="size-8 shrink-0 rounded-md" />
</div>
diff --git a/src/web/src/components/community/bots/bot-quota-summary.test.ts b/src/web/src/components/community/bots/bot-quota-summary.test.ts
new file mode 100644
index 000000000..0062a6979
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-quota-summary.test.ts
@@ -0,0 +1,205 @@
+import React, { createContext, useContext } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+import type { QuotaLimit } from "@alook/shared"
+import type { MachineBackendQuota } from "@/hooks/community/use-machines"
+
+vi.mock("lucide-react", () => ({ ChevronDown: "chevron-icon" }))
+vi.mock("@/components/provider-logo", () => ({
+ ProviderLogo: (props: unknown) => React.createElement("provider-logo", props as Record<string, unknown>),
+}))
+
+const PopoverContext = createContext<{
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}>({ open: false, onOpenChange: () => undefined })
+
+vi.mock("@/components/ui/popover", () => ({
+ Popover: ({ open, onOpenChange, children }: React.PropsWithChildren<{
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ }>) => React.createElement(PopoverContext.Provider, { value: { open, onOpenChange } }, children),
+ PopoverTrigger: ({ render }: { render: React.ReactElement }) => {
+ const context = useContext(PopoverContext)
+ return React.cloneElement(render, { onClick: () => context.onOpenChange(!context.open) })
+ },
+ PopoverContent: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => {
+ const context = useContext(PopoverContext)
+ return context.open ? React.createElement("popover-content", props, children) : null
+ },
+}))
+
+vi.mock("@/lib/time", () => ({ timeAgo: () => "2m ago" }))
+
+import {
+ MachineQuotaSummary,
+ groupQuotaLimits,
+ quotaBucketIdentity,
+ remainingPercent,
+ selectMostConstrainedLimit,
+} from "./bot-quota-summary"
+
+function limit({
+ limitId = "primary",
+ productId = "spark",
+ productName = "Spark",
+ modelId = "gpt-5.3-codex-spark",
+ window = { kind: "rolling" as const, durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ usedPercent = 82,
+ resetsAt,
+}: Partial<{
+ limitId: string
+ productId: string
+ productName: string
+ modelId: string
+ window: QuotaLimit["bucket"]["window"]
+ usedPercent: number
+ resetsAt: string
+}> = {}): QuotaLimit {
+ return {
+ bucket: {
+ limitId,
+ product: { kind: "reported", id: productId, displayName: productName },
+ model: { kind: "reported", id: modelId },
+ window,
+ },
+ usedPercent,
+ ...(resetsAt ? { resetsAt } : {}),
+ }
+}
+
+function quotaEntry(
+ limits: QuotaLimit[],
+ status: "available" | "stale" = "available",
+ backend = "codex",
+): MachineBackendQuota {
+ return {
+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: backend },
+ capability: "supported",
+ runtimeState: "healthy",
+ snapshot: {
+ status,
+ observedAt: "2026-08-29T00:00:00.000Z",
+ planName: "Plus",
+ limits,
+ },
+ }
+}
+
+function render(entries?: MachineBackendQuota[]) {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(MachineQuotaSummary, { machineId: "m1", entries }),
+ )
+ })
+ return renderer
+}
+
+function text(node: TestRenderer.ReactTestInstance): string {
+ return node.children.map((child) => typeof child === "string" ? child : text(child)).join(" ")
+}
+
+describe("quota helpers", () => {
+ it("uses only canonical identity fields for stable bucket keys", () => {
+ const first = limit({ usedPercent: 82, productName: "Spark", resetsAt: "2026-08-30T00:00:00Z" })
+ const relabeled = limit({ usedPercent: 10, productName: "Spark Plus", resetsAt: "2026-09-01T00:00:00Z" })
+ expect(quotaBucketIdentity(first)).toBe(quotaBucketIdentity(relabeled))
+ })
+
+ it("selects lowest remaining, then earliest reset, then canonical identity", () => {
+ const loose = limit({ limitId: "loose", usedPercent: 20 })
+ const later = limit({ limitId: "later", usedPercent: 80, resetsAt: "2026-08-31T00:00:00Z" })
+ const sooner = limit({ limitId: "sooner", usedPercent: 80, resetsAt: "2026-08-30T00:00:00Z" })
+ expect(selectMostConstrainedLimit([loose, later, sooner])).toBe(sooner)
+ expect(remainingPercent(sooner)).toBe(20)
+
+ const a = limit({ limitId: "a", usedPercent: 80 })
+ const b = limit({ limitId: "b", usedPercent: 80 })
+ expect(selectMostConstrainedLimit([b, a])).toBe(a)
+ })
+
+ it("keeps Spark rolling and weekly windows distinct in one product/model group", () => {
+ const rolling = limit()
+ const weekly = limit({
+ limitId: "weekly",
+ window: { kind: "calendar", period: "week", displayName: "Weekly usage limit" },
+ usedPercent: 55.5,
+ })
+ const groups = groupQuotaLimits([rolling, weekly])
+ expect(groups).toHaveLength(1)
+ expect(groups[0]!.limits.map(quotaBucketIdentity)).toHaveLength(2)
+ expect(new Set(groups[0]!.limits.map(quotaBucketIdentity)).size).toBe(2)
+ })
+})
+
+describe("MachineQuotaSummary", () => {
+ it("renders one machine-level summary and groups every backend in complete detail", () => {
+ const rolling = limit({ usedPercent: 82 })
+ const weekly = limit({
+ limitId: "weekly",
+ window: { kind: "calendar", period: "week", displayName: "Weekly usage limit" },
+ usedPercent: 55.5,
+ })
+ const codex = quotaEntry([weekly, rolling])
+ const pi: MachineBackendQuota = {
+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "pi" },
+ capability: "unsupported",
+ runtimeState: "healthy",
+ snapshot: { status: "pending" },
+ }
+ const claude: MachineBackendQuota = {
+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "claude" },
+ capability: "supported",
+ runtimeState: "healthy",
+ snapshot: { status: "pending" },
+ }
+ const renderer = render([pi, codex, claude])
+ const trigger = renderer.root.findByProps({ "data-testid": "community-machine-quota-m1" })
+ expect(trigger.props["aria-expanded"]).toBe(false)
+ expect(text(trigger)).toContain("Quota · Spark · 18% left · 2 limits")
+
+ act(() => trigger.props.onClick())
+ expect(renderer.root.findByProps({ "data-testid": "community-machine-quota-m1" }).props["aria-expanded"])
+ .toBe(true)
+ const detail = renderer.root.findByProps({ "data-testid": "community-machine-quota-detail-m1" })
+ expect(text(detail)).toContain("Machine quota")
+ expect(text(detail)).toContain("Claude")
+ expect(text(detail)).toContain("Codex")
+ expect(text(detail)).toContain("Pi")
+ expect(text(detail)).toContain("Pending")
+ expect(text(detail)).toContain("Not supported")
+ expect(text(detail)).toContain("5 hour usage limit")
+ expect(text(detail)).toContain("Weekly usage limit")
+ expect(text(detail)).toContain("18% left")
+ expect(text(detail)).toContain("44.5% left")
+ expect(text(detail)).toContain("2m ago")
+ expect(detail.findAllByType("provider-logo").map((node) => node.props.provider))
+ .toEqual(["claude", "codex", "pi"])
+ })
+
+ it("shows one limit's server-authored window and stale state", () => {
+ const renderer = render([quotaEntry([limit({ usedPercent: 37.5 })], "stale")])
+ const trigger = renderer.root.findByProps({ "data-testid": "community-machine-quota-m1" })
+ expect(text(trigger)).toContain("Quota · Spark · 62.5% left")
+ expect(text(trigger)).toContain("Stale")
+ })
+
+ it("renders honest fixed-height placeholders for missing capability states", () => {
+ expect(text(render().root)).toContain("Quota unavailable")
+ const unsupported = render([{
+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "pi" },
+ capability: "unsupported",
+ runtimeState: "healthy",
+ snapshot: { status: "pending" },
+ }])
+ expect(text(unsupported.root)).toContain("Quota not supported")
+ expect(unsupported.root.findByType("provider-logo").props.provider).toBe("pi")
+ expect(text(render([{
+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "codex" },
+ capability: "supported",
+ runtimeState: "offline",
+ snapshot: { status: "pending" },
+ }]).root)).toContain("Quota pending")
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-quota-summary.tsx b/src/web/src/components/community/bots/bot-quota-summary.tsx
new file mode 100644
index 000000000..673fec19d
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-quota-summary.tsx
@@ -0,0 +1,323 @@
+"use client"
+
+import { useState } from "react"
+import { ChevronDown } from "lucide-react"
+import type { QuotaLimit } from "@alook/shared"
+import { ProviderLogo } from "@/components/provider-logo"
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover"
+import { timeAgo } from "@/lib/time"
+import { tid } from "@/lib/community/testids"
+import type { MachineBackendQuota } from "@/hooks/community/use-machines"
+
+const RESET_FMT = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+})
+
+function productIdentity(limit: QuotaLimit): string {
+ return limit.bucket.product.kind === "reported"
+ ? `reported:${limit.bucket.product.id}`
+ : "unknown"
+}
+
+function modelIdentity(limit: QuotaLimit): string {
+ const model = limit.bucket.model
+ return model.kind === "reported" ? `reported:${model.id}` : model.kind
+}
+
+function windowIdentity(limit: QuotaLimit): string {
+ const window = limit.bucket.window
+ if (window.kind === "rolling") return `rolling:${window.durationSeconds}`
+ if (window.kind === "calendar") return `calendar:${window.period}`
+ return `provider_defined:${window.id}:${window.durationSeconds === undefined ? "absent" : window.durationSeconds}`
+}
+
+export function quotaBucketIdentity(limit: QuotaLimit): string {
+ return [
+ productIdentity(limit),
+ modelIdentity(limit),
+ windowIdentity(limit),
+ limit.bucket.limitId,
+ ].join("\u0000")
+}
+
+function decimalPlaces(value: number): number {
+ const source = String(value).toLowerCase()
+ if (source.includes("e-")) {
+ const [coefficient, exponent] = source.split("e-")
+ return Number(exponent) + (coefficient.split(".")[1]?.length ?? 0)
+ }
+ return source.split(".")[1]?.length ?? 0
+}
+
+export function remainingPercent(limit: QuotaLimit): number {
+ const precision = Math.min(12, decimalPlaces(limit.usedPercent))
+ return Number((100 - limit.usedPercent).toFixed(precision))
+}
+
+function percentLabel(limit: QuotaLimit): string {
+ return `${remainingPercent(limit)}% left`
+}
+
+function resetTimestamp(limit: QuotaLimit): number {
+ if (!limit.resetsAt) return Number.POSITIVE_INFINITY
+ const parsed = Date.parse(limit.resetsAt)
+ return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed
+}
+
+export function selectMostConstrainedLimit(limits: QuotaLimit[]): QuotaLimit | null {
+ return limits.toSorted((a, b) => {
+ const remaining = remainingPercent(a) - remainingPercent(b)
+ if (remaining !== 0) return remaining
+ const resetA = resetTimestamp(a)
+ const resetB = resetTimestamp(b)
+ if (resetA !== resetB) return resetA < resetB ? -1 : 1
+ return quotaBucketIdentity(a).localeCompare(quotaBucketIdentity(b))
+ })[0] ?? null
+}
+
+function productLabel(limit: QuotaLimit): string {
+ return limit.bucket.product.displayName
+}
+
+function modelLabel(limit: QuotaLimit): string | null {
+ const model = limit.bucket.model
+ if (model.kind === "not_applicable") return null
+ return model.kind === "unknown" ? "Unknown model" : model.id
+}
+
+function resetLabel(limit: QuotaLimit): string {
+ if (!limit.resetsAt) return "Reset unavailable"
+ const parsed = new Date(limit.resetsAt)
+ return Number.isNaN(parsed.getTime())
+ ? "Reset unavailable"
+ : `Resets ${RESET_FMT.format(parsed)}`
+}
+
+type QuotaGroup = {
+ key: string
+ product: string
+ model: string | null
+ limits: QuotaLimit[]
+}
+
+export function groupQuotaLimits(limits: QuotaLimit[]): QuotaGroup[] {
+ const groups = new Map<string, QuotaGroup>()
+ for (const limit of limits) {
+ const key = `${productIdentity(limit)}\u0000${modelIdentity(limit)}`
+ const current = groups.get(key)
+ if (current) current.limits.push(limit)
+ else groups.set(key, {
+ key,
+ product: productLabel(limit),
+ model: modelLabel(limit),
+ limits: [limit],
+ })
+ }
+ return [...groups.values()]
+}
+
+function hasQuotaLimits(entry: MachineBackendQuota): boolean {
+ return (
+ entry.capability === "supported"
+ && (entry.snapshot.status === "available" || entry.snapshot.status === "stale")
+ && entry.snapshot.limits.length > 0
+ )
+}
+
+function quotaPlaceholder(entries: MachineBackendQuota[] | undefined): string | null {
+ if (entries?.some(hasQuotaLimits)) return null
+ if (!entries?.length) return "Quota unavailable"
+ if (entries.some((entry) => entry.capability === "supported" && entry.snapshot.status === "pending")) {
+ return "Quota pending"
+ }
+ if (entries.every((entry) => entry.capability === "unsupported")) return "Quota not supported"
+ return "Quota unavailable"
+}
+
+function backendLabel(backendId: string): string {
+ return backendId
+ .split(/[-_]/)
+ .filter(Boolean)
+ .map((part) => part[0]?.toUpperCase() + part.slice(1))
+ .join(" ")
+}
+
+function backendPlaceholder(entry: MachineBackendQuota): string {
+ if (entry.capability === "unsupported") return "Not supported"
+ if (entry.capability === "supported" && entry.snapshot.status === "pending") return "Pending"
+ return "Unavailable"
+}
+
+function constrainedEntry(entries: MachineBackendQuota[]): {
+ entry: MachineBackendQuota
+ limit: QuotaLimit
+} | null {
+ const usable = entries.filter(hasQuotaLimits)
+ const limit = selectMostConstrainedLimit(usable.flatMap((entry) => (
+ entry.snapshot.status === "available" || entry.snapshot.status === "stale"
+ ? entry.snapshot.limits
+ : []
+ )))
+ if (!limit) return null
+ const entry = usable.find((candidate) => (
+ (candidate.snapshot.status === "available" || candidate.snapshot.status === "stale")
+ && candidate.snapshot.limits.includes(limit)
+ ))
+ return entry ? { entry, limit } : null
+}
+
+export function MachineQuotaSummary({
+ machineId,
+ entries,
+}: {
+ machineId: string
+ entries?: MachineBackendQuota[]
+}) {
+ const [open, setOpen] = useState(false)
+ const placeholder = quotaPlaceholder(entries)
+ if (placeholder || !entries) {
+ return (
+ <div
+ data-testid={tid.machineQuota(machineId)}
+ className="flex h-7 min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
+ >
+ {entries?.map((entry) => (
+ <ProviderLogo
+ key={entry.scope.agentBackendId}
+ provider={entry.scope.agentBackendId}
+ className="size-3.5 shrink-0"
+ />
+ ))}
+ <span className="truncate">{placeholder ?? "Quota unavailable"}</span>
+ </div>
+ )
+ }
+
+ const constrained = constrainedEntry(entries)
+ if (!constrained) return null
+ const limitCount = entries.reduce((count, entry) => (
+ entry.snapshot.status === "available" || entry.snapshot.status === "stale"
+ ? count + entry.snapshot.limits.length
+ : count
+ ), 0)
+ const stale = constrained.entry.snapshot.status === "stale"
+ const summary = [
+ "Quota",
+ productLabel(constrained.limit),
+ percentLabel(constrained.limit),
+ ...(limitCount > 1 ? [`${limitCount} limits`] : []),
+ ].join(" · ")
+ const sortedEntries = entries.toSorted((a, b) => (
+ a.scope.agentBackendId.localeCompare(b.scope.agentBackendId)
+ ))
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-label={`Quota details: ${summary}${stale ? ". Stale" : ""}`}
+ data-testid={tid.machineQuota(machineId)}
+ className="group flex h-11 max-w-full min-w-0 items-center gap-1.5 rounded-md text-left text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:h-7"
+ >
+ <ProviderLogo
+ provider={constrained.entry.scope.agentBackendId}
+ className="size-3.5 shrink-0"
+ />
+ <span className="truncate text-foreground/85">{summary}</span>
+ {stale && <span className="shrink-0 text-warning">Stale</span>}
+ <ChevronDown className="size-3 shrink-0 transition-transform group-data-popup-open:rotate-180" />
+ </button>
+ }
+ />
+ <PopoverContent
+ align="start"
+ className="max-h-[min(32rem,calc(100vh-2rem))] w-80 max-w-[calc(100vw-1rem)] overflow-y-auto p-4 thin-scrollbar"
+ data-testid={tid.machineQuotaDetail(machineId)}
+ >
+ <div className="flex flex-col gap-4">
+ <h3 className="text-sm font-medium text-foreground">Machine quota</h3>
+ {sortedEntries.map((entry) => {
+ const snapshot = entry.snapshot
+ if (snapshot.status !== "available" && snapshot.status !== "stale") {
+ return (
+ <section key={entry.scope.agentBackendId} className="flex flex-col gap-2">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <ProviderLogo provider={entry.scope.agentBackendId} className="size-3.5 shrink-0" />
+ <span className="truncate text-xs font-medium text-foreground">
+ {backendLabel(entry.scope.agentBackendId)}
+ </span>
+ </div>
+ <div className="rounded-md border border-border/70 px-3 py-2 text-xs text-muted-foreground">
+ {backendPlaceholder(entry)}
+ </div>
+ </section>
+ )
+ }
+ const groups = groupQuotaLimits(snapshot.limits)
+ return (
+ <section key={entry.scope.agentBackendId} className="flex flex-col gap-2">
+ <div className="flex min-w-0 items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <ProviderLogo provider={entry.scope.agentBackendId} className="size-3.5 shrink-0" />
+ <span className="truncate text-xs font-medium text-foreground">
+ {backendLabel(entry.scope.agentBackendId)}
+ </span>
+ </div>
+ <span className={snapshot.status === "stale" ? "shrink-0 text-[11px] text-warning" : "shrink-0 text-[11px] text-muted-foreground"}>
+ {[snapshot.planName, snapshot.status === "stale" ? "Stale" : null]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ </div>
+ {groups.length === 0 ? (
+ <div className="rounded-md border border-border/70 px-3 py-2 text-xs text-muted-foreground">
+ Unavailable
+ </div>
+ ) : groups.map((group) => (
+ <div key={group.key} className="flex flex-col gap-2">
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate text-xs text-foreground">{group.product}</span>
+ {group.model && (
+ <span className="truncate font-mono text-[11px] text-muted-foreground">
+ {group.model}
+ </span>
+ )}
+ </div>
+ <div className="flex flex-col divide-y divide-border/60 rounded-md border border-border/70">
+ {group.limits.map((limit) => (
+ <div key={quotaBucketIdentity(limit)} className="flex flex-col gap-1 p-3">
+ <div className="flex items-start justify-between gap-4">
+ <span className="text-xs text-foreground">
+ {limit.bucket.window.displayName}
+ </span>
+ <span className="shrink-0 font-mono text-xs font-medium tabular-nums text-foreground">
+ {percentLabel(limit)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between gap-4 text-[11px] text-muted-foreground">
+ <span>{resetLabel(limit)}</span>
+ <span className="shrink-0">Updated {timeAgo(snapshot.observedAt)}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ </section>
+ )
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.test.ts b/src/web/src/components/community/bots/bot-token-usage-chart.test.ts
new file mode 100644
index 000000000..53188722c
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-token-usage-chart.test.ts
@@ -0,0 +1,127 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+import type { BotTokenUsage, BotUsageDay } from "@/hooks/community/use-bots"
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: React.PropsWithChildren) => React.createElement(React.Fragment, null, children),
+ TooltipTrigger: ({ render }: { render: React.ReactElement }) => React.cloneElement(render),
+ TooltipContent: ({ children }: React.PropsWithChildren) =>
+ React.createElement("tooltip-content", null, children),
+}))
+
+import {
+ BotTokenUsageChart,
+ normalizedBarHeight,
+ usageDayPresentation,
+} from "./bot-token-usage-chart"
+
+const unavailable = null
+const complete = (tokens: number) => tokens
+
+function usageDay(
+ day: string,
+ metrics: BotUsageDay["metrics"],
+ period: BotUsageDay["period"] = "closed",
+): BotUsageDay {
+ return { day, period, metrics }
+}
+
+const sevenDays = (last: BotUsageDay): BotUsageDay[] => [
+ usageDay("2026-08-23", { input: complete(5), output: complete(5), cache: complete(0) }),
+ usageDay("2026-08-24", { input: complete(10), output: complete(10), cache: complete(0) }),
+ usageDay("2026-08-25", { input: unavailable, output: unavailable, cache: unavailable }),
+ usageDay("2026-08-26", { input: complete(20), output: complete(10), cache: unavailable }),
+ usageDay("2026-08-27", { input: complete(0), output: complete(0), cache: complete(0) }),
+ usageDay("2026-08-28", { input: complete(40), output: complete(40), cache: complete(20) }),
+ last,
+]
+
+function render(usage?: BotTokenUsage) {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotTokenUsageChart, { botId: "bot_1", usage }),
+ )
+ })
+ return renderer
+}
+
+function text(node: TestRenderer.ReactTestInstance): string {
+ return node.children.map((child) => typeof child === "string" ? child : text(child)).join(" ")
+}
+
+describe("usage chart normalization", () => {
+ it("keeps exact zero and unavailable distinct without projecting coverage labels", () => {
+ expect(usageDayPresentation(usageDay("2026-08-29", {
+ input: complete(0), output: complete(0), cache: complete(0),
+ }))).toEqual({ knownTotal: 0, unavailable: false })
+
+ expect(usageDayPresentation(usageDay("2026-08-29", {
+ input: complete(12), output: complete(3), cache: unavailable,
+ }))).toEqual({ knownTotal: 15, unavailable: false })
+
+ expect(usageDayPresentation(usageDay("2026-08-29", {
+ input: unavailable, output: unavailable, cache: unavailable,
+ }))).toEqual({ knownTotal: 0, unavailable: true })
+ })
+
+ it("normalizes all-zero, one-nonzero, and extreme differences to the seven-day maximum", () => {
+ expect(normalizedBarHeight(0, 0)).toBe(0)
+ expect(normalizedBarHeight(0, 900)).toBe(0)
+ expect(normalizedBarHeight(900, 900)).toBe(100)
+ expect(normalizedBarHeight(1, 1_000_000)).toBeCloseTo(0.0001, 8)
+ })
+})
+
+describe("BotTokenUsageChart", () => {
+ it("renders seven keyboard/tap targets oldest-to-newest without a persistent x-axis", () => {
+ const usage: BotTokenUsage = {
+ capability: "supported",
+ days: sevenDays(usageDay(
+ "2026-08-29",
+ { input: complete(8), output: complete(2), cache: complete(0) },
+ "in_progress",
+ )),
+ }
+ const renderer = render(usage)
+ const targets = renderer.root.findAll((node) => (
+ node.props.role === "listitem" && node.props["data-testid"]
+ ))
+ expect(targets).toHaveLength(7)
+ expect(targets[0]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-23")
+ expect(targets[6]!.props["data-testid"]).toBe("community-bot-usage-day-bot_1-2026-08-29")
+ expect(targets[6]!.props["aria-label"]).toContain("Input 8")
+ expect(targets[6]!.props["aria-label"]).toContain("Output 2")
+ expect(renderer.root.findAll((node) => String(node.props.className).includes("h-10.5")))
+ .not.toHaveLength(0)
+ expect(text(renderer.root)).not.toContain("8/23")
+ expect(text(renderer.root)).not.toContain("Today")
+ expect(text(renderer.root)).not.toContain("Tokens")
+ })
+
+ it("shares one proportional seven-day scale without coverage annotations or background pipes", () => {
+ const usage: BotTokenUsage = {
+ capability: "supported",
+ days: sevenDays(usageDay(
+ "2026-08-29",
+ { input: complete(50), output: complete(0), cache: complete(0) },
+ "in_progress",
+ )),
+ }
+ const renderer = render(usage)
+ const heightNodes = renderer.root.findAll((node) => typeof node.props.style?.height === "string")
+ expect(heightNodes.map((node) => node.props.style.height)).toContain("100%")
+ expect(heightNodes.map((node) => node.props.style.height)).toContain("50%")
+ expect(renderer.root.findAll((node) => String(node.props.className).includes("ring-inset")))
+ .toHaveLength(0)
+ })
+
+ it("omits missing and unsupported usage without reserving a chart slot", () => {
+ const unsupported = render({ capability: "unsupported", days: [] })
+ expect(unsupported.toJSON()).toBeNull()
+
+ const unknown = render()
+ expect(unknown.toJSON()).toBeNull()
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-token-usage-chart.tsx b/src/web/src/components/community/bots/bot-token-usage-chart.tsx
new file mode 100644
index 000000000..9ceeace7a
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-token-usage-chart.tsx
@@ -0,0 +1,242 @@
+"use client"
+
+import { useState } from "react"
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover"
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip"
+import { tid } from "@/lib/community/testids"
+import type { BotTokenUsage, BotUsageDay } from "@/hooks/community/use-bots"
+import type { DailyUsageMetric } from "@alook/shared"
+
+const TOKEN_FMT = new Intl.NumberFormat(undefined)
+const DAY_FMT = new Intl.DateTimeFormat(undefined, {
+ month: "short",
+ day: "numeric",
+ timeZone: "UTC",
+})
+const AXIS_DAY_FMT = new Intl.DateTimeFormat(undefined, {
+ month: "numeric",
+ day: "numeric",
+ timeZone: "UTC",
+})
+
+type MetricKey = "input" | "output" | "cache"
+
+const METRICS: Array<{
+ key: MetricKey
+ label: string
+ className: string
+}> = [
+ { key: "input", label: "Input", className: "bg-foreground/75" },
+ { key: "output", label: "Output", className: "bg-muted-foreground/75" },
+ { key: "cache", label: "Cache", className: "bg-foreground/25" },
+]
+
+function parseUtcDay(day: string): Date {
+ return new Date(`${day}T00:00:00.000Z`)
+}
+
+function dayLabel(day: BotUsageDay): string {
+ if (day.period === "in_progress") return "Today"
+ const parsed = parseUtcDay(day.day)
+ return Number.isNaN(parsed.getTime()) ? day.day : AXIS_DAY_FMT.format(parsed)
+}
+
+function fullDayLabel(day: BotUsageDay): string {
+ const parsed = parseUtcDay(day.day)
+ return Number.isNaN(parsed.getTime()) ? day.day : DAY_FMT.format(parsed)
+}
+
+function metricTokens(metric: DailyUsageMetric): number | null {
+ return metric
+}
+
+function metricLabel(metric: DailyUsageMetric): string {
+ if (metric === null) return "Unavailable"
+ return TOKEN_FMT.format(metric)
+}
+
+export type UsageDayPresentation = {
+ knownTotal: number
+ unavailable: boolean
+}
+
+export function usageDayPresentation(day: BotUsageDay): UsageDayPresentation {
+ const metrics = Object.values(day.metrics)
+ const known = metrics.flatMap((metric) => {
+ const tokens = metricTokens(metric)
+ return tokens === null ? [] : [tokens]
+ })
+ const knownTotal = known.reduce((sum, tokens) => sum + tokens, 0)
+ const unavailable = known.length === 0
+ return {
+ knownTotal,
+ unavailable,
+ }
+}
+
+export function normalizedBarHeight(total: number, maxTotal: number): number {
+ if (total <= 0 || maxTotal <= 0) return 0
+ return (total / maxTotal) * 100
+}
+
+function accessibleDayLabel(day: BotUsageDay): string {
+ return [
+ fullDayLabel(day),
+ `Input ${metricLabel(day.metrics.input)}`,
+ `Output ${metricLabel(day.metrics.output)}`,
+ `Cache ${metricLabel(day.metrics.cache)}`,
+ ].join(". ")
+}
+
+function UsageDayDetail({ day }: { day: BotUsageDay }) {
+ return (
+ <span className="flex min-w-44 flex-col gap-1">
+ <span className="font-medium">{fullDayLabel(day)}</span>
+ {METRICS.map((metric) => (
+ <span key={metric.key} className="flex items-center justify-between gap-4">
+ <span>{metric.label}</span>
+ <span className="font-mono tabular-nums">{metricLabel(day.metrics[metric.key])}</span>
+ </span>
+ ))}
+ </span>
+ )
+}
+
+function UsageBar({
+ day,
+ presentation,
+ maxKnownTotal,
+}: {
+ day: BotUsageDay
+ presentation: UsageDayPresentation
+ maxKnownTotal: number
+}) {
+ const totalHeight = normalizedBarHeight(presentation.knownTotal, maxKnownTotal)
+ return (
+ <span className="relative flex min-h-0 w-full flex-1 items-end justify-center">
+ <span
+ className="flex w-3 flex-col-reverse overflow-hidden rounded-sm"
+ style={{ height: `${totalHeight}%` }}
+ >
+ {METRICS.map((metric) => {
+ const tokens = metricTokens(day.metrics[metric.key])
+ if (!tokens || presentation.knownTotal === 0) return null
+ return (
+ <span
+ key={metric.key}
+ className={["w-full", metric.className].join(" ")}
+ style={{ flexGrow: tokens }}
+ />
+ )
+ })}
+ </span>
+ </span>
+ )
+}
+
+export function BotTokenUsageChart({
+ botId,
+ usage,
+ scaleMaxTokens,
+}: {
+ botId: string
+ usage?: BotTokenUsage
+ scaleMaxTokens?: number
+}) {
+ const [mobileOpen, setMobileOpen] = useState(false)
+ const [mobileDayIndex, setMobileDayIndex] = useState(6)
+ if (!usage || usage.capability !== "supported") return null
+
+ const presentations = usage.days.map(usageDayPresentation)
+ const maxKnownTotal = scaleMaxTokens
+ ?? Math.max(0, ...presentations.map((day) => day.knownTotal))
+
+ return (
+ <section
+ aria-label="Token usage over the last 7 days"
+ data-testid={tid.botUsage(botId)}
+ className="h-10.5 w-32 max-w-full"
+ >
+ <div className="relative grid h-full min-h-0 grid-cols-7 gap-1" role="list">
+ {usage.days.map((day, index) => {
+ const presentation = presentations[index]!
+ return (
+ <Tooltip key={day.day}>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ role="listitem"
+ aria-label={accessibleDayLabel(day)}
+ data-testid={tid.botUsageDay(botId, day.day)}
+ className="group hidden min-w-0 flex-col items-center gap-1 rounded-sm focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:flex"
+ >
+ <UsageBar day={day} presentation={presentation} maxKnownTotal={maxKnownTotal} />
+ </button>
+ }
+ />
+ <TooltipContent className="items-start">
+ <UsageDayDetail day={day} />
+ </TooltipContent>
+ </Tooltip>
+ )
+ })}
+ {usage.days.map((day, index) => (
+ <div
+ key={`mobile-${day.day}`}
+ role="listitem"
+ aria-label={accessibleDayLabel(day)}
+ className="group flex min-w-0 flex-col items-center gap-1 sm:hidden"
+ >
+ <UsageBar day={day} presentation={presentations[index]!} maxKnownTotal={maxKnownTotal} />
+ </div>
+ ))}
+ <Popover open={mobileOpen} onOpenChange={setMobileOpen}>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-label="Open token usage details"
+ aria-expanded={mobileOpen}
+ className="absolute inset-0 z-10 min-h-11 rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:hidden"
+ />
+ }
+ />
+ <PopoverContent
+ side="bottom"
+ align="end"
+ className="max-h-[calc(100vh-2rem)] w-72 max-w-[calc(100vw-1rem)] overflow-y-auto p-3 thin-scrollbar sm:hidden"
+ >
+ <div className="flex flex-col gap-3">
+ <div className="text-xs text-foreground">
+ <UsageDayDetail day={usage.days[mobileDayIndex] ?? usage.days.at(-1)!} />
+ </div>
+ <div className="flex flex-col border-t border-border/60 pt-2">
+ {usage.days.map((day, index) => (
+ <button
+ key={day.day}
+ type="button"
+ data-testid={tid.botUsageDay(botId, day.day)}
+ aria-pressed={index === mobileDayIndex}
+ onClick={() => setMobileDayIndex(index)}
+ className="flex h-11 items-center rounded-md px-2 text-left text-xs text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <span>{dayLabel(day)}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ </section>
+ )
+}
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 63f66a72e..a7de6c152 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -4,7 +4,22 @@ import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tan
import { apiFetch, readUploadError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { BotActivityDay } from "@/lib/community/models/people"
-import type { ReasoningEffort } from "@alook/shared"
+import type { DailyUsageMetric, ReasoningEffort } from "@alook/shared"
+
+export type BotUsageDay = {
+ day: string
+ period: "closed" | "in_progress"
+ metrics: {
+ input: DailyUsageMetric
+ output: DailyUsageMetric
+ cache: DailyUsageMetric
+ }
+}
+
+export type BotTokenUsage = {
+ capability: "supported" | "unsupported" | "unknown"
+ days: BotUsageDay[]
+}
export type BotSummary = {
id: string
@@ -25,6 +40,10 @@ export type BotSummary = {
// Sparse — only days with activity; oldest→newest; [] for a brand-new bot.
// The heatmap builds the full 30-day calendar and fills from this by day-key.
dailyActivity: BotActivityDay[]
+ // Owner-only seven-day provider telemetry. Older optimistic mutation payloads
+ // can omit it until the bots query refetches, which renders the unknown-state
+ // placeholder instead of inventing zero usage.
+ usage?: BotTokenUsage
}
export type BotsResponse = { bots: BotSummary[] }
diff --git a/src/web/src/hooks/community/use-machines.ts b/src/web/src/hooks/community/use-machines.ts
index de438fd4c..a75d2cd37 100644
--- a/src/web/src/hooks/community/use-machines.ts
+++ b/src/web/src/hooks/community/use-machines.ts
@@ -3,7 +3,42 @@
import { useQuery, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import type { CommunityMachineSummary } from "@alook/shared"
+import type {
+ CommunityMachineSummary,
+ ProviderQuotaObservation,
+ QuotaLimit,
+} from "@alook/shared"
+
+type MachineQuotaSnapshot =
+ | { status: "pending" }
+ | {
+ status: "error"
+ code: Extract<ProviderQuotaObservation, { status: "error" }>["code"]
+ }
+ | {
+ status: "available" | "stale"
+ observedAt: string
+ planName?: string
+ limits: QuotaLimit[]
+ }
+
+export type MachineBackendQuota = {
+ scope: {
+ kind: "machine_backend"
+ machineId: string
+ agentBackendId: string
+ }
+ capability: "supported" | "unsupported" | "unknown"
+ runtimeState: "healthy" | "unhealthy" | "offline"
+ snapshot: MachineQuotaSnapshot
+}
+
+// Machine WS events intentionally carry the base summary without owner-only
+// quota. Keep quota optional so live status updates can replace a machine safely;
+// the next owner API fetch restores its complete replace-all quota snapshot.
+export type MachineSummary = CommunityMachineSummary & {
+ quota?: MachineBackendQuota[]
+}
/**
* Fetches the current user's community-daemon machines.
@@ -12,16 +47,16 @@ import type { CommunityMachineSummary } from "@alook/shared"
* live-patch `communityKeys.machines()` via `queryClient.setQueryData` on
* `community:machine.*` WS events, so this list stays fresh without a refetch.
*/
-export type MachinesResponse = { machines: CommunityMachineSummary[] }
+export type MachinesResponse = { machines: MachineSummary[] }
// Frozen empty fallback — see `use-servers.ts` for the rationale.
-const EMPTY_MACHINES: readonly CommunityMachineSummary[] = Object.freeze([])
+const EMPTY_MACHINES: readonly MachineSummary[] = Object.freeze([])
export const machinesQueryFn = () =>
apiFetch<MachinesResponse>("/api/community/machines")
export function useMachines(): UseQueryResult<MachinesResponse> & {
- machines: CommunityMachineSummary[]
+ machines: MachineSummary[]
} {
const query = useQuery({
queryKey: communityKeys.machines(),
@@ -29,6 +64,6 @@ export function useMachines(): UseQueryResult<MachinesResponse> & {
})
return {
...query,
- machines: query.data?.machines ?? (EMPTY_MACHINES as CommunityMachineSummary[]),
+ machines: query.data?.machines ?? (EMPTY_MACHINES as MachineSummary[]),
}
}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 6310de61f..9c4c46def 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -84,6 +84,11 @@ export const tid = {
botReportProblemStatus: "bot-report-problem-status",
botAvatarPickerTrigger: "community-bot-avatar-picker-trigger",
botReasoningEffort: "community-bot-reasoning-effort",
+ botCardModel: "bot-card-model",
+ botUsage: (botId: string) => `community-bot-usage-${botId}`,
+ botUsageDay: (botId: string, day: string) => `community-bot-usage-day-${botId}-${day}`,
+ machineQuota: (machineId: string) => `community-machine-quota-${machineId}`,
+ machineQuotaDetail: (machineId: string) => `community-machine-quota-detail-${machineId}`,
forumTagDialog: "community-forum-tag-dialog",
forumTagDialogChip: (tag: string) => `community-forum-tag-dialog-chip-${tag}`,
diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
new file mode 100644
index 000000000..0800bc89d
--- /dev/null
+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
@@ -0,0 +1,296 @@
+import type { Page, TestInfo } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { tid } from "./_fixtures/testids"
+
+const days = [
+ { day: "2026-08-23", period: "closed", metrics: { input: 1200, output: 400, cache: 2000 } },
+ { day: "2026-08-24", period: "closed", metrics: { input: 800, output: 200, cache: 1000 } },
+ { day: "2026-08-25", period: "closed", metrics: { input: null, output: null, cache: null } },
+ { day: "2026-08-26", period: "closed", metrics: { input: 700, output: 300, cache: null } },
+ { day: "2026-08-27", period: "closed", metrics: { input: 0, output: 0, cache: 0 } },
+ { day: "2026-08-28", period: "closed", metrics: { input: 4000, output: 1200, cache: 6400 } },
+ { day: "2026-08-29", period: "in_progress", metrics: { input: 1800, output: 650, cache: 2400 } },
+] as const
+
+const smallerDays = days.map((day) => ({
+ ...day,
+ metrics: {
+ input: day.metrics.input === null ? null : day.metrics.input / 10,
+ output: day.metrics.output === null ? null : day.metrics.output / 10,
+ cache: day.metrics.cache === null ? null : day.metrics.cache / 10,
+ },
+}))
+
+const claudeDays = days.map((day) => ({
+ ...day,
+ metrics: {
+ input: day.metrics.input === null ? null : day.metrics.input / 2,
+ output: day.metrics.output === null ? null : day.metrics.output / 2,
+ cache: day.metrics.cache === null ? null : day.metrics.cache / 2,
+ },
+}))
+
+const machine = {
+ id: "machine_telemetry",
+ hostname: "studio-mac",
+ displayName: "Studio Mac",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "26.0",
+ daemonVersion: "0.1.24",
+ lastSeenAt: "2026-08-29T01:00:00.000Z",
+ status: "online",
+ availableRuntimes: [
+ { id: "codex", status: "healthy" },
+ { id: "pi", status: "healthy" },
+ { id: "claude", status: "healthy" },
+ ],
+ createdAt: "2026-08-29T00:00:00.000Z",
+ updatedAt: "2026-08-29T01:00:00.000Z",
+ quota: [
+ {
+ scope: { kind: "machine_backend", machineId: "machine_telemetry", agentBackendId: "codex" },
+ capability: "supported",
+ runtimeState: "healthy",
+ snapshot: {
+ status: "available",
+ observedAt: new Date().toISOString(),
+ planName: "Plus",
+ limits: [
+ {
+ bucket: {
+ limitId: "spark-five-hour",
+ product: { kind: "reported", id: "spark", displayName: "Spark" },
+ model: { kind: "reported", id: "gpt-5.3-codex-spark" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ },
+ usedPercent: 82,
+ resetsAt: "2026-08-29T05:00:00.000Z",
+ },
+ {
+ bucket: {
+ limitId: "spark-weekly",
+ product: { kind: "reported", id: "spark", displayName: "Spark" },
+ model: { kind: "reported", id: "gpt-5.3-codex-spark" },
+ window: { kind: "calendar", period: "week", displayName: "Weekly usage limit" },
+ },
+ usedPercent: 55.5,
+ resetsAt: "2026-09-01T00:00:00.000Z",
+ },
+ ],
+ },
+ },
+ {
+ scope: { kind: "machine_backend", machineId: "machine_telemetry", agentBackendId: "pi" },
+ capability: "unsupported",
+ runtimeState: "healthy",
+ snapshot: { status: "pending" },
+ },
+ {
+ scope: { kind: "machine_backend", machineId: "machine_telemetry", agentBackendId: "claude" },
+ capability: "supported",
+ runtimeState: "healthy",
+ snapshot: {
+ status: "available",
+ observedAt: new Date().toISOString(),
+ planName: "Max",
+ limits: [{
+ bucket: {
+ limitId: "five_hour",
+ product: { kind: "reported", id: "claude", displayName: "Claude" },
+ model: { kind: "not_applicable" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hour usage limit" },
+ },
+ usedPercent: 36,
+ resetsAt: "2026-08-29T06:00:00.000Z",
+ }],
+ },
+ },
+ ],
+}
+
+const bots = [
+ {
+ id: "bot_codex",
+ name: "Alli",
+ description: "",
+ image: null,
+ machineId: machine.id,
+ runtime: "codex",
+ modelName: "gpt-5.3-codex-spark",
+ lastRefreshContextAt: "2026-08-28T20:00:00.000Z",
+ dailyActivity: [],
+ usage: { capability: "supported", days },
+ },
+ {
+ id: "bot_pi",
+ name: "Scout",
+ description: "",
+ image: null,
+ machineId: machine.id,
+ runtime: "pi",
+ modelName: null,
+ lastRefreshContextAt: null,
+ dailyActivity: [],
+ usage: { capability: "unsupported", days: [] },
+ },
+ {
+ id: "bot_claude",
+ name: "Draft",
+ description: "",
+ image: null,
+ machineId: machine.id,
+ runtime: "claude",
+ modelName: "claude-opus-4-6",
+ lastRefreshContextAt: null,
+ dailyActivity: [],
+ usage: { capability: "supported", days: claudeDays },
+ },
+ {
+ id: "bot_small",
+ name: "Pocket",
+ description: "",
+ image: null,
+ machineId: machine.id,
+ runtime: "codex",
+ modelName: "gpt-5.3-codex-spark",
+ lastRefreshContextAt: null,
+ dailyActivity: [],
+ usage: { capability: "supported", days: smallerDays },
+ },
+]
+
+async function attachScreenshot(page: Page, testInfo: TestInfo, name: string) {
+ const path = testInfo.outputPath(`${name}.png`)
+ await page.screenshot({ path, fullPage: true })
+ await testInfo.attach(`${name}.png`, { path, contentType: "image/png" })
+}
+
+async function expectNoHorizontalOverflow(page: Page) {
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
+}
+
+test("My Bots renders seven-day usage and replace-all quota across responsive themes", async ({ asUser }, testInfo) => {
+ const { page } = await asUser("alice", { hasTouch: true })
+ await page.route("**/api/community/bots", async (route) => {
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ bots }) })
+ })
+ await page.route("**/api/community/machines", async (route) => {
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ machines: [machine] }) })
+ })
+ await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "light" })
+ await page.setViewportSize({ width: 1280, height: 900 })
+ await gotoAfterUserWsAuth(page, "/c/me/bots")
+
+ const usage = page.getByTestId(tid.botUsage("bot_codex"))
+ await expect(usage).toBeVisible()
+ await expect(usage.getByRole("listitem")).toHaveCount(7)
+ await expect(usage).not.toContainText("8/23")
+ await expect(usage).not.toContainText("Today")
+ await expect(usage).not.toContainText("Tokens")
+ await expect.poll(async () => (await usage.boundingBox())?.height ?? 0).toBe(42)
+ const botCard = usage.locator('xpath=ancestor::*[@data-slot="card"]')
+ await expect.poll(async () => (await botCard.boundingBox())?.height ?? 0)
+ .toBeLessThanOrEqual(80)
+ const [usageBox, botMetaBox] = await Promise.all([
+ usage.boundingBox(),
+ botCard.getByTestId(tid.botCardModel).boundingBox(),
+ ])
+ expect(usageBox).not.toBeNull()
+ expect(botMetaBox).not.toBeNull()
+ expect(Math.abs(
+ usageBox!.y + usageBox!.height - (botMetaBox!.y + botMetaBox!.height),
+ )).toBeLessThanOrEqual(3)
+ await expect(page.getByTestId(tid.botUsage("bot_pi"))).toHaveCount(0)
+ await expect(page.getByText("Token usage not supported")).toHaveCount(0)
+ const claudeUsage = page.getByTestId(tid.botUsage("bot_claude"))
+ await expect(claudeUsage.getByRole("listitem")).toHaveCount(7)
+ const quota = page.getByTestId(tid.machineQuota(machine.id))
+ await expect(quota).toHaveCount(1)
+ await expect(quota).toContainText("Quota · Spark · 18% left · 3 limits")
+
+ const largestDayBar = page
+ .getByTestId(tid.botUsageDay("bot_codex", "2026-08-28"))
+ .locator('[style*="height"]')
+ const smallerDayBar = page
+ .getByTestId(tid.botUsageDay("bot_small", "2026-08-28"))
+ .locator('[style*="height"]')
+ await expect(largestDayBar).toHaveAttribute("style", /height: 100%/)
+ await expect(smallerDayBar).toHaveAttribute("style", /height: 10%/)
+ await expect(
+ page.getByTestId(tid.botUsageDay("bot_claude", "2026-08-28")).locator('[style*="height"]'),
+ ).toHaveAttribute("style", /height: 50%/)
+
+ const usageDay = page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-26"))
+ await usageDay.hover()
+ const tooltip = page.locator('[data-slot="tooltip-content"]:visible')
+ await expect(tooltip).toContainText("Input700")
+ await expect(tooltip).toContainText("Output300")
+ await expect(tooltip).toContainText("CacheUnavailable")
+ await usageDay.focus()
+ await expect(page.getByText("Input", { exact: true }).last()).toBeVisible()
+ await page.keyboard.press("Escape")
+
+ await expect(quota).toHaveAttribute("aria-expanded", "false")
+ await quota.click()
+ await expect(quota).toHaveAttribute("aria-expanded", "true")
+ const quotaDetail = page.getByTestId(tid.machineQuotaDetail(machine.id))
+ await expect(quotaDetail).toContainText("Codex")
+ await expect(quotaDetail).toContainText("Pi")
+ await expect(quotaDetail).toContainText("Not supported")
+ await expect(quotaDetail).toContainText("Claude")
+ await expect(quotaDetail).toContainText("Max")
+ await expect(quotaDetail).toContainText("64% left")
+ await expect(quotaDetail).toContainText("5 hour usage limit")
+ await expect(quotaDetail).toContainText("Weekly usage limit")
+ await expect(quotaDetail).toContainText("gpt-5.3-codex-spark")
+ await expect(quotaDetail).toHaveCSS("opacity", "1")
+
+ await expectNoHorizontalOverflow(page)
+ await attachScreenshot(page, testInfo, "my-bots-telemetry-pc-light")
+ await quota.click()
+ await expect(quota).toHaveAttribute("aria-expanded", "false")
+ await expect(quotaDetail).toBeHidden()
+ await page.emulateMedia({ colorScheme: "dark" })
+ await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(true)
+ await page.waitForTimeout(300)
+ await attachScreenshot(page, testInfo, "my-bots-telemetry-pc-dark")
+
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.emulateMedia({ colorScheme: "light" })
+ await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(false)
+ await page.waitForTimeout(300)
+ await expectNoHorizontalOverflow(page)
+ await expect(usage).toBeVisible()
+ await expect(usage.getByRole("listitem")).toHaveCount(7)
+ const mobileUsageTrigger = usage.getByRole("button", { name: "Open token usage details" })
+ const mobileUsageBox = await mobileUsageTrigger.boundingBox()
+ expect(mobileUsageBox?.height).toBeGreaterThanOrEqual(44)
+ expect(mobileUsageBox?.width).toBeGreaterThanOrEqual(44)
+ await mobileUsageTrigger.tap()
+ const mobileUsageDay = page.locator(
+ `[data-testid="${tid.botUsageDay("bot_codex", "2026-08-26")}"]:visible`,
+ )
+ await expect.poll(async () => (await mobileUsageDay.boundingBox())?.height ?? 0)
+ .toBeGreaterThanOrEqual(44)
+ await expect.poll(async () => (await mobileUsageDay.boundingBox())?.width ?? 0)
+ .toBeGreaterThanOrEqual(44)
+ await mobileUsageDay.tap()
+ const mobileUsageDetail = page.locator('[data-slot="popover-content"]:visible')
+ await expect(mobileUsageDetail).toContainText("Input700")
+ await expect(mobileUsageDetail).toContainText("Output300")
+ await expect(mobileUsageDetail).toContainText("CacheUnavailable")
+ const mobileQuotaBox = await quota.boundingBox()
+ expect(mobileQuotaBox?.height).toBeGreaterThanOrEqual(44)
+ expect(mobileQuotaBox?.width).toBeGreaterThanOrEqual(44)
+ await mobileUsageTrigger.tap()
+ await expect(mobileUsageTrigger).toHaveAttribute("aria-expanded", "false")
+ await expect(page.locator('[data-slot="popover-content"]:visible')).toHaveCount(0)
+ await attachScreenshot(page, testInfo, "my-bots-telemetry-mobile-light")
+ await page.emulateMedia({ colorScheme: "dark" })
+ await expect.poll(() => page.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(true)
+ await page.waitForTimeout(300)
+ await expectNoHorizontalOverflow(page)
+ await attachScreenshot(page, testInfo, "my-bots-telemetry-mobile-dark")
+})
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts
index 1d1178c37..fe919bd4b 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts
@@ -1,4 +1,9 @@
-import { test as base, type BrowserContext, type Page } from "@playwright/test"
+import {
+ test as base,
+ type BrowserContext,
+ type BrowserContextOptions,
+ type Page,
+} from "@playwright/test"
import { readFileSync } from "fs"
import { resolve } from "path"
import {
@@ -13,7 +18,10 @@ import type { UserKey } from "../_setup/users"
// Per-user authenticated context factory. A journey calls `asUser("bob")` to
// get Bob's own browser context + page (separate from Alice's) so multi-user
// realtime journeys can drive two or three sessions at once.
-type AsUser = (key: UserKey) => Promise<{ context: BrowserContext; page: Page }>
+type AsUser = (
+ key: UserKey,
+ options?: Omit<BrowserContextOptions, "storageState">,
+) => Promise<{ context: BrowserContext; page: Page }>
function throwOrSkipFailure(
decision: FailureDecision,
@@ -48,9 +56,9 @@ export const test = base.extend<{ asUser: AsUser; serviceGuard: void }>({
}, { auto: true }],
asUser: async ({ browser }, provide) => {
const opened: BrowserContext[] = []
- const factory: AsUser = async (key) => {
+ const factory: AsUser = async (key, options) => {
const statePath = resolve(AUTH_DIR, `${key}.json`)
- const context = await browser.newContext({ storageState: statePath })
+ const context = await browser.newContext({ ...options, storageState: statePath })
opened.push(context)
const page = await context.newPage()
return { context, page }
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index 642d8a616..1b575d3cd 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -7,6 +7,7 @@ import {
flushAsyncWork,
mockCheckAliveFetch,
mockCreateDb,
+ mockD1Batch,
mockFindCredentialByHash,
mockGetBotBinding,
mockGetBotBindingWithOwner,
@@ -185,6 +186,127 @@ describe("WebSocketDurableObject", () => {
expect(credentialHash).toBe("0".repeat(64))
})
+ it("persists only valid quotas for backends present in the accepted runtime report", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [{ id: "codex" }],
+ status: "online",
+ lastSeenAt: "2026-07-06T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-05T00:00:00.000Z",
+ priorAvailableRuntimes: [{ id: "codex" }],
+ priorDaemonVersion: "0.1.0",
+ priorStatus: "online",
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "codex" }],
+ capabilities: ["control-heartbeat-v1"],
+ runningAgents: [],
+ providerQuotas: [{
+ agentBackendId: "codex",
+ observation: {
+ status: "error",
+ sourceEpoch: "Q".repeat(22),
+ code: "network",
+ retryable: true,
+ },
+ }],
+ }))
+
+ expect(mockUpsertMachineByMachineId).toHaveBeenCalledOnce()
+ expect(mockD1Batch).toHaveBeenCalledOnce()
+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>
+ expect(statements).toHaveLength(1)
+ expect(statements[0]!.sql).toContain("community_machine_backend_quota")
+ expect(statements[0]!.values.slice(0, 4)).toEqual(["cm_1", "codex", "Q".repeat(22), "error"])
+
+ mockD1Batch.mockClear()
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "codex" }],
+ capabilities: ["control-heartbeat-v1"],
+ runningAgents: [],
+ providerQuotas: [{ agentBackendId: "codex", observation: { status: "error" } }],
+ }))
+ expect(mockUpsertMachineByMachineId).toHaveBeenCalledTimes(2)
+ expect(mockD1Batch).not.toHaveBeenCalled()
+ })
+
+ it("continues core ready reconciliation when optional quota persistence fails", async () => {
+ const { durable, store, storage } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [{ id: "codex" }],
+ status: "online",
+ lastSeenAt: "2026-08-08T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-08-07T00:00:00.000Z",
+ priorAvailableRuntimes: [{ id: "codex" }],
+ priorDaemonVersion: "0.1.0",
+ priorStatus: "online",
+ })
+ mockD1Batch.mockRejectedValueOnce(new Error("quota D1 unavailable"))
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "codex" }],
+ capabilities: ["control-heartbeat-v1"],
+ runningAgents: [],
+ providerQuotas: [{
+ agentBackendId: "codex",
+ observation: {
+ status: "error",
+ sourceEpoch: "Q".repeat(22),
+ code: "network",
+ retryable: true,
+ },
+ }],
+ }))
+
+ expect(mockReconcileBotActivityFromRunningAgents).toHaveBeenCalledWith(
+ expect.anything(),
+ "cm_1",
+ [],
+ )
+ expect(storage.put).toHaveBeenCalled()
+ expect(storage.setAlarm).toHaveBeenCalled()
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "provider_quota_dropped",
+ expect.objectContaining({ frame_type: "ready", machineId: "cm_1" }),
+ )
+ })
+
it.each([
["legacy ready", undefined, false],
["heartbeat-capable ready", ["control-heartbeat-v1"], true],
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
index f182cb4d4..1d3baaa67 100644
--- a/src/ws-do/src/ws-durable/machine-ready.ts
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -2,6 +2,7 @@ import {
CONTROL_HEARTBEAT_CAPABILITY,
createDb,
HostReadyMessageSchema,
+ ProviderQuotaSnapshotSchema,
queries,
WS_EVENTS,
} from "@alook/shared"
@@ -18,6 +19,7 @@ import type {
} from "./internal"
import { scheduleHeartbeatAlarm } from "./machine-lifecycle"
import { broadcastToAudience, notifyUserDO } from "./presence-typing"
+import { prepareQuotaReplace } from "./provider-telemetry-persistence"
/**
* Order-normalized runtime JSON includes status and lastError, so a health
@@ -63,9 +65,23 @@ export async function handleReadyFrame(
identity: CommunityMachineIdentity,
ws: WebSocket,
): Promise<boolean> {
- const readyParse = HostReadyMessageSchema.safeParse(parsed)
+ const readyParse = HostReadyMessageSchema
+ .omit({ providerQuotas: true })
+ .passthrough()
+ .safeParse(parsed)
if (!readyParse.success) return false
const ready = readyParse.data
+ const raw = parsed as Record<string, unknown>
+ const quotaParse = raw.providerQuotas === undefined
+ ? null
+ : ProviderQuotaSnapshotSchema.array().max(2).safeParse(raw.providerQuotas)
+ const quotaBackends = quotaParse?.success
+ ? new Set(quotaParse.data.map((snapshot) => snapshot.agentBackendId))
+ : null
+ const providerQuotas = quotaParse?.success
+ && quotaBackends?.size === quotaParse.data.length
+ ? quotaParse.data
+ : []
const controlHeartbeat = ready.capabilities.includes(CONTROL_HEARTBEAT_CAPABILITY)
const state = ws.deserializeAttachment() as import("./internal").ConnectionState
if (
@@ -115,6 +131,27 @@ export async function handleReadyFrame(
return true
}
const { machine, priorAvailableRuntimes, priorDaemonVersion, priorStatus } = result
+ const acceptedQuotas = providerQuotas.filter((snapshot) =>
+ ready.runtimeReport.some((runtime) => runtime.id === snapshot.agentBackendId)
+ )
+ if (acceptedQuotas.length > 0) {
+ const nowIso = new Date().toISOString()
+ try {
+ await context.env.DB.batch(
+ acceptedQuotas.map((snapshot) => prepareQuotaReplace(context.env.DB, identity, snapshot, nowIso))
+ )
+ } catch (err) {
+ // Quota is an optional sibling of the existing ready lifecycle. A
+ // telemetry-only persistence failure must not strand reconciliation,
+ // heartbeat scheduling, or machine status after ready already won its
+ // authenticated session transition.
+ context.log.warn("provider_quota_dropped", {
+ frame_type: "ready",
+ machineId: identity.machineId,
+ err: err instanceof Error ? err : new Error(String(err)),
+ })
+ }
+ }
// Reconciliation is the coarse safety net for an activity frame lost
// during disconnect. It clears only stale system-owned activity pills;
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index 2ac9439f1..0480d351c 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -7,6 +7,7 @@ import {
flushAsyncWork,
mockCheckAliveFetch,
mockCreateDb,
+ mockD1Batch,
mockFindCredentialByHash,
mockGetBotBinding,
mockGetBotBindingWithOwner,
@@ -279,6 +280,113 @@ describe("WebSocketDurableObject", () => {
// Socket didn't close — the DO doesn't touch ws.close() on any per-frame D1 error.
expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
})
+
+ it("persists an idle bot's usage and matching backend quota in one D1 batch", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: [{
+ botId: "bot_1",
+ day: new Date().toISOString().slice(0, 10),
+ metrics: {
+ input: 12,
+ output: 7,
+ cache: null,
+ },
+ }],
+ quota: {
+ agentBackendId: "codex",
+ observation: {
+ status: "available",
+ sourceEpoch: "A".repeat(22),
+ freshForSeconds: 300,
+ limits: [{
+ bucket: {
+ limitId: "primary",
+ product: { kind: "reported", id: "codex", displayName: "Codex" },
+ model: { kind: "not_applicable" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hours" },
+ },
+ usedPercent: 25,
+ }],
+ },
+ },
+ }))
+
+ expect(mockD1Batch).toHaveBeenCalledOnce()
+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string; values: unknown[] }>
+ expect(statements.map((statement) => statement.sql)).toEqual([
+ expect.stringContaining("community_user_profile"),
+ expect.stringContaining("community_bot_daily_token_usage"),
+ expect.stringContaining("DELETE FROM community_bot_daily_token_usage"),
+ expect.stringContaining("community_machine_backend_quota"),
+ ])
+ expect(statements[1]!.values).toMatchObject({ 0: "bot_1", 2: 12, 3: 7, 4: null })
+ })
+
+ it("persists each valid telemetry section when the sibling section is malformed", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ const day = new Date().toISOString().slice(0, 10)
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: [{
+ botId: "bot_1",
+ day,
+ metrics: {
+ input: 3,
+ output: null,
+ cache: null,
+ },
+ }],
+ quota: { agentBackendId: "codex", observation: { status: "error" } },
+ }))
+ let statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string }>
+ expect(statements.some((statement) => statement.sql.includes("community_bot_daily_token_usage"))).toBe(true)
+ expect(statements.some((statement) => statement.sql.includes("community_machine_backend_quota"))).toBe(false)
+
+ mockD1Batch.mockClear()
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "agent_activity",
+ agentId: "bot_1",
+ state: "idle",
+ dailyUsage: [{ botId: "another_bot", day, metrics: {} }],
+ quota: {
+ agentBackendId: "codex",
+ observation: {
+ status: "error",
+ sourceEpoch: "B".repeat(22),
+ code: "network",
+ retryable: true,
+ },
+ },
+ }))
+ statements = mockD1Batch.mock.calls[0]![0] as Array<{ sql: string }>
+ expect(statements.some((statement) => statement.sql.includes("community_bot_daily_token_usage"))).toBe(false)
+ expect(statements.some((statement) => statement.sql.includes("community_machine_backend_quota"))).toBe(true)
+ })
})
describe("community-machine — agent_typing / agent_typing_stop frames", () => {
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.ts
index 64bbf1e8f..a4fd3ab96 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts
@@ -1,15 +1,18 @@
import {
AgentActivityMessageSchema,
+ DailyUsageSnapshotSchema,
AgentTypingMessageSchema,
AgentTypingStopMessageSchema,
createDb,
HostBotAuditEventFrameSchema,
isBotActivityStatus,
pickBotActivityPreset,
+ ProviderQuotaSnapshotSchema,
queries,
RUNNING_PRESETS,
withD1Retry,
WS_EVENTS,
+ utcDayKeyDaysAgo,
} from "@alook/shared"
import { handleFrameForBoundBot } from "./bound-bot-frame"
import type { CommunityMachineIdentity, WsDurableContext } from "./internal"
@@ -19,6 +22,12 @@ import {
fanOutTypingStop,
notifyUserDO,
} from "./presence-typing"
+import {
+ prepareActivityProfileUpsert,
+ prepareQuotaReplace,
+ prepareUsagePrune,
+ prepareUsageUpsert,
+} from "./provider-telemetry-persistence"
const IDLE_RESET_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000
@@ -44,10 +53,31 @@ export async function handleActivityFrame(
parsed: unknown,
identity: CommunityMachineIdentity,
): Promise<boolean> {
- const activityParse = AgentActivityMessageSchema.safeParse(parsed)
+ const activityParse = AgentActivityMessageSchema
+ .omit({ dailyUsage: true, quota: true })
+ .passthrough()
+ .safeParse(parsed)
if (!activityParse.success) return false
const { agentId, state } = activityParse.data
+ const raw = parsed as Record<string, unknown>
+ const now = new Date()
+ const allowedDays = new Set(Array.from({ length: 7 }, (_, offset) => utcDayKeyDaysAgo(now, offset)))
+ const usageParse = raw.dailyUsage === undefined
+ ? null
+ : DailyUsageSnapshotSchema.array().max(7).safeParse(raw.dailyUsage)
+ const parsedUsage = usageParse?.success ? usageParse.data : undefined
+ const usageDays = parsedUsage ? new Set(parsedUsage.map((snapshot) => snapshot.day)) : null
+ const validUsage = state === "idle"
+ && parsedUsage !== undefined
+ && usageDays?.size === parsedUsage.length
+ && parsedUsage.every((snapshot) => snapshot.botId === agentId && allowedDays.has(snapshot.day))
+ ? parsedUsage
+ : undefined
+ const quotaParse = raw.quota === undefined
+ ? null
+ : ProviderQuotaSnapshotSchema.safeParse(raw.quota)
+ const validQuota = quotaParse?.success ? quotaParse.data : undefined
const db = createDb(context.env.DB)
await handleFrameForBoundBot(context, {
frameType: "agent_activity",
@@ -55,7 +85,7 @@ export async function handleActivityFrame(
machineId: identity.machineId,
resolveBinding: () => queries.communityBot.getBotBinding(db, agentId),
isMatch: (binding) => binding.machineId === identity.machineId,
- write: async () => {
+ write: async (binding) => {
const prior = await withD1Retry(
() => queries.communityUserProfile.getProfile(db, agentId),
{ route: "ws-do:agent-activity-profile-read" },
@@ -66,33 +96,80 @@ export async function handleActivityFrame(
const priorText = prior?.statusText ? prior.statusText : null
// This path owns only known activity pills. Any other persisted pair is
// owner-authored and must survive activity heartbeats unchanged.
- if (
+ const customStatus =
(priorEmoji !== null || priorText !== null) &&
!isBotActivityStatus(priorEmoji, priorText)
- ) return
+ const profileWritable = !customStatus
const priorIsRunning =
priorEmoji !== null &&
RUNNING_PRESETS.some((preset) => preset.emoji === priorEmoji && preset.text === priorText)
// Reuse an existing running preset instead of rerolling on every
// derived turn_end → idle → wake → running transition.
- const preset =
+ const preset = profileWritable
+ ? (
state === "running" && priorIsRunning
? { emoji: priorEmoji as string, text: priorText as string }
: pickBotActivityPreset(state, Math.random())
- if (preset.emoji === priorEmoji && preset.text === priorText) return
- await withD1Retry(
- () => queries.communityUserProfile.updateProfile(db, agentId, {
+ )
+ : null
+ const profileChanged = preset !== null
+ && (preset.emoji !== priorEmoji || preset.text !== priorText)
+ const quota = validQuota?.agentBackendId === binding.runtime ? validQuota : undefined
+ const hasTelemetry = (validUsage?.length ?? 0) > 0 || quota !== undefined
+ if (!hasTelemetry) {
+ if (!profileChanged || !preset) return
+ await withD1Retry(
+ () => queries.communityUserProfile.updateProfile(db, agentId, {
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ }),
+ { route: "ws-do:agent-activity-profile" },
+ )
+ await broadcastToAudience(context, agentId, {
+ type: WS_EVENTS.STATUS_UPDATE,
+ userId: agentId,
statusEmoji: preset.emoji,
statusText: preset.text,
- }),
- { route: "ws-do:agent-activity-profile" },
- )
- await broadcastToAudience(context, agentId, {
- type: WS_EVENTS.STATUS_UPDATE,
- userId: agentId,
- statusEmoji: preset.emoji,
- statusText: preset.text,
- })
+ })
+ return
+ }
+ const nowIso = now.toISOString()
+ const statements: D1PreparedStatement[] = []
+ const profileStatementIndex = profileChanged && preset ? statements.length : -1
+ if (profileChanged && preset) {
+ statements.push(prepareActivityProfileUpsert(
+ context.env.DB,
+ identity.machineId,
+ agentId,
+ preset.emoji,
+ preset.text,
+ ))
+ }
+ for (const snapshot of validUsage ?? []) {
+ statements.push(prepareUsageUpsert(context.env.DB, identity.machineId, snapshot, nowIso))
+ }
+ if (validUsage && validUsage.length > 0) {
+ statements.push(prepareUsagePrune(
+ context.env.DB,
+ identity.machineId,
+ agentId,
+ utcDayKeyDaysAgo(now, 6),
+ ))
+ }
+ if (quota) statements.push(prepareQuotaReplace(context.env.DB, identity, quota, nowIso))
+ const results = await context.env.DB.batch(statements)
+ if (
+ profileStatementIndex >= 0
+ && preset
+ && (results[profileStatementIndex]?.meta.changes ?? 0) > 0
+ ) {
+ await broadcastToAudience(context, agentId, {
+ type: WS_EVENTS.STATUS_UPDATE,
+ userId: agentId,
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ })
+ }
},
})
return true
diff --git a/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts b/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts
new file mode 100644
index 000000000..57a1ea5dc
--- /dev/null
+++ b/src/ws-do/src/ws-durable/provider-telemetry-persistence.test.ts
@@ -0,0 +1,165 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { DatabaseSync } from "node:sqlite";
+import type { DailyUsageSnapshot, ProviderQuotaSnapshot } from "@alook/shared";
+import {
+ prepareQuotaReplace,
+ prepareUsageUpsert,
+} from "./provider-telemetry-persistence.js";
+
+function d1Adapter(sqlite: DatabaseSync): D1Database {
+ return {
+ prepare(sql: string) {
+ const statement = sqlite.prepare(sql);
+ return {
+ bind(...values: unknown[]) {
+ return {
+ run: () => statement.run(...values as never[]),
+ };
+ },
+ };
+ },
+ } as unknown as D1Database;
+}
+
+function run(statement: D1PreparedStatement): void {
+ (statement as unknown as { run(): unknown }).run();
+}
+
+function usage(
+ botId: string,
+ input: DailyUsageSnapshot["metrics"]["input"],
+ output: DailyUsageSnapshot["metrics"]["output"],
+ cache: DailyUsageSnapshot["metrics"]["cache"],
+): DailyUsageSnapshot {
+ return { botId, day: "2026-08-28", metrics: { input, output, cache } };
+}
+
+function quota(
+ sourceEpoch: string,
+ observation: Omit<ProviderQuotaSnapshot["observation"], "sourceEpoch">,
+): ProviderQuotaSnapshot {
+ return {
+ agentBackendId: "codex",
+ observation: { ...observation, sourceEpoch },
+ };
+}
+
+describe("provider telemetry persistence SQL", () => {
+ let sqlite: DatabaseSync;
+ let db: D1Database;
+
+ beforeEach(() => {
+ sqlite = new DatabaseSync(":memory:");
+ db = d1Adapter(sqlite);
+ sqlite.exec(`
+ CREATE TABLE community_bot_binding (
+ user_id TEXT PRIMARY KEY NOT NULL,
+ machine_id TEXT NOT NULL
+ );
+ CREATE TABLE community_bot_daily_token_usage (
+ bot_id TEXT NOT NULL,
+ day TEXT NOT NULL,
+ input_tokens INTEGER,
+ output_tokens INTEGER,
+ cache_tokens INTEGER,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (bot_id, day)
+ );
+ CREATE TABLE community_machine (
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL
+ );
+ CREATE TABLE community_machine_backend_quota (
+ machine_id TEXT NOT NULL,
+ agent_backend_id TEXT NOT NULL,
+ source_epoch TEXT NOT NULL,
+ status TEXT NOT NULL,
+ plan_name TEXT,
+ fresh_for_seconds INTEGER,
+ limits TEXT,
+ error_code TEXT,
+ retryable INTEGER,
+ observed_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (machine_id, agent_backend_id)
+ );
+ `);
+ sqlite.prepare("INSERT INTO community_bot_binding (user_id, machine_id) VALUES (?, ?)").run("bot_1", "machine_1");
+ sqlite.prepare("INSERT INTO community_machine (id, user_id) VALUES (?, ?)").run("machine_1", "owner_1");
+ });
+
+ afterEach(() => sqlite.close());
+
+ it("replaces the whole daily row with the daemon's latest snapshot", () => {
+ const first = usage(
+ "bot_1",
+ 10,
+ null,
+ 5,
+ );
+ const replacement = usage(
+ "bot_1",
+ 7,
+ 4,
+ null,
+ );
+
+ run(prepareUsageUpsert(db, "machine_1", first, "2026-08-28T10:00:00.000Z"));
+ run(prepareUsageUpsert(db, "machine_1", replacement, "2026-08-28T11:00:00.000Z"));
+
+ expect(sqlite.prepare(`
+ SELECT input_tokens, output_tokens, cache_tokens
+ FROM community_bot_daily_token_usage
+ WHERE bot_id = 'bot_1' AND day = '2026-08-28'
+ `).get()).toEqual({
+ input_tokens: 7,
+ output_tokens: 4,
+ cache_tokens: null,
+ });
+ });
+
+ it("checks the current binding inside the usage statement", () => {
+ sqlite.prepare("UPDATE community_bot_binding SET machine_id = ? WHERE user_id = ?").run("machine_2", "bot_1");
+
+ run(prepareUsageUpsert(db, "machine_1", usage(
+ "bot_1",
+ 9,
+ 3,
+ 1,
+ ), "2026-08-28T10:00:00.000Z"));
+
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_bot_daily_token_usage").get()).toEqual({ count: 0 });
+ });
+
+ it("retains a same-source success on transient error and replaces it for a new source", () => {
+ const available = quota("A".repeat(22), {
+ status: "available",
+ planName: "Plus",
+ freshForSeconds: 300,
+ limits: [{
+ bucket: {
+ limitId: "primary",
+ product: { kind: "reported", id: "codex", displayName: "Codex" },
+ model: { kind: "not_applicable" },
+ window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hours" },
+ },
+ usedPercent: 25,
+ }],
+ });
+ const sameSourceError = quota("A".repeat(22), { status: "error", code: "network", retryable: true });
+ const newSourceError = quota("B".repeat(22), { status: "error", code: "unauthorized", retryable: false });
+
+ run(prepareQuotaReplace(db, { machineId: "machine_1", userId: "owner_1" }, available, "2026-08-28T10:00:00.000Z"));
+ run(prepareQuotaReplace(db, { machineId: "machine_1", userId: "owner_1" }, sameSourceError, "2026-08-28T10:01:00.000Z"));
+ expect(sqlite.prepare(`
+ SELECT source_epoch, status, plan_name, error_code
+ FROM community_machine_backend_quota
+ `).get()).toEqual({ source_epoch: "A".repeat(22), status: "available", plan_name: "Plus", error_code: null });
+
+ run(prepareQuotaReplace(db, { machineId: "machine_1", userId: "owner_1" }, newSourceError, "2026-08-28T10:02:00.000Z"));
+ expect(sqlite.prepare(`
+ SELECT source_epoch, status, plan_name, error_code
+ FROM community_machine_backend_quota
+ `).get()).toEqual({ source_epoch: "B".repeat(22), status: "error", plan_name: null, error_code: "unauthorized" });
+ });
+});
diff --git a/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts b/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts
new file mode 100644
index 000000000..8d5d05d27
--- /dev/null
+++ b/src/ws-do/src/ws-durable/provider-telemetry-persistence.ts
@@ -0,0 +1,118 @@
+import type {
+ DailyUsageSnapshot,
+ ProviderQuotaSnapshot,
+} from "@alook/shared";
+
+const USAGE_UPSERT_SQL = `
+ INSERT INTO community_bot_daily_token_usage (
+ bot_id, day,
+ input_tokens, output_tokens, cache_tokens,
+ updated_at
+ )
+ SELECT ?, ?, ?, ?, ?, ?
+ WHERE EXISTS (
+ SELECT 1 FROM community_bot_binding
+ WHERE user_id = ? AND machine_id = ?
+ )
+ ON CONFLICT(bot_id, day) DO UPDATE SET
+ input_tokens = excluded.input_tokens,
+ output_tokens = excluded.output_tokens,
+ cache_tokens = excluded.cache_tokens,
+ updated_at = excluded.updated_at`;
+
+const QUOTA_REPLACE_SQL = `
+ INSERT INTO community_machine_backend_quota (
+ machine_id, agent_backend_id, source_epoch, status, plan_name,
+ fresh_for_seconds, limits, error_code, retryable, observed_at, updated_at
+ )
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
+ FROM community_machine
+ WHERE id = ? AND user_id = ?
+ ON CONFLICT(machine_id, agent_backend_id) DO UPDATE SET
+ source_epoch = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.source_epoch ELSE excluded.source_epoch END,
+ status = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.status ELSE excluded.status END,
+ plan_name = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.plan_name ELSE excluded.plan_name END,
+ fresh_for_seconds = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.fresh_for_seconds ELSE excluded.fresh_for_seconds END,
+ limits = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.limits ELSE excluded.limits END,
+ error_code = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.error_code ELSE excluded.error_code END,
+ retryable = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.retryable ELSE excluded.retryable END,
+ observed_at = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.observed_at ELSE excluded.observed_at END,
+ updated_at = CASE WHEN community_machine_backend_quota.source_epoch = excluded.source_epoch AND community_machine_backend_quota.status = 'available' AND excluded.status = 'error' THEN community_machine_backend_quota.updated_at ELSE excluded.updated_at END`;
+
+export function prepareUsageUpsert(
+ db: D1Database,
+ machineId: string,
+ snapshot: DailyUsageSnapshot,
+ nowIso: string,
+): D1PreparedStatement {
+ return db.prepare(USAGE_UPSERT_SQL).bind(
+ snapshot.botId,
+ snapshot.day,
+ snapshot.metrics.input,
+ snapshot.metrics.output,
+ snapshot.metrics.cache,
+ nowIso,
+ snapshot.botId,
+ machineId,
+ );
+}
+
+export function prepareUsagePrune(
+ db: D1Database,
+ machineId: string,
+ botId: string,
+ oldestDay: string,
+): D1PreparedStatement {
+ return db.prepare(`
+ DELETE FROM community_bot_daily_token_usage
+ WHERE bot_id = ? AND day < ?
+ AND EXISTS (
+ SELECT 1 FROM community_bot_binding
+ WHERE user_id = ? AND machine_id = ?
+ )
+ `).bind(botId, oldestDay, botId, machineId);
+}
+
+export function prepareQuotaReplace(
+ db: D1Database,
+ identity: { machineId: string; userId: string },
+ snapshot: ProviderQuotaSnapshot,
+ nowIso: string,
+): D1PreparedStatement {
+ const observation = snapshot.observation;
+ return db.prepare(QUOTA_REPLACE_SQL).bind(
+ identity.machineId,
+ snapshot.agentBackendId,
+ observation.sourceEpoch,
+ observation.status,
+ observation.status === "available" ? observation.planName ?? null : null,
+ observation.status === "available" ? observation.freshForSeconds : null,
+ observation.status === "available" ? JSON.stringify(observation.limits) : null,
+ observation.status === "error" ? observation.code : null,
+ observation.status === "error" ? (observation.retryable ? 1 : 0) : null,
+ nowIso,
+ nowIso,
+ identity.machineId,
+ identity.userId,
+ );
+}
+
+export function prepareActivityProfileUpsert(
+ db: D1Database,
+ machineId: string,
+ botId: string,
+ statusEmoji: string | null,
+ statusText: string | null,
+): D1PreparedStatement {
+ return db.prepare(`
+ INSERT INTO community_user_profile (user_id, about_me, banner_color, status_emoji, status_text)
+ SELECT ?, '', NULL, ?, ?
+ WHERE EXISTS (
+ SELECT 1 FROM community_bot_binding
+ WHERE user_id = ? AND machine_id = ?
+ )
+ ON CONFLICT(user_id) DO UPDATE SET
+ status_emoji = excluded.status_emoji,
+ status_text = excluded.status_text
+ `).bind(botId, statusEmoji, statusText ?? "", botId, machineId);
+}
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index b29ea4d46..9ac6342f1 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -134,6 +134,11 @@ export const mockGetProfile = vi
export const mockReconcileBotActivityFromRunningAgents = vi
.fn<(db: unknown, machineId: string, runningAgentIds: string[]) => Promise<Array<{ botUserId: string; statusEmoji: string; statusText: string }>>>()
.mockResolvedValue([])
+const mockD1Prepare = vi.fn((sql: string) => ({
+ bind: (...values: unknown[]) => ({ sql, values }),
+}))
+export const mockD1Batch = vi.fn(async (statements: unknown[]) =>
+ statements.map(() => ({ success: true, meta: { changes: 1 } })))
export const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
// mockToSummary now returns row.status verbatim — status is the source of
// truth on the column, not a derivation from lastSeenAt. See
@@ -189,29 +194,7 @@ vi.mock("@alook/shared", async () => {
}
},
}
- // Mirror the shared HostReadyMessageSchema: the daemon's ready frame must be
- // FLAT (fields at top level), not wrapped in a `ready` key. A wrapped frame
- // is rejected — regression guard against the wire-shape mismatch we hit
- // when the daemon sent `{type:"ready", ready:{...}}` while the DO expected
- // flat top-level fields.
- const HostReadyMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; runtimeReport?: unknown; capabilities?: unknown; runningAgents?: unknown }
- if (m?.type !== "ready") return { success: false } as const
- if (!Array.isArray(m?.runtimeReport)) return { success: false } as const
- const data: Record<string, unknown> = {
- type: "ready",
- runtimeReport: m.runtimeReport,
- capabilities: Array.isArray(m.capabilities) ? m.capabilities : [],
- runningAgents: Array.isArray(m.runningAgents) ? m.runningAgents : [],
- }
- for (const k of ["hostname", "platform", "arch", "osRelease", "daemonVersion"]) {
- const val = (m as Record<string, unknown>)[k]
- if (typeof val === "string") data[k] = val
- }
- return { success: true as const, data }
- },
- }
+ const HostReadyMessageSchema = actual.HostReadyMessageSchema
const MachineHeartbeatAckMessageSchema = {
safeParse(v: unknown) {
const m = v as { type?: unknown; nonce?: unknown }
@@ -228,15 +211,7 @@ vi.mock("@alook/shared", async () => {
: { success: false as const }
},
}
- const AgentActivityMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; state?: unknown }
- if (m?.type !== "agent_activity") return { success: false } as const
- if (typeof m.agentId !== "string") return { success: false } as const
- if (!["idle", "starting", "running", "stopping"].includes(m.state as string)) return { success: false } as const
- return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }
- },
- }
+ const AgentActivityMessageSchema = actual.AgentActivityMessageSchema
const AgentTypingMessageSchema = {
safeParse(v: unknown) {
const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }
@@ -516,7 +491,10 @@ export function createDO() {
const { ctx, getWebSockets, storage, store } = createMockCtx()
const stubGet = vi.fn().mockReturnValue({ fetch: mockStubFetch })
const env = {
- DB: {} as D1Database,
+ DB: {
+ prepare: (sql: string) => mockD1Prepare(sql),
+ batch: (statements: unknown[]) => mockD1Batch(statements),
+ } as unknown as D1Database,
WS_DO: {
idFromName: vi.fn().mockReturnValue("mock-do-id"),
get: stubGet,
@@ -555,6 +533,11 @@ export function resetHarness() {
mockUpdateProfile.mockResolvedValue({})
mockGetProfile.mockResolvedValue(null)
mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
+ mockD1Prepare.mockImplementation((sql: string) => ({
+ bind: (...values: unknown[]) => ({ sql, values }),
+ }))
+ mockD1Batch.mockImplementation(async (statements: unknown[]) =>
+ statements.map(() => ({ success: true, meta: { changes: 1 } })))
mockTimeoutPendingDiagnosticReportsForMachine.mockResolvedValue([])
mockGetNextPendingDiagnosticDeadlineForMachine.mockResolvedValue(null)
// Daemon-auth binds the token to a machine row for daemonId+workspace;