Skip to content

Commit d12c92c

Browse files
authored
fix(usage): roll up session lineage history
Summary: - Roll up transcript-backed session usage across logical session lineage. - Preserve lineage through /new and /reset rotations. - Add Control UI usage scope controls with legacy gateway fallback. - Refresh generated protocol and Control UI locale fallback surfaces. Verification: - pnpm test src/auto-reply/reply/session.test.ts ui/src/ui/controllers/usage.node.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts - pnpm protocol:check - pnpm ui:i18n:check - pnpm ui:build - git diff --check - PR CI green on 10f1085 Closes #50701.
1 parent 737e570 commit d12c92c

76 files changed

Lines changed: 1299 additions & 145 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Docs: https://docs.openclaw.ai
66

77
### Changes
88

9+
- Control UI/usage: add transcript-backed historical lineage rollups for rotated logical sessions, with current-instance vs historical-lineage scope controls and long-range presets so usage history stays visible after restarts and updates. Fixes #50701. Thanks @dev-gideon-llc and @BunsDev.
910
- Agents/failover: harden state-aware lane suspension by persisting quota resume transitions, restoring configured lane concurrency, preserving non-quota failure reasons, and exporting model failover events through diagnostics OTLP. Thanks @BunsDev.
1011
- Channels/streaming: make progress draft labels scroll away with other progress lines, render structured tool rows as compact emoji/title/details, show web-search queries from provider-native argument shapes, and skip empty Discord apply-patch starts until a patch summary exists. (#79146)
1112
- Telegram: preserve the channel-specific 10-option poll cap in the unified outbound adapter so over-limit polls are rejected before send. (#78762) Thanks @obviyus.

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2243,6 +2243,9 @@ public struct SessionsUsageParams: Codable, Sendable {
22432243
public let startdate: String?
22442244
public let enddate: String?
22452245
public let mode: AnyCodable?
2246+
public let range: AnyCodable?
2247+
public let groupby: AnyCodable?
2248+
public let includehistorical: Bool?
22462249
public let utcoffset: String?
22472250
public let limit: Int?
22482251
public let includecontextweight: Bool?
@@ -2252,6 +2255,9 @@ public struct SessionsUsageParams: Codable, Sendable {
22522255
startdate: String?,
22532256
enddate: String?,
22542257
mode: AnyCodable?,
2258+
range: AnyCodable?,
2259+
groupby: AnyCodable?,
2260+
includehistorical: Bool?,
22552261
utcoffset: String?,
22562262
limit: Int?,
22572263
includecontextweight: Bool?)
@@ -2260,6 +2266,9 @@ public struct SessionsUsageParams: Codable, Sendable {
22602266
self.startdate = startdate
22612267
self.enddate = enddate
22622268
self.mode = mode
2269+
self.range = range
2270+
self.groupby = groupby
2271+
self.includehistorical = includehistorical
22632272
self.utcoffset = utcoffset
22642273
self.limit = limit
22652274
self.includecontextweight = includecontextweight
@@ -2270,6 +2279,9 @@ public struct SessionsUsageParams: Codable, Sendable {
22702279
case startdate = "startDate"
22712280
case enddate = "endDate"
22722281
case mode
2282+
case range
2283+
case groupby = "groupBy"
2284+
case includehistorical = "includeHistorical"
22732285
case utcoffset = "utcOffset"
22742286
case limit
22752287
case includecontextweight = "includeContextWeight"

‎src/auto-reply/reply/agent-runner-session-reset.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ export async function resetReplyRunSession(params: {
6262
sessionId: nextSessionId,
6363
updatedAt: now,
6464
sessionStartedAt: now,
65+
usageFamilyKey: prevEntry.usageFamilyKey ?? params.sessionKey,
66+
usageFamilySessionIds: Array.from(
67+
new Set([...(prevEntry.usageFamilySessionIds ?? []), prevEntry.sessionId, nextSessionId]),
68+
),
6569
lastInteractionAt: now,
6670
systemSent: false,
6771
abortedLastRun: false,

‎src/auto-reply/reply/session-updates.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,10 @@ export async function incrementCompactionCount(params: {
278278
storePath,
279279
newSessionId,
280280
});
281+
updates.usageFamilyKey = entry.usageFamilyKey ?? sessionKey;
282+
updates.usageFamilySessionIds = Array.from(
283+
new Set([...(entry.usageFamilySessionIds ?? []), entry.sessionId, newSessionId]),
284+
);
281285
} else if (sessionFileChanged && explicitNewSessionFile) {
282286
updates.sessionFile = explicitNewSessionFile;
283287
}

‎src/auto-reply/reply/session.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2178,6 +2178,69 @@ describe("initSessionState preserves behavior overrides across /new and /reset",
21782178
}
21792179
});
21802180

2181+
it("preserves usage family metadata across /new and /reset", async () => {
2182+
const storePath = await createStorePath("openclaw-reset-usage-family-");
2183+
const sessionKey = "agent:main:telegram:dm:user-usage-family";
2184+
const existingSessionId = "existing-session-usage-family";
2185+
const cases = [
2186+
{
2187+
name: "new preserves usage family metadata",
2188+
body: "/new",
2189+
},
2190+
{
2191+
name: "reset preserves usage family metadata",
2192+
body: "/reset",
2193+
},
2194+
] as const;
2195+
2196+
for (const testCase of cases) {
2197+
await seedSessionStoreWithOverrides({
2198+
storePath,
2199+
sessionKey,
2200+
sessionId: existingSessionId,
2201+
overrides: {
2202+
usageFamilyKey: "family:user-usage-family",
2203+
usageFamilySessionIds: ["ancestor-session", existingSessionId],
2204+
},
2205+
});
2206+
2207+
const result = await initSessionState({
2208+
ctx: {
2209+
Body: testCase.body,
2210+
RawBody: testCase.body,
2211+
CommandBody: testCase.body,
2212+
From: "user-usage-family",
2213+
To: "bot",
2214+
ChatType: "direct",
2215+
SessionKey: sessionKey,
2216+
Provider: "telegram",
2217+
Surface: "telegram",
2218+
},
2219+
cfg: {
2220+
session: { store: storePath, idleMinutes: 999 },
2221+
} as OpenClawConfig,
2222+
commandAuthorized: true,
2223+
});
2224+
2225+
expect(result.resetTriggered, testCase.name).toBe(true);
2226+
expect(result.sessionId, testCase.name).not.toBe(existingSessionId);
2227+
expect(result.sessionEntry.usageFamilyKey, testCase.name).toBe("family:user-usage-family");
2228+
expect(result.sessionEntry.usageFamilySessionIds, testCase.name).toEqual([
2229+
"ancestor-session",
2230+
existingSessionId,
2231+
result.sessionId,
2232+
]);
2233+
2234+
const stored = JSON.parse(await fs.readFile(storePath, "utf-8"));
2235+
expect(stored[sessionKey].usageFamilyKey, testCase.name).toBe("family:user-usage-family");
2236+
expect(stored[sessionKey].usageFamilySessionIds, testCase.name).toEqual([
2237+
"ancestor-session",
2238+
existingSessionId,
2239+
result.sessionId,
2240+
]);
2241+
}
2242+
});
2243+
21812244
it("preserves selected auth profile overrides across /new and /reset", async () => {
21822245
const storePath = await createStorePath("openclaw-reset-model-auth-");
21832246
const sessionKey = "agent:main:telegram:dm:user-model-auth";

‎src/auto-reply/reply/session.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,18 @@ export async function initSessionState(params: {
544544
}
545545

546546
const baseEntry = !isNewSession && freshEntry ? entry : undefined;
547+
const usageFamilyKey = previousSessionEntry
548+
? (previousSessionEntry.usageFamilyKey ?? sessionKey)
549+
: baseEntry?.usageFamilyKey;
550+
const usageFamilySessionIds = previousSessionEntry
551+
? Array.from(
552+
new Set([
553+
...(previousSessionEntry.usageFamilySessionIds ?? []),
554+
previousSessionEntry.sessionId,
555+
sessionId,
556+
]),
557+
)
558+
: baseEntry?.usageFamilySessionIds;
547559
// Track the originating channel/to for announce routing (subagent announce-back).
548560
const originatingChannelRaw = ctx.OriginatingChannel as string | undefined;
549561
const isInterSession = isInterSessionInputProvenance(ctx.InputProvenance);
@@ -626,6 +638,8 @@ export async function initSessionState(params: {
626638
reasoningLevel: persistedReasoning ?? baseEntry?.reasoningLevel,
627639
ttsAuto: persistedTtsAuto ?? baseEntry?.ttsAuto,
628640
responseUsage: baseEntry?.responseUsage,
641+
usageFamilyKey,
642+
usageFamilySessionIds,
629643
modelOverride: persistedModelOverride ?? baseEntry?.modelOverride,
630644
providerOverride: persistedProviderOverride ?? baseEntry?.providerOverride,
631645
modelOverrideSource: persistedModelOverrideSource ?? baseEntry?.modelOverrideSource,

‎src/config/sessions/types.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,10 @@ export type SessionEntry = {
220220
quotaSuspension?: QuotaSuspension;
221221
/** Timestamp (ms) when the current sessionId first became active. */
222222
sessionStartedAt?: number;
223+
/** Stable usage lineage key for transcript-backed rollups across sessionId rotations. */
224+
usageFamilyKey?: string;
225+
/** Session ids known to belong to this usage lineage, including archived predecessors. */
226+
usageFamilySessionIds?: string[];
223227
/** Timestamp (ms) of the last user/channel interaction that should extend idle lifetime. */
224228
lastInteractionAt?: number;
225229
/** Stable first-run start time for subagent sessions, persisted after completion. */

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,20 @@ export const SessionsUsageParamsSchema = Type.Object(
346346
mode: Type.Optional(
347347
Type.Union([Type.Literal("utc"), Type.Literal("gateway"), Type.Literal("specific")]),
348348
),
349+
/** Preset range for usage queries when explicit start/end dates are omitted. */
350+
range: Type.Optional(
351+
Type.Union([
352+
Type.Literal("7d"),
353+
Type.Literal("30d"),
354+
Type.Literal("90d"),
355+
Type.Literal("1y"),
356+
Type.Literal("all"),
357+
]),
358+
),
359+
/** Usage row grouping. `family` rolls up known rotated session ids for a logical key. */
360+
groupBy: Type.Optional(Type.Union([Type.Literal("instance"), Type.Literal("family")])),
361+
/** Backward-compatible alias for requesting family grouping. */
362+
includeHistorical: Type.Optional(Type.Boolean()),
349363
/** UTC offset to use when mode is `specific` (for example, UTC-4 or UTC+5:30). */
350364
utcOffset: Type.Optional(Type.String({ pattern: "^UTC[+-]\\d{1,2}(?::[0-5]\\d)?$" })),
351365
/** Maximum sessions to return (default 50). */

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

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,98 @@ describe("sessions.usage", () => {
214214
}
215215
});
216216

217+
it("rolls up known session family ids when historical usage is requested", async () => {
218+
const storeKey = "agent:opus:main";
219+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-usage-test-"));
220+
221+
try {
222+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
223+
const agentSessionsDir = path.join(stateDir, "agents", "opus", "sessions");
224+
fs.mkdirSync(agentSessionsDir, { recursive: true });
225+
fs.writeFileSync(path.join(agentSessionsDir, "current.jsonl"), "", "utf-8");
226+
fs.writeFileSync(
227+
path.join(agentSessionsDir, "old.jsonl.reset.2026-02-01T00-00-00.000Z"),
228+
"",
229+
"utf-8",
230+
);
231+
232+
vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({
233+
storePath: "(multiple)",
234+
store: {
235+
[storeKey]: {
236+
sessionId: "current",
237+
sessionFile: "current.jsonl",
238+
updatedAt: 1_000,
239+
usageFamilyKey: storeKey,
240+
usageFamilySessionIds: ["old", "current"],
241+
},
242+
},
243+
});
244+
vi.mocked(loadSessionCostSummaryFromCache).mockImplementation(async ({ sessionId }) => ({
245+
summary: {
246+
input: sessionId === "old" ? 10 : 20,
247+
output: 0,
248+
cacheRead: 0,
249+
cacheWrite: 0,
250+
totalTokens: sessionId === "old" ? 10 : 20,
251+
totalCost: sessionId === "old" ? 0.01 : 0.02,
252+
inputCost: sessionId === "old" ? 0.01 : 0.02,
253+
outputCost: 0,
254+
cacheReadCost: 0,
255+
cacheWriteCost: 0,
256+
missingCostEntries: 0,
257+
messageCounts: {
258+
total: 1,
259+
user: 1,
260+
assistant: 0,
261+
toolCalls: 0,
262+
toolResults: 0,
263+
errors: 0,
264+
},
265+
},
266+
cacheStatus: {
267+
status: "fresh",
268+
cachedFiles: 1,
269+
pendingFiles: 0,
270+
staleFiles: 0,
271+
},
272+
}));
273+
274+
const respond = await runSessionsUsage({
275+
...BASE_USAGE_RANGE,
276+
key: storeKey,
277+
groupBy: "family",
278+
includeHistorical: true,
279+
});
280+
281+
expect(respond).toHaveBeenCalledTimes(1);
282+
expect(respond.mock.calls[0]?.[0]).toBe(true);
283+
const result = respond.mock.calls[0]?.[1] as {
284+
sessions: Array<{
285+
key: string;
286+
scope?: string;
287+
includedSessionIds?: string[];
288+
usage?: { totalTokens: number; totalCost: number; messageCounts?: { total: number } };
289+
}>;
290+
totals: { totalTokens: number; totalCost: number };
291+
};
292+
expect(result.sessions).toHaveLength(1);
293+
expect(result.sessions[0]).toMatchObject({
294+
key: storeKey,
295+
scope: "family",
296+
includedSessionIds: ["current", "old"],
297+
});
298+
expect(result.sessions[0]?.usage?.totalTokens).toBe(30);
299+
expect(result.sessions[0]?.usage?.totalCost).toBeCloseTo(0.03);
300+
expect(result.sessions[0]?.usage?.messageCounts?.total).toBe(2);
301+
expect(result.totals.totalTokens).toBe(30);
302+
expect(result.totals.totalCost).toBeCloseTo(0.03);
303+
});
304+
} finally {
305+
fs.rmSync(stateDir, { recursive: true, force: true });
306+
}
307+
});
308+
217309
it("prefers the deterministic store key when duplicate sessionIds exist", async () => {
218310
const preferredKey = "agent:opus:acp:run-dup";
219311
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-usage-test-"));

0 commit comments

Comments
 (0)