Skip to content

Commit bb1e0ce

Browse files
committed
fix(gateway): resolve SQLite usage details
1 parent 76cc60a commit bb1e0ce

2 files changed

Lines changed: 147 additions & 66 deletions

File tree

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

Lines changed: 64 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ vi.mock("../session-utils.js", async () => {
2323
const actual = await vi.importActual<typeof import("../session-utils.js")>("../session-utils.js");
2424
return {
2525
...actual,
26+
loadSessionEntryReadOnly: vi.fn(actual.loadSessionEntryReadOnly),
2627
loadCombinedSessionStoreForGateway: vi.fn(() => ({ storePath: "(multiple)", store: {} })),
2728
};
2829
});
@@ -33,6 +34,7 @@ vi.mock("../../infra/session-cost-usage.js", async () => {
3334
);
3435
return {
3536
...actual,
37+
resolveExistingUsageSessionFile: vi.fn(actual.resolveExistingUsageSessionFile),
3638
discoverAllSessions: vi.fn(async (params?: { agentId?: string }) => {
3739
if (params?.agentId === "main") {
3840
return [
@@ -100,8 +102,9 @@ import {
100102
loadSessionCostSummariesFromCache,
101103
loadSessionLogs,
102104
loadSessionUsageTimeSeries,
105+
resolveExistingUsageSessionFile,
103106
} from "../../infra/session-cost-usage.js";
104-
import { loadCombinedSessionStoreForGateway } from "../session-utils.js";
107+
import { loadCombinedSessionStoreForGateway, loadSessionEntryReadOnly } from "../session-utils.js";
105108
import { testApi, usageHandlers } from "./usage.js";
106109

107110
const TEST_RUNTIME_CONFIG = {
@@ -182,6 +185,20 @@ function expectSuccessfulSessionsUsage(
182185
return result.sessions;
183186
}
184187

188+
function mockStoredSession(key: string, sessionId: string) {
189+
const entry = { sessionId, updatedAt: 1_000 };
190+
vi.mocked(loadSessionEntryReadOnly).mockReturnValueOnce({
191+
cfg: TEST_RUNTIME_CONFIG,
192+
canonicalKey: key,
193+
entry,
194+
legacyKey: undefined,
195+
store: { [key]: entry },
196+
storeKeys: [key],
197+
storePath: "/tmp/agents/opus/sessions/sessions.json",
198+
});
199+
return entry;
200+
}
201+
185202
async function withUsageState(
186203
run: (writeSessionFile: (fileName: string) => string) => Promise<void>,
187204
) {
@@ -504,7 +521,8 @@ describe("sessions.usage", () => {
504521

505522
it("uses the requested agent for legacy specific session keys", async () => {
506523
await withUsageState(async (writeSessionFile) => {
507-
const sessionFile = writeSessionFile("main.jsonl");
524+
writeSessionFile("main.jsonl");
525+
mockStoredSession("agent:opus:main", "main");
508526

509527
vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({
510528
storePath: "(multiple)",
@@ -532,7 +550,7 @@ describe("sessions.usage", () => {
532550
agentId: "opus",
533551
sessions: expect.arrayContaining([
534552
expect.objectContaining({
535-
sessionFile: fs.realpathSync(sessionFile),
553+
sessionFile: expect.stringMatching(/^sqlite:/),
536554
sessionId: "main",
537555
}),
538556
]),
@@ -550,7 +568,8 @@ describe("sessions.usage", () => {
550568
};
551569

552570
await withUsageState(async (writeSessionFile) => {
553-
const sessionFile = writeSessionFile("current.jsonl");
571+
writeSessionFile("current.jsonl");
572+
mockStoredSession("global", "current");
554573

555574
const sessionEntry = {
556575
sessionId: "current",
@@ -583,7 +602,7 @@ describe("sessions.usage", () => {
583602
agentId: "opus",
584603
sessions: expect.arrayContaining([
585604
expect.objectContaining({
586-
sessionFile: fs.realpathSync(sessionFile),
605+
sessionFile: expect.stringMatching(/^sqlite:/),
587606
sessionId: "current",
588607
}),
589608
]),
@@ -637,6 +656,7 @@ describe("sessions.usage", () => {
637656

638657
await withUsageState(async (writeSessionFile) => {
639658
writeSessionFile("s-opus.jsonl");
659+
mockStoredSession(storeKey, "s-opus");
640660

641661
// Swap the store mock for this test: the canonical key differs from the discovered key
642662
// but points at the same sessionId.
@@ -672,6 +692,7 @@ describe("sessions.usage", () => {
672692
await withUsageState(async (writeSessionFile) => {
673693
writeSessionFile("current.jsonl");
674694
writeSessionFile("old.jsonl.reset.2026-02-01T00-00-00.000Z");
695+
mockStoredSession(storeKey, "current");
675696

676697
vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({
677698
storePath: "(multiple)",
@@ -750,6 +771,7 @@ describe("sessions.usage", () => {
750771

751772
await withUsageState(async (writeSessionFile) => {
752773
writeSessionFile("run-dup.jsonl");
774+
mockStoredSession(preferredKey, "run-dup");
753775

754776
vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({
755777
storePath: "(multiple)",
@@ -774,6 +796,13 @@ describe("sessions.usage", () => {
774796
const sessions = expectSuccessfulSessionsUsage(respond);
775797
expect(sessions).toHaveLength(1);
776798
expect(sessions[0]?.key).toBe(preferredKey);
799+
expect(vi.mocked(loadSessionCostSummariesFromCache)).toHaveBeenCalledWith(
800+
expect.objectContaining({
801+
sessions: expect.arrayContaining([
802+
expect.objectContaining({ sessionFile: expect.stringMatching(/^sqlite:/) }),
803+
]),
804+
}),
805+
);
777806
});
778807
});
779808

@@ -789,28 +818,43 @@ describe("sessions.usage", () => {
789818
expect(error?.message).toContain("Invalid session reference");
790819
});
791820

792-
it("passes parsed agentId into sessions.usage.timeseries", async () => {
793-
await runSessionsUsageTimeseries({
794-
key: "agent:opus:s-opus",
795-
});
821+
it("passes a canonical SQLite target into sessions.usage.timeseries", async () => {
822+
mockStoredSession("agent:opus:s-opus", "s-opus");
823+
await runSessionsUsageTimeseries({ key: "agent:opus:s-opus" });
796824

797-
expect(vi.mocked(loadSessionUsageTimeSeries)).toHaveBeenCalled();
798-
expect(
799-
(mockArg(vi.mocked(loadSessionUsageTimeSeries), 0, 0) as { agentId?: string }).agentId,
800-
).toBe("opus");
825+
expect(vi.mocked(loadSessionUsageTimeSeries)).toHaveBeenCalledWith(
826+
expect.objectContaining({ agentId: "opus", sessionFile: expect.stringMatching(/^sqlite:/) }),
827+
);
801828
});
802829

803-
it("passes parsed agentId into sessions.usage.logs", async () => {
804-
await runSessionsUsageLogs({
805-
key: "agent:opus:s-opus",
806-
});
830+
it("passes a canonical SQLite target into sessions.usage.logs", async () => {
831+
mockStoredSession("agent:opus:s-opus", "s-opus");
832+
await runSessionsUsageLogs({ key: "agent:opus:s-opus" });
807833

808-
expect(vi.mocked(loadSessionLogs)).toHaveBeenCalled();
809-
expect((mockArg(vi.mocked(loadSessionLogs), 0, 0) as { agentId?: string }).agentId).toBe(
810-
"opus",
834+
expect(vi.mocked(loadSessionLogs)).toHaveBeenCalledWith(
835+
expect.objectContaining({ agentId: "opus", sessionFile: expect.stringMatching(/^sqlite:/) }),
811836
);
812837
});
813838

839+
it("preserves JSONL detail lookup for storeless sessions", async () => {
840+
await withUsageState(async (writeSessionFile) => {
841+
const sessionFile = writeSessionFile("storeless.jsonl");
842+
await runSessionsUsageTimeseries({ key: "agent:opus:storeless" });
843+
expect(vi.mocked(loadSessionUsageTimeSeries)).toHaveBeenCalledWith(
844+
expect.objectContaining({ sessionFile, sessionEntry: undefined }),
845+
);
846+
});
847+
});
848+
849+
it("fails closed when a canonical stored target no longer matches", async () => {
850+
const key = "agent:opus:stale";
851+
mockStoredSession(key, "stale");
852+
vi.mocked(resolveExistingUsageSessionFile).mockReturnValueOnce(undefined);
853+
const respond = await runSessionsUsageTimeseries({ key });
854+
expect(mockArg(respond, 0, 0)).toBe(false);
855+
expect(vi.mocked(loadSessionUsageTimeSeries)).not.toHaveBeenCalled();
856+
});
857+
814858
it("rejects traversal-style keys in timeseries/log lookups", async () => {
815859
const timeseriesRespond = await runSessionsUsageTimeseries({
816860
key: "agent:opus:../../etc/passwd",

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

Lines changed: 83 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
validateSessionsUsageParams,
1010
} from "../../../packages/gateway-protocol/src/index.js";
1111
import { listAgentIds, resolveDefaultAgentId } from "../../agents/agent-scope.js";
12+
import { parseSqliteSessionFileMarker } from "../../config/sessions/legacy-sqlite-marker.js";
1213
import {
1314
resolveSessionFilePath,
1415
resolveSessionFilePathOptions,
@@ -128,6 +129,48 @@ const sessionsUsageCache = new Map<string, SessionsUsageCacheEntry>();
128129

129130
class SessionsUsageInvalidRequestError extends Error {}
130131

132+
type ResolvedSessionUsageTarget = {
133+
entry: SessionEntry | undefined;
134+
agentId: string;
135+
sessionId: string;
136+
sessionFile: string;
137+
};
138+
139+
function resolveSessionUsageTarget(
140+
key: string,
141+
config: OpenClawConfig,
142+
agentIdHint?: string,
143+
): ResolvedSessionUsageTarget | undefined {
144+
const { canonicalKey, entry, storePath } = loadSessionEntryReadOnly(
145+
key,
146+
agentIdHint ? { agentId: agentIdHint } : undefined,
147+
);
148+
const parsed = parseAgentSessionKey(key);
149+
const agentId = parsed?.agentId ?? agentIdHint ?? resolveDefaultAgentId(config);
150+
const sessionId = entry?.sessionId ?? parsed?.rest ?? key;
151+
const sessionFile = entry
152+
? resolveExistingUsageSessionFile({
153+
agentId,
154+
sessionId,
155+
sessionTarget: {
156+
agentId,
157+
sessionId,
158+
sessionKey: canonicalKey,
159+
storePath,
160+
},
161+
})
162+
: resolveExistingUsageSessionFile({
163+
agentId,
164+
sessionId,
165+
sessionFile: resolveSessionFilePath(
166+
sessionId,
167+
undefined,
168+
resolveSessionFilePathOptions({ storePath, agentId }),
169+
),
170+
});
171+
return sessionFile ? { entry, agentId, sessionId, sessionFile } : undefined;
172+
}
173+
131174
function findCostUsageCacheEvictionKey(): string | undefined {
132175
for (const [key, entry] of costUsageCache) {
133176
// Prefer evicting settled entries so duplicate callers can still join active loads.
@@ -277,34 +320,22 @@ function resolveSessionUsageFileOrRespond(
277320
key: string,
278321
respond: RespondFn,
279322
config: OpenClawConfig,
280-
): {
281-
config: OpenClawConfig;
282-
entry: SessionEntry | undefined;
283-
agentId: string;
284-
sessionId: string;
285-
sessionFile: string;
286-
} | null {
287-
const { entry, storePath } = loadSessionEntryReadOnly(key);
288-
289-
// For discovered sessions (not in store), try using key as sessionId directly
290-
const parsed = parseAgentSessionKey(key);
291-
const agentId = parsed?.agentId ?? resolveDefaultAgentId(config);
292-
const rawSessionId = parsed?.rest ?? key;
293-
const sessionId = entry?.sessionId ?? rawSessionId;
294-
let sessionFile: string;
323+
): (ResolvedSessionUsageTarget & { config: OpenClawConfig }) | null {
324+
let resolved: ResolvedSessionUsageTarget | undefined;
295325
try {
296-
const pathOpts = resolveSessionFilePathOptions({ storePath, agentId });
297-
sessionFile = resolveSessionFilePath(sessionId, entry, pathOpts);
326+
resolved = resolveSessionUsageTarget(key, config);
298327
} catch {
328+
resolved = undefined;
329+
}
330+
if (!resolved) {
299331
respond(
300332
false,
301333
undefined,
302334
errorShape(ErrorCodes.INVALID_REQUEST, `Invalid session key: ${key}`),
303335
);
304336
return null;
305337
}
306-
307-
return { config, entry, agentId, sessionId, sessionFile };
338+
return { config, ...resolved };
308339
}
309340

310341
const parseDateParts = (raw: unknown): DateParts | undefined => {
@@ -1346,7 +1377,7 @@ export const usageHandlers: GatewayRequestHandlers = {
13461377
load: async () => {
13471378
// Load session store for named sessions only on a result-cache miss.
13481379
const sessionStoreOpts = effectiveAgentId ? { agentId: effectiveAgentId } : {};
1349-
const { storePath, store } = loadCombinedSessionStoreForGateway(config, sessionStoreOpts);
1380+
const { store } = loadCombinedSessionStoreForGateway(config, sessionStoreOpts);
13501381
const scopedStore = effectiveAgentId
13511382
? filterSessionStoreByAgent({
13521383
config,
@@ -1387,47 +1418,53 @@ export const usageHandlers: GatewayRequestHandlers = {
13871418
const storeEntry = storeMatch?.entry ?? storeByIdMatch?.entry;
13881419
const sessionId = storeEntry?.sessionId ?? keyRest;
13891420

1390-
// Resolve the session file path
1391-
let sessionFile: string | undefined;
1421+
// Stored sessions are canonical SQLite targets. JSONL discovery remains only for
1422+
// sessions without a store row, so retired locators cannot redirect live state.
1423+
let resolved: ResolvedSessionUsageTarget | undefined;
13921424
try {
1393-
const pathOpts = resolveSessionFilePathOptions({
1394-
storePath: storePath !== "(multiple)" ? storePath : undefined,
1395-
agentId: agentIdFromKey,
1396-
});
1397-
sessionFile = resolveExistingUsageSessionFile({
1398-
sessionId,
1399-
sessionEntry: storeEntry,
1400-
sessionFile: resolveSessionFilePath(sessionId, storeEntry, pathOpts),
1401-
agentId: agentIdFromKey,
1402-
});
1425+
resolved = resolveSessionUsageTarget(resolvedStoreKey, config, agentIdFromKey);
1426+
if (
1427+
!resolved ||
1428+
resolved.agentId !== agentIdFromKey ||
1429+
resolved.sessionId !== sessionId
1430+
) {
1431+
throw new Error("session target mismatch");
1432+
}
14031433
} catch {
14041434
throw new SessionsUsageInvalidRequestError(
14051435
`Invalid session reference: ${specificKey}`,
14061436
);
14071437
}
1438+
const { sessionFile } = resolved;
14081439

1409-
if (sessionFile) {
1440+
let updatedAt: number | undefined;
1441+
if (parseSqliteSessionFileMarker(sessionFile)) {
1442+
updatedAt = storeEntry?.updatedAt ?? now;
1443+
} else {
14101444
try {
14111445
const stats = fs.statSync(sessionFile);
14121446
if (stats.isFile()) {
1413-
maybeMergeFamilyEntry({
1414-
mergedEntries,
1415-
groupingMode,
1416-
base: {
1417-
key: resolvedStoreKey,
1418-
agentId: agentIdFromKey,
1419-
sessionId,
1420-
sessionFile,
1421-
label: storeEntry?.label,
1422-
updatedAt: storeEntry?.updatedAt ?? stats.mtimeMs,
1423-
storeEntry,
1424-
},
1425-
});
1447+
updatedAt = storeEntry?.updatedAt ?? stats.mtimeMs;
14261448
}
14271449
} catch {
14281450
// File doesn't exist - no results for this key
14291451
}
14301452
}
1453+
if (updatedAt !== undefined) {
1454+
maybeMergeFamilyEntry({
1455+
mergedEntries,
1456+
groupingMode,
1457+
base: {
1458+
key: resolvedStoreKey,
1459+
agentId: agentIdFromKey,
1460+
sessionId,
1461+
sessionFile,
1462+
label: storeEntry?.label,
1463+
updatedAt,
1464+
storeEntry,
1465+
},
1466+
});
1467+
}
14311468
} else {
14321469
// Full discovery for list view
14331470
const discoveredSessions = await discoverAllSessionsForUsage({

0 commit comments

Comments
 (0)