Skip to content

Commit 99bd275

Browse files
Alix-007Alix-007
andauthored
fix(ui): scope usage by agent filter
Fixes #87132. Default Usage now requests all configured agents with `agentScope: "all"`, while selecting a specific agent sends `agentId` consistently to both session usage and cost usage calls. The gateway now supports explicit all-agent session usage, aggregates all-agent cost summaries across configured agents, and keeps scoped cache entries separate. Legacy gateway fallbacks remain for older `agentId` / `agentScope` support, with protocol docs/schema and Swift generated models updated. Verification: - `node scripts/run-vitest.mjs ui/src/ui/controllers/usage.node.test.ts ui/src/ui/app-render-usage-tab.test.ts ui/src/ui/views/usage.test.ts --reporter=dot` - `node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-methods.config.ts src/gateway/server-methods/usage.test.ts src/gateway/server-methods/usage.cost-usage-cache.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts --reporter=dot` - `pnpm check:test-types` - `pnpm protocol:check` - targeted `node scripts/run-oxlint.mjs ...` - `git diff --check` - autoreview clean after Swift compatibility fix - PR CI green at head `d67156a3c552c4f9c8b6edf8516b6242bf5cdd26` Co-authored-by: Alix-007 <[email protected]>
1 parent d4021d1 commit 99bd275

17 files changed

Lines changed: 808 additions & 41 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2379,6 +2379,7 @@ public struct SessionsCompactParams: Codable, Sendable {
23792379
public struct SessionsUsageParams: Codable, Sendable {
23802380
public let key: String?
23812381
public let agentid: String?
2382+
public let agentscope: String?
23822383
public let startdate: String?
23832384
public let enddate: String?
23842385
public let mode: AnyCodable?
@@ -2392,6 +2393,7 @@ public struct SessionsUsageParams: Codable, Sendable {
23922393
public init(
23932394
key: String?,
23942395
agentid: String? = nil,
2396+
agentscope: String? = nil,
23952397
startdate: String?,
23962398
enddate: String?,
23972399
mode: AnyCodable?,
@@ -2404,6 +2406,7 @@ public struct SessionsUsageParams: Codable, Sendable {
24042406
{
24052407
self.key = key
24062408
self.agentid = agentid
2409+
self.agentscope = agentscope
24072410
self.startdate = startdate
24082411
self.enddate = enddate
24092412
self.mode = mode
@@ -2418,6 +2421,7 @@ public struct SessionsUsageParams: Codable, Sendable {
24182421
private enum CodingKeys: String, CodingKey {
24192422
case key
24202423
case agentid = "agentId"
2424+
case agentscope = "agentScope"
24212425
case startdate = "startDate"
24222426
case enddate = "endDate"
24232427
case mode

‎docs/gateway/protocol.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,9 +347,11 @@ enumeration of `src/gateway/server-methods/*.ts`.
347347
- `models.list` returns the runtime-allowed model catalog. Pass `{ "view": "configured" }` for picker-sized configured models (`agents.defaults.models` first, then `models.providers.*.models`), or `{ "view": "all" }` for the full catalog.
348348
- `usage.status` returns provider usage windows/remaining quota summaries.
349349
- `usage.cost` returns aggregated cost usage summaries for a date range.
350+
Pass `agentId` for one agent, or `agentScope: "all"` to aggregate configured agents.
350351
- `doctor.memory.status` returns vector-memory / cached embedding readiness for the active default agent workspace. Pass `{ "probe": true }` or `{ "deep": true }` only when the caller explicitly wants a live embedding provider ping.
351352
- `doctor.memory.remHarness` returns a bounded, read-only REM harness preview for remote control-plane clients. It can include workspace paths, memory snippets, rendered grounded markdown, and deep promotion candidates, so callers need `operator.read`.
352-
- `sessions.usage` returns per-session usage summaries.
353+
- `sessions.usage` returns per-session usage summaries. Pass `agentId` for one
354+
agent, or `agentScope: "all"` to list configured agents together.
353355
- `sessions.usage.timeseries` returns timeseries usage for one session.
354356
- `sessions.usage.logs` returns usage log entries for one session.
355357

‎scripts/protocol-gen-swift.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const STRICT_LITERAL_STRUCTS = new Set([
4242

4343
const DEFAULTED_OPTIONAL_INIT_PARAMS: Record<string, Set<string>> = {
4444
SessionsAbortParams: new Set(["agentId"]),
45-
SessionsUsageParams: new Set(["agentId"]),
45+
SessionsUsageParams: new Set(["agentId", "agentScope"]),
4646
ArtifactsListParams: new Set(["agentId"]),
4747
ArtifactsGetParams: new Set(["agentId"]),
4848
ArtifactsDownloadParams: new Set(["agentId"]),

‎src/gateway/protocol/schema/sessions.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,8 @@ export const SessionsUsageParamsSchema = Type.Object(
358358
key: Type.Optional(NonEmptyString),
359359
/** Agent scope for list-style usage queries. */
360360
agentId: Type.Optional(NonEmptyString),
361+
/** Explicit all-agent scope for list-style usage queries. */
362+
agentScope: Type.Optional(Type.Literal("all")),
361363
/** Start date for range filter (YYYY-MM-DD). */
362364
startDate: Type.Optional(Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}$" })),
363365
/** End date for range filter (YYYY-MM-DD). */

‎src/gateway/server-methods/usage.cost-usage-cache.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,14 @@ describe("costUsageCache bounded growth", () => {
8686
// oldest-first, never the newest.
8787
const lastStartMs = Date.UTC(2026, 0, 1) + (ITERATIONS - 1) * DAY_MS;
8888
const lastEndMs = lastStartMs + ((ITERATIONS - 1) % 3 === 0 ? DAY_MS : 7 * DAY_MS) - 1;
89-
const lastCacheKey = `${lastStartMs}-${lastEndMs}`;
89+
const lastCacheKey = `agent:__default__:${lastStartMs}-${lastEndMs}`;
9090
expect(testApi.costUsageCache.has(lastCacheKey)).toBe(true);
9191

9292
// Tertiary: the oldest entry must have been evicted once the cap was
9393
// exceeded. Pre-fix all 600 entries remain and this fails too.
9494
const firstStartMs = Date.UTC(2026, 0, 1);
9595
const firstEndMs = firstStartMs + DAY_MS - 1;
96-
const firstCacheKey = `${firstStartMs}-${firstEndMs}`;
96+
const firstCacheKey = `agent:__default__:${firstStartMs}-${firstEndMs}`;
9797
expect(testApi.costUsageCache.has(firstCacheKey)).toBe(false);
9898
});
9999

@@ -125,7 +125,7 @@ describe("costUsageCache bounded growth", () => {
125125
});
126126
await Promise.resolve();
127127

128-
expect(testApi.costUsageCache.has("1-2")).toBe(true);
128+
expect(testApi.costUsageCache.has("agent:__default__:1-2")).toBe(true);
129129
expect(mocks.loadCostUsageSummaryFromCache).toHaveBeenCalledTimes(257);
130130
void inFlight.catch(() => {});
131131
void repeated.catch(() => {});

‎src/gateway/server-methods/usage.sessions-usage.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,45 @@ describe("sessions.usage", () => {
194194
expect(sessions[0].agentId).toBe("main");
195195
});
196196

197+
it("uses explicit all-agent scope for list-style usage queries", async () => {
198+
const respond = await runSessionsUsage({ ...BASE_USAGE_RANGE, agentScope: "all" });
199+
200+
expect(vi.mocked(loadCombinedSessionStoreForGateway)).toHaveBeenCalledWith(
201+
TEST_RUNTIME_CONFIG,
202+
{},
203+
);
204+
expect(vi.mocked(discoverAllSessions)).toHaveBeenCalledTimes(2);
205+
expect(
206+
vi
207+
.mocked(discoverAllSessions)
208+
.mock.calls.map((call) => (call[0] as { agentId?: string }).agentId),
209+
).toEqual(["main", "opus"]);
210+
211+
const sessions = expectSuccessfulSessionsUsage(respond);
212+
expect(sessions.map((session) => session.key)).toEqual([
213+
"agent:opus:s-opus",
214+
"agent:main:s-main",
215+
]);
216+
expect(sessions.map((session) => session.agentId)).toEqual(["opus", "main"]);
217+
});
218+
219+
it("rejects all-agent scope with a specific agent or key", async () => {
220+
const withAgent = await runSessionsUsage({
221+
...BASE_USAGE_RANGE,
222+
agentId: "opus",
223+
agentScope: "all",
224+
});
225+
const withKey = await runSessionsUsage({
226+
...BASE_USAGE_RANGE,
227+
key: "agent:opus:s-opus",
228+
agentScope: "all",
229+
});
230+
231+
expect(mockArg(withAgent, 0, 0)).toBe(false);
232+
expect(mockArg(withKey, 0, 0)).toBe(false);
233+
expect(vi.mocked(discoverAllSessions)).not.toHaveBeenCalled();
234+
});
235+
197236
it("uses the requested agent for list-style usage queries", async () => {
198237
const respond = await runSessionsUsage({ ...BASE_USAGE_RANGE, agentId: "opus" });
199238

‎src/gateway/server-methods/usage.test.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,25 @@ vi.mock("../../infra/session-cost-usage.js", async () => {
1212
startDate: "2026-02-01",
1313
endDate: "2026-02-02",
1414
daily: [],
15-
totals: { totalTokens: 1, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalCost: 0 },
15+
totals: {
16+
input: 0,
17+
output: 0,
18+
cacheRead: 0,
19+
cacheWrite: 0,
20+
totalTokens: 1,
21+
totalCost: 0,
22+
inputCost: 0,
23+
outputCost: 0,
24+
cacheReadCost: 0,
25+
cacheWriteCost: 0,
26+
missingCostEntries: 0,
27+
},
1628
})),
1729
};
1830
});
1931

2032
import { loadCostUsageSummaryFromCache } from "../../infra/session-cost-usage.js";
21-
import { testApi } from "./usage.js";
33+
import { testApi, usageHandlers } from "./usage.js";
2234

2335
describe("gateway usage helpers", () => {
2436
const dayMs = 24 * 60 * 60 * 1000;
@@ -161,4 +173,78 @@ describe("gateway usage helpers", () => {
161173
"background",
162174
);
163175
});
176+
177+
it("keeps cost usage cache entries scoped by agentId", async () => {
178+
const config = {} as OpenClawConfig;
179+
180+
await testApi.loadCostUsageSummaryCached({
181+
startMs: 1,
182+
endMs: 2,
183+
config,
184+
agentId: "main",
185+
});
186+
await testApi.loadCostUsageSummaryCached({
187+
startMs: 1,
188+
endMs: 2,
189+
config,
190+
agentId: "research",
191+
});
192+
await testApi.loadCostUsageSummaryCached({
193+
startMs: 1,
194+
endMs: 2,
195+
config,
196+
agentId: "research",
197+
});
198+
199+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledTimes(2);
200+
expect(vi.mocked(loadCostUsageSummaryFromCache).mock.calls.at(0)?.[0]).toMatchObject({
201+
agentId: "main",
202+
});
203+
expect(vi.mocked(loadCostUsageSummaryFromCache).mock.calls.at(1)?.[0]).toMatchObject({
204+
agentId: "research",
205+
});
206+
});
207+
208+
it("passes usage.cost agentId through to the cost summary loader", async () => {
209+
const respond = vi.fn();
210+
211+
await usageHandlers["usage.cost"]({
212+
respond,
213+
params: { startDate: "2026-02-01", endDate: "2026-02-02", agentId: "research" },
214+
context: { getRuntimeConfig: () => ({}) },
215+
} as unknown as Parameters<(typeof usageHandlers)["usage.cost"]>[0]);
216+
217+
expect(respond).toHaveBeenCalledWith(true, expect.any(Object), undefined);
218+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledWith(
219+
expect.objectContaining({ agentId: "research" }),
220+
);
221+
});
222+
223+
it("passes usage.cost all-agent scope through to all configured agent loaders", async () => {
224+
const respond = vi.fn();
225+
226+
await usageHandlers["usage.cost"]({
227+
respond,
228+
params: { startDate: "2026-02-01", endDate: "2026-02-02", agentScope: "all" },
229+
context: {
230+
getRuntimeConfig: () => ({
231+
agents: { list: [{ id: "main" }, { id: "research" }] },
232+
}),
233+
},
234+
} as unknown as Parameters<(typeof usageHandlers)["usage.cost"]>[0]);
235+
236+
expect(respond).toHaveBeenCalledWith(
237+
true,
238+
expect.objectContaining({
239+
totals: expect.objectContaining({ totalTokens: 2 }),
240+
}),
241+
undefined,
242+
);
243+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledWith(
244+
expect.objectContaining({ agentId: "main" }),
245+
);
246+
expect(vi.mocked(loadCostUsageSummaryFromCache)).toHaveBeenCalledWith(
247+
expect.objectContaining({ agentId: "research" }),
248+
);
249+
});
164250
});

0 commit comments

Comments
 (0)