Skip to content

Commit 6ac998e

Browse files
Erick Kinneebrokemac79
authored andcommitted
fix(gateway): scope session list model catalog to each row's agent
Unscoped sessions.list resolved one completed catalog (the default agent's) and stamped it onto every row, so a multi-agent listing projected the default agent's thinking levels and context caps onto sessions owned by other agents whenever provider/model collided. Resolve a per-agent completed catalog map for unscoped listings (each configured agent's snapshot, read-only, never starts discovery) and select the catalog by the row's sessionAgentId. The list cache fence now advances when any row owner's catalog revision changes. Plain-array callers (search/resolve/direct listSessionsFromStore) are unchanged; scoped requests resolve exactly one agent's catalog.
1 parent ee70dbc commit 6ac998e

6 files changed

Lines changed: 288 additions & 25 deletions

File tree

‎src/gateway/server-methods/sessions-list-cache.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { readSessionAutomationVersion } from "../session-automation-index.js";
1212
import { readSessionLifecyclePersistenceVersion } from "../session-lifecycle-state.js";
1313
import { isGatewayAdmin } from "../session-sharing.js";
1414
import { readSessionTitleProjectionUnavailableVersion } from "../session-transcript-title-reader.js";
15-
import type { SessionsListResult } from "../session-utils.types.js";
15+
import type { SessionListModelCatalog, SessionsListResult } from "../session-utils.types.js";
1616
import { gatewayClientSessionCreator } from "./gateway-client-identity.js";
1717
import { readSessionsMutationVersion } from "./session-change-event.js";
1818
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
@@ -22,7 +22,7 @@ type SessionListFence = {
2222
agentDatabaseRegistryToken: symbol;
2323
incognitoDatabaseGeneration: number;
2424
lifecyclePersistenceVersion: number;
25-
modelCatalogRevision: number;
25+
modelCatalogRevision: string;
2626
sessionAutomationVersion: number;
2727
sessionIdentityMutationVersion: number;
2828
sessionsMutationVersion: number;
@@ -56,16 +56,33 @@ function readModelCatalogRevision(modelCatalog: readonly ModelCatalogEntry[] | u
5656
return revision;
5757
}
5858

59+
/**
60+
* Serializes the per-agent catalog revision set so the cache fence advances
61+
* when any row owner's catalog changes. The revision identity of each distinct
62+
* catalog array is monotonic; the string join is stable per sorted agent set.
63+
*/
64+
function readSessionListModelCatalogFence(
65+
modelCatalog: SessionListModelCatalog | undefined,
66+
): string {
67+
if (!modelCatalog || modelCatalog.size === 0) {
68+
return "none";
69+
}
70+
return [...modelCatalog.entries()]
71+
.toSorted(([left], [right]) => left.localeCompare(right))
72+
.map(([agentId, entries]) => `${agentId}:${readModelCatalogRevision(entries)}`)
73+
.join(",");
74+
}
75+
5976
function readSessionListFence(
6077
context: GatewayRequestContext,
61-
modelCatalog: readonly ModelCatalogEntry[] | undefined,
78+
modelCatalog: SessionListModelCatalog | undefined,
6279
): SessionListFence {
6380
return {
6481
agentRunIndexVersion: readAgentRunIndexVersion(),
6582
agentDatabaseRegistryToken: readOpenClawAgentDatabaseRegistryToken(),
6683
incognitoDatabaseGeneration: readOpenIncognitoAgentDatabaseGeneration(),
6784
lifecyclePersistenceVersion: readSessionLifecyclePersistenceVersion(),
68-
modelCatalogRevision: readModelCatalogRevision(modelCatalog),
85+
modelCatalogRevision: readSessionListModelCatalogFence(modelCatalog),
6986
sessionAutomationVersion: readSessionAutomationVersion(),
7087
sessionIdentityMutationVersion: readSessionIdentityMutationVersion(),
7188
sessionsMutationVersion: readSessionsMutationVersion(context),
@@ -159,7 +176,7 @@ export async function respondWithCachedSessionList(params: {
159176
client: GatewayClient | null;
160177
config: OpenClawConfig;
161178
context: GatewayRequestContext;
162-
modelCatalog?: readonly ModelCatalogEntry[];
179+
modelCatalog?: SessionListModelCatalog;
163180
request: SessionsListParams;
164181
respond: RespondFn;
165182
run: () => Promise<SessionsListResult>;
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { SessionsListParams } from "../../../packages/gateway-protocol/src/index.js";
3+
import type { ModelCatalogEntry } from "../../agents/model-catalog.types.js";
4+
import { upsertSessionEntryCore } from "../../config/sessions/session-accessor.js";
5+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
6+
import { resetAgentEventsForTest } from "../../infra/agent-events.js";
7+
import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
8+
import type { GatewaySessionRow } from "../session-utils.types.js";
9+
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js";
10+
11+
const { sessionReadHandlers } = await import("./sessions-read.js");
12+
13+
function identifiedClient(profileId: string): GatewayClient {
14+
return {
15+
connect: {
16+
minProtocol: 1,
17+
maxProtocol: 1,
18+
client: { id: "openclaw-control-ui", version: "test", platform: "test", mode: "webchat" },
19+
role: "operator",
20+
scopes: ["operator.read", "operator.write"],
21+
},
22+
authenticatedUserProfile: {
23+
profileId,
24+
displayName: profileId,
25+
hasAvatar: false,
26+
updatedAt: 1,
27+
},
28+
};
29+
}
30+
31+
function requestContext(config: OpenClawConfig): GatewayRequestContext {
32+
return {
33+
chatAbortControllers: new Map(),
34+
getRuntimeConfig: () => config,
35+
getSessionEventSubscriberConnIds: () => new Set(),
36+
loadGatewayModelCatalog: async () => [],
37+
logGateway: { debug: vi.fn() },
38+
} as unknown as GatewayRequestContext;
39+
}
40+
41+
async function listSessions(params: {
42+
client: GatewayClient;
43+
context: GatewayRequestContext;
44+
request: SessionsListParams;
45+
}) {
46+
const responses: Parameters<RespondFn>[] = [];
47+
await sessionReadHandlers["sessions.list"]?.({
48+
params: params.request,
49+
client: params.client,
50+
context: params.context,
51+
respond: (...response: Parameters<RespondFn>) => responses.push(response),
52+
} as never);
53+
expect(responses).toHaveLength(1);
54+
expect(responses[0]?.[0]).toBe(true);
55+
return responses[0]?.[1] as {
56+
count: number;
57+
nextOffset: number | null;
58+
sessions: GatewaySessionRow[];
59+
totalCount: number;
60+
};
61+
}
62+
63+
async function seedSessions(): Promise<OpenClawConfig> {
64+
const config: OpenClawConfig = {
65+
agents: { list: [{ id: "main", default: true }, { id: "work" }] },
66+
};
67+
await upsertSessionEntryCore(
68+
{ agentId: "main", sessionKey: "agent:main:active" },
69+
{
70+
sessionId: "main-active",
71+
updatedAt: 400,
72+
createdActor: { type: "human", id: "[email protected]" },
73+
visibility: "shared",
74+
},
75+
);
76+
await upsertSessionEntryCore(
77+
{ agentId: "work", sessionKey: "agent:work:active" },
78+
{
79+
sessionId: "work-active",
80+
updatedAt: 100,
81+
createdActor: { type: "human", id: "[email protected]" },
82+
visibility: "shared",
83+
},
84+
);
85+
return config;
86+
}
87+
88+
beforeEach(() => {
89+
resetAgentEventsForTest();
90+
});
91+
92+
afterEach(() => {
93+
resetAgentEventsForTest();
94+
vi.restoreAllMocks();
95+
});
96+
97+
describe("sessions.list catalog scoping", () => {
98+
it("keeps unscoped listings owner-scoped when agents have distinct completed catalogs", async () => {
99+
await withOpenClawTestState({ scenario: "minimal" }, async () => {
100+
const config = await seedSessions();
101+
config.agents = {
102+
...config.agents,
103+
defaults: { model: { primary: "dynamic-router/reasoner" } },
104+
};
105+
const mainCatalog: ModelCatalogEntry[] = [
106+
{
107+
provider: "dynamic-router",
108+
id: "reasoner",
109+
name: "Reasoner",
110+
reasoning: true,
111+
compat: { supportedReasoningEfforts: ["low", "high", "max"] },
112+
},
113+
];
114+
const workCatalog: ModelCatalogEntry[] = [
115+
{
116+
provider: "dynamic-router",
117+
id: "reasoner",
118+
name: "Reasoner",
119+
reasoning: true,
120+
compat: { supportedReasoningEfforts: ["medium"] },
121+
},
122+
];
123+
const context = {
124+
...requestContext(config),
125+
readPreparedGatewayModelCatalog: vi.fn(async (options?: { agentId?: string }) =>
126+
options?.agentId === "work" ? workCatalog : mainCatalog,
127+
),
128+
};
129+
const client = identifiedClient("[email protected]");
130+
const request = { archived: "all" as const, limit: 100 };
131+
132+
const result = await listSessions({ client, context, request });
133+
134+
const mainRow = result.sessions.find((session) => session.agentId === "main");
135+
const workRow = result.sessions.find((session) => session.agentId === "work");
136+
expect(mainRow).toBeDefined();
137+
expect(workRow).toBeDefined();
138+
expect(mainRow?.thinkingOptions).toEqual(
139+
expect.arrayContaining(["off", "low", "high", "max"]),
140+
);
141+
expect(workRow?.thinkingOptions).toEqual(expect.arrayContaining(["off", "medium"]));
142+
expect(workRow?.thinkingOptions).not.toEqual(expect.arrayContaining(["low", "high", "max"]));
143+
expect(context.readPreparedGatewayModelCatalog).toHaveBeenCalledWith({
144+
agentId: "main",
145+
});
146+
expect(context.readPreparedGatewayModelCatalog).toHaveBeenCalledWith({
147+
agentId: "work",
148+
});
149+
});
150+
});
151+
152+
it("uses only the requested agent's catalog for scoped listings", async () => {
153+
await withOpenClawTestState({ scenario: "minimal" }, async () => {
154+
const config = await seedSessions();
155+
config.agents = {
156+
...config.agents,
157+
defaults: { model: { primary: "dynamic-router/reasoner" } },
158+
};
159+
const mainCatalog: ModelCatalogEntry[] = [
160+
{
161+
provider: "dynamic-router",
162+
id: "reasoner",
163+
name: "Reasoner",
164+
reasoning: true,
165+
compat: { supportedReasoningEfforts: ["low", "high", "max"] },
166+
},
167+
];
168+
const context = {
169+
...requestContext(config),
170+
readPreparedGatewayModelCatalog: vi.fn(async () => mainCatalog),
171+
};
172+
const client = identifiedClient("[email protected]");
173+
174+
const result = await listSessions({
175+
client,
176+
context,
177+
request: { agentId: "main", archived: "all" as const, limit: 100 },
178+
});
179+
180+
expect(result.sessions.every((session) => session.agentId === "main")).toBe(true);
181+
expect(result.sessions[0]?.thinkingOptions).toEqual(
182+
expect.arrayContaining(["off", "low", "high", "max"]),
183+
);
184+
expect(context.readPreparedGatewayModelCatalog).toHaveBeenCalledTimes(1);
185+
expect(context.readPreparedGatewayModelCatalog).toHaveBeenCalledWith({
186+
agentId: "main",
187+
});
188+
});
189+
});
190+
});

‎src/gateway/server-methods/sessions-read.ts‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
validateSessionsResolveParams,
1212
validateSessionsSearchParams,
1313
} from "../../../packages/gateway-protocol/src/index.js";
14+
import { listAgentIds } from "../../agents/agent-scope-config.js";
1415
import {
1516
isPerAgentSessionStoreConfig,
1617
listSessionMembershipKeys,
@@ -211,13 +212,31 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
211212
const cfg = context.getRuntimeConfig();
212213
const configuredAgentsOnly = p.configuredAgentsOnly === true;
213214
const identityId = gatewayClientSessionCreator(client)?.id;
214-
const preparedModelCatalog = await measureDiagnosticsTimelineSpan(
215+
const preparedModelCatalogByAgent = await measureDiagnosticsTimelineSpan(
215216
"gateway.sessions.list.model_catalog",
216-
() =>
217-
readPreparedServerMethodModelCatalog(
218-
context,
219-
p.agentId ? { agentId: p.agentId } : undefined,
220-
),
217+
async () => {
218+
// Scoped listings use exactly the requested agent's completed catalog.
219+
// Unscoped listings must not apply one agent's catalog to rows owned by
220+
// another agent; resolve each configured agent's completed snapshot
221+
// (read-only, never starts discovery) so row projections stay
222+
// owner-scoped while cache reuse stays fenced per agent.
223+
if (p.agentId) {
224+
const agentId = normalizeAgentId(p.agentId);
225+
const catalog = await readPreparedServerMethodModelCatalog(context, { agentId });
226+
return new Map([[agentId, catalog]]);
227+
}
228+
const catalogByAgent = new Map<
229+
string,
230+
Awaited<ReturnType<typeof readPreparedServerMethodModelCatalog>>
231+
>();
232+
for (const agentId of listAgentIds(cfg)) {
233+
catalogByAgent.set(
234+
agentId,
235+
await readPreparedServerMethodModelCatalog(context, { agentId }),
236+
);
237+
}
238+
return catalogByAgent;
239+
},
221240
{
222241
config: cfg,
223242
phase: "sessions.list",
@@ -231,7 +250,10 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
231250
allowFullReload?: boolean;
232251
excludedKeys?: ReadonlySet<string>;
233252
loaded?: ReturnType<typeof loadCombinedSessionStoreForGatewayCore> & {
234-
modelCatalog: Awaited<ReturnType<typeof readPreparedServerMethodModelCatalog>>;
253+
modelCatalogByAgent: Map<
254+
string,
255+
Awaited<ReturnType<typeof readPreparedServerMethodModelCatalog>>
256+
>;
235257
};
236258
rowRepairAttempted?: boolean;
237259
} = {},
@@ -255,12 +277,12 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
255277
},
256278
},
257279
);
258-
loaded = { ...loadedStore, modelCatalog: preparedModelCatalog };
280+
loaded = { ...loadedStore, modelCatalogByAgent: preparedModelCatalogByAgent };
259281
}
260282
if (!loaded) {
261283
throw new Error("sessions.list store input was not loaded");
262284
}
263-
const { durableStorePath, durableTargets, modelCatalog, storePath } = loaded;
285+
const { durableStorePath, durableTargets, modelCatalogByAgent, storePath } = loaded;
264286
const visibilityFilter = createSessionListEntryFilter({ client });
265287
const entryFilter =
266288
visibilityFilter || options.excludedKeys?.size
@@ -276,7 +298,7 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
276298
...(entryFilter ? { entryFilter } : {}),
277299
storePath,
278300
store: loaded.store,
279-
modelCatalog,
301+
modelCatalog: modelCatalogByAgent,
280302
opts: p,
281303
...(p.involvingMe === true && identityId ? { involvingActorId: identityId } : {}),
282304
}),
@@ -477,7 +499,7 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
477499
client,
478500
config: cfg,
479501
context,
480-
modelCatalog: preparedModelCatalog,
502+
modelCatalog: preparedModelCatalogByAgent,
481503
request: p,
482504
respond,
483505
run,

0 commit comments

Comments
 (0)