test: streamline trigger and session coverage

This commit is contained in:
Peter Steinberger
2026-02-23 17:52:23 +00:00
parent ddc67aa4ef
commit b81bce703c
3 changed files with 48 additions and 115 deletions

View File

@@ -126,23 +126,32 @@ describe("trigger handling", () => {
expect(runEmbeddedPiAgentMock).not.toHaveBeenCalled(); expect(runEmbeddedPiAgentMock).not.toHaveBeenCalled();
}); });
}); });
it("sets per-response usage footer via /usage", async () => { it("handles explicit /usage tokens, back-compat, and cycle persistence", async () => {
await withTempHome(async (home) => {
const { blockReplies, replies } = await runCommandAndCollectReplies({
home,
body: "/usage tokens",
});
expect(blockReplies.length).toBe(0);
expect(replies.length).toBe(1);
expect(String(replies[0]?.text ?? "")).toContain("Usage footer: tokens");
expect(getRunEmbeddedPiAgentMock()).not.toHaveBeenCalled();
});
});
it("handles /usage back-compat and cycles modes, persisting to the session store", async () => {
await withTempHome(async (home) => { await withTempHome(async (home) => {
const cfg = makeCfg(home); const cfg = makeCfg(home);
const explicitTokens = await getReplyFromConfig(
{
Body: "/usage tokens",
From: "+1000",
To: "+2000",
Provider: "whatsapp",
SenderE164: "+1000",
CommandAuthorized: true,
},
undefined,
cfg,
);
expect(
String(
(Array.isArray(explicitTokens) ? explicitTokens[0]?.text : explicitTokens?.text) ?? "",
),
).toContain("Usage footer: tokens");
const explicitStore = await readSessionStore(home);
expect(pickFirstStoreEntry<{ responseUsage?: string }>(explicitStore)?.responseUsage).toBe(
"tokens",
);
const r0 = await getReplyFromConfig( const r0 = await getReplyFromConfig(
{ {
Body: "/usage on", Body: "/usage on",
@@ -158,8 +167,6 @@ describe("trigger handling", () => {
expect(String((Array.isArray(r0) ? r0[0]?.text : r0?.text) ?? "")).toContain( expect(String((Array.isArray(r0) ? r0[0]?.text : r0?.text) ?? "")).toContain(
"Usage footer: tokens", "Usage footer: tokens",
); );
const s0 = await readSessionStore(home);
expect(pickFirstStoreEntry<{ responseUsage?: string }>(s0)?.responseUsage).toBe("tokens");
const r1 = await getReplyFromConfig( const r1 = await getReplyFromConfig(
{ {
@@ -176,8 +183,6 @@ describe("trigger handling", () => {
expect(String((Array.isArray(r1) ? r1[0]?.text : r1?.text) ?? "")).toContain( expect(String((Array.isArray(r1) ? r1[0]?.text : r1?.text) ?? "")).toContain(
"Usage footer: full", "Usage footer: full",
); );
const s1 = await readSessionStore(home);
expect(pickFirstStoreEntry<{ responseUsage?: string }>(s1)?.responseUsage).toBe("full");
const r2 = await getReplyFromConfig( const r2 = await getReplyFromConfig(
{ {
@@ -194,8 +199,6 @@ describe("trigger handling", () => {
expect(String((Array.isArray(r2) ? r2[0]?.text : r2?.text) ?? "")).toContain( expect(String((Array.isArray(r2) ? r2[0]?.text : r2?.text) ?? "")).toContain(
"Usage footer: off", "Usage footer: off",
); );
const s2 = await readSessionStore(home);
expect(pickFirstStoreEntry<{ responseUsage?: string }>(s2)?.responseUsage).toBeUndefined();
const r3 = await getReplyFromConfig( const r3 = await getReplyFromConfig(
{ {
@@ -212,8 +215,10 @@ describe("trigger handling", () => {
expect(String((Array.isArray(r3) ? r3[0]?.text : r3?.text) ?? "")).toContain( expect(String((Array.isArray(r3) ? r3[0]?.text : r3?.text) ?? "")).toContain(
"Usage footer: tokens", "Usage footer: tokens",
); );
const s3 = await readSessionStore(home); const finalStore = await readSessionStore(home);
expect(pickFirstStoreEntry<{ responseUsage?: string }>(s3)?.responseUsage).toBe("tokens"); expect(pickFirstStoreEntry<{ responseUsage?: string }>(finalStore)?.responseUsage).toBe(
"tokens",
);
expect(getRunEmbeddedPiAgentMock()).not.toHaveBeenCalled(); expect(getRunEmbeddedPiAgentMock()).not.toHaveBeenCalled();
}); });

View File

@@ -66,7 +66,7 @@ async function expectResetBlockedForNonOwner(params: {
expect(getRunEmbeddedPiAgentMock()).not.toHaveBeenCalled(); expect(getRunEmbeddedPiAgentMock()).not.toHaveBeenCalled();
} }
async function expectUnauthorizedCommandDropped(home: string, body: "/status" | "/whoami") { async function expectUnauthorizedCommandDropped(home: string, body: "/status") {
const runEmbeddedPiAgentMock = getRunEmbeddedPiAgentMock(); const runEmbeddedPiAgentMock = getRunEmbeddedPiAgentMock();
const cfg = makeUnauthorizedWhatsAppCfg(home); const cfg = makeUnauthorizedWhatsAppCfg(home);
@@ -90,10 +90,7 @@ function mockEmbeddedOk() {
return mockRunEmbeddedPiAgentOk("ok"); return mockRunEmbeddedPiAgentOk("ok");
} }
async function runInlineUnauthorizedCommand(params: { async function runInlineUnauthorizedCommand(params: { home: string; command: "/status" }) {
home: string;
command: "/status" | "/help";
}) {
const cfg = makeUnauthorizedWhatsAppCfg(params.home); const cfg = makeUnauthorizedWhatsAppCfg(params.home);
const res = await getReplyFromConfig( const res = await getReplyFromConfig(
{ {
@@ -225,7 +222,7 @@ describe("trigger handling", () => {
}); });
}); });
it("handles inline help/whoami/commands and strips directives before the agent", async () => { it("handles inline commands and strips directives before the agent", async () => {
await withTempHome(async (home) => { await withTempHome(async (home) => {
const cases: Array<{ const cases: Array<{
body: string; body: string;
@@ -244,11 +241,6 @@ describe("trigger handling", () => {
blockReplyContains: "Identity", blockReplyContains: "Identity",
requestOverrides: { SenderId: "12345" }, requestOverrides: { SenderId: "12345" },
}, },
{
body: "please /help now",
stripToken: "/help",
blockReplyContains: "Help",
},
]; ];
for (const testCase of cases) { for (const testCase of cases) {
await expectInlineCommandHandledAndStripped({ await expectInlineCommandHandledAndStripped({
@@ -263,40 +255,19 @@ describe("trigger handling", () => {
}); });
}); });
it("enforces top-level command auth, keeps inline text, and handles direct /help", async () => { it("enforces top-level command auth while keeping inline text", async () => {
await withTempHome(async (home) => { await withTempHome(async (home) => {
for (const command of ["/status", "/whoami"] as const) { await expectUnauthorizedCommandDropped(home, "/status");
await expectUnauthorizedCommandDropped(home, command); const runEmbeddedPiAgentMock = mockEmbeddedOk();
} const res = await runInlineUnauthorizedCommand({
for (const command of ["/status", "/help"] as const) { home,
const runEmbeddedPiAgentMock = mockEmbeddedOk(); command: "/status",
const res = await runInlineUnauthorizedCommand({ });
home, const text = Array.isArray(res) ? res[0]?.text : res?.text;
command, expect(text).toBe("ok");
}); expect(runEmbeddedPiAgentMock).toHaveBeenCalled();
const text = Array.isArray(res) ? res[0]?.text : res?.text; const prompt = runEmbeddedPiAgentMock.mock.calls.at(-1)?.[0]?.prompt ?? "";
expect(text).toBe("ok"); expect(prompt).toContain("/status");
expect(runEmbeddedPiAgentMock).toHaveBeenCalled();
const prompt = runEmbeddedPiAgentMock.mock.calls.at(-1)?.[0]?.prompt ?? "";
expect(prompt).toContain(command);
}
const runEmbeddedPiAgentMock = getRunEmbeddedPiAgentMock();
const callsBeforeHelp = runEmbeddedPiAgentMock.mock.calls.length;
const helpRes = await getReplyFromConfig(
{
Body: "/help",
From: "+1002",
To: "+2000",
CommandAuthorized: true,
},
{},
makeCfg(home),
);
const helpText = Array.isArray(helpRes) ? helpRes[0]?.text : helpRes?.text;
expect(helpText).toContain("Help");
expect(helpText).toContain("Session");
expect(helpText).toContain("More: /commands for full list");
expect(runEmbeddedPiAgentMock.mock.calls.length).toBe(callsBeforeHelp);
}); });
}); });

View File

@@ -122,7 +122,11 @@ describe("initSessionState thread forking", () => {
const parsedHeader = JSON.parse(headerLine) as { const parsedHeader = JSON.parse(headerLine) as {
parentSession?: string; parentSession?: string;
}; };
expect(parsedHeader.parentSession).toBe(parentSessionFile); const expectedParentSession = await fs.realpath(parentSessionFile);
const actualParentSession = parsedHeader.parentSession
? await fs.realpath(parsedHeader.parentSession)
: undefined;
expect(actualParentSession).toBe(expectedParentSession);
warn.mockRestore(); warn.mockRestore();
}); });
@@ -1302,54 +1306,6 @@ describe("persistSessionUsageUpdate", () => {
}); });
describe("initSessionState stale threadId fallback", () => { describe("initSessionState stale threadId fallback", () => {
async function seedSessionStore(params: {
storePath: string;
sessionKey: string;
entry: Record<string, unknown>;
}) {
await fs.mkdir(path.dirname(params.storePath), { recursive: true });
await fs.writeFile(
params.storePath,
JSON.stringify({ [params.sessionKey]: params.entry }, null, 2),
"utf-8",
);
}
it("ignores persisted lastThreadId on main sessions for non-thread messages", async () => {
const storePath = await createStorePath("stale-main-thread-");
const sessionKey = "agent:main:main";
await seedSessionStore({
storePath,
sessionKey,
entry: {
sessionId: "s1",
updatedAt: Date.now(),
lastChannel: "telegram",
lastTo: "telegram:123",
lastThreadId: 42,
deliveryContext: {
channel: "telegram",
to: "telegram:123",
threadId: 42,
},
},
});
const cfg = { session: { store: storePath } } as OpenClawConfig;
const result = await initSessionState({
ctx: {
Body: "hello from DM",
SessionKey: sessionKey,
},
cfg,
commandAuthorized: true,
});
expect(result.sessionEntry.lastThreadId).toBeUndefined();
expect(result.sessionEntry.deliveryContext?.threadId).toBeUndefined();
});
it("does not inherit lastThreadId from a previous thread interaction in non-thread sessions", async () => { it("does not inherit lastThreadId from a previous thread interaction in non-thread sessions", async () => {
const storePath = await createStorePath("stale-thread-"); const storePath = await createStorePath("stale-thread-");
const cfg = { session: { store: storePath } } as OpenClawConfig; const cfg = { session: { store: storePath } } as OpenClawConfig;
@@ -1377,6 +1333,7 @@ describe("initSessionState stale threadId fallback", () => {
commandAuthorized: true, commandAuthorized: true,
}); });
expect(mainResult.sessionEntry.lastThreadId).toBeUndefined(); expect(mainResult.sessionEntry.lastThreadId).toBeUndefined();
expect(mainResult.sessionEntry.deliveryContext?.threadId).toBeUndefined();
}); });
it("preserves lastThreadId within the same thread session", async () => { it("preserves lastThreadId within the same thread session", async () => {