fix: validate embedded chat history limits

This commit is contained in:
Peter Steinberger
2026-05-28 20:56:45 -04:00
parent f7b0b5429e
commit 7bf100b028
2 changed files with 49 additions and 1 deletions

View File

@@ -132,4 +132,51 @@ describe("embedded gateway stub", () => {
},
);
});
it("normalizes string chat history limits before projection", async () => {
const rawMessages = [
{ role: "user", content: "older" },
{ role: "assistant", content: "newer" },
];
runtime.readSessionMessagesAsync.mockResolvedValueOnce(rawMessages);
const callGateway = createEmbeddedCallGateway();
await callGateway<{ messages: unknown[] }>({
method: "chat.history",
params: { sessionKey: "agent:main:main", limit: "2" },
});
expect(runtime.projectRecentChatDisplayMessages).toHaveBeenCalledWith(rawMessages, {
maxChars: 100_000,
maxMessages: 2,
});
expect(runtime.readSessionMessagesAsync).toHaveBeenCalledWith(
"sess-main",
"/tmp/openclaw-sessions.json",
undefined,
{
mode: "recent",
maxMessages: 2,
maxBytes: 1024 * 1024,
},
);
});
it("rejects malformed chat history limits before reading session files", async () => {
const callGateway = createEmbeddedCallGateway();
await expect(
callGateway({
method: "chat.history",
params: { sessionKey: "agent:main:main", limit: "2.5" },
}),
).rejects.toThrow("limit must be a positive integer");
await expect(
callGateway({
method: "chat.history",
params: { sessionKey: "agent:main:main", limit: -1 },
}),
).rejects.toThrow("limit must be a positive integer");
expect(runtime.readSessionMessagesAsync).not.toHaveBeenCalled();
});
});

View File

@@ -4,6 +4,7 @@ import type { SessionsListParams, SessionsResolveParams } from "../../gateway/pr
import type { ReadSessionMessagesAsyncOptions } from "../../gateway/session-utils.fs.js";
import type { SessionsListResult } from "../../gateway/session-utils.types.js";
import type { SessionsResolveResult } from "../../gateway/sessions-resolve.js";
import { readPositiveIntegerParam } from "./common.js";
type EmbeddedCallGateway = <T = Record<string, unknown>>(opts: CallGatewayOptions) => Promise<T>;
@@ -108,7 +109,7 @@ async function handleChatHistory(params: Record<string, unknown>): Promise<{
const rt = await getRuntime();
const sessionKey = typeof params.sessionKey === "string" ? params.sessionKey : "";
const limit = typeof params.limit === "number" ? params.limit : undefined;
const limit = readPositiveIntegerParam(params, "limit");
const { cfg, storePath, entry } = rt.loadSessionEntry(sessionKey);
const sessionId = entry?.sessionId as string | undefined;