Skip to content

Commit bf56830

Browse files
committed
test: split compact command lifecycle coverage
1 parent a875ead commit bf56830

3 files changed

Lines changed: 328 additions & 285 deletions

File tree

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
// Tests compact-command session authority across awaited lifecycle transitions.
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { OpenClawConfig } from "../../config/config.js";
4+
import {
5+
abortEmbeddedAgentRun,
6+
buildCompactParams,
7+
compactEmbeddedAgentSession,
8+
handleCompactCommand,
9+
incrementCompactionCount,
10+
isCurrentSessionEntry,
11+
isEmbeddedAgentRunAbortableForCompaction,
12+
resetCompactCommandMocks,
13+
waitForEmbeddedAgentRunEnd,
14+
} from "./commands-compact.test-support.js";
15+
import type { HandleCommandsParams } from "./commands-types.js";
16+
17+
describe("handleCompactCommand lifecycle authority", () => {
18+
beforeEach(resetCompactCommandMocks);
19+
20+
it("does not abort the command reply run before compacting", async () => {
21+
vi.mocked(isEmbeddedAgentRunAbortableForCompaction).mockReturnValueOnce(false);
22+
vi.mocked(compactEmbeddedAgentSession).mockResolvedValueOnce({
23+
ok: true,
24+
compacted: false,
25+
});
26+
27+
const result = await handleCompactCommand(
28+
{
29+
...buildCompactParams("/compact", {
30+
commands: { text: true },
31+
channels: { whatsapp: { allowFrom: ["*"] } },
32+
} as OpenClawConfig),
33+
sessionEntry: {
34+
sessionId: "session-1",
35+
updatedAt: Date.now(),
36+
},
37+
} as HandleCommandsParams,
38+
true,
39+
);
40+
41+
expect(result?.shouldContinue).toBe(false);
42+
expect(vi.mocked(isEmbeddedAgentRunAbortableForCompaction)).toHaveBeenCalledWith("session-1");
43+
expect(vi.mocked(abortEmbeddedAgentRun)).not.toHaveBeenCalled();
44+
expect(vi.mocked(waitForEmbeddedAgentRunEnd)).not.toHaveBeenCalled();
45+
expect(vi.mocked(compactEmbeddedAgentSession)).toHaveBeenCalledOnce();
46+
});
47+
48+
it("does not abort a run after the bound session changes", async () => {
49+
vi.mocked(isCurrentSessionEntry).mockReturnValueOnce(false);
50+
vi.mocked(isEmbeddedAgentRunAbortableForCompaction).mockReturnValueOnce(true);
51+
52+
const result = await handleCompactCommand(
53+
{
54+
...buildCompactParams("/compact", {
55+
commands: { text: true },
56+
channels: { whatsapp: { allowFrom: ["*"] } },
57+
} as OpenClawConfig),
58+
sessionEntry: {
59+
sessionId: "session-1",
60+
updatedAt: Date.now(),
61+
},
62+
} as HandleCommandsParams,
63+
true,
64+
);
65+
66+
expect(result?.sessionCompaction).toEqual({
67+
compacted: false,
68+
reason: "command session changed",
69+
});
70+
expect(vi.mocked(isEmbeddedAgentRunAbortableForCompaction)).not.toHaveBeenCalled();
71+
expect(vi.mocked(abortEmbeddedAgentRun)).not.toHaveBeenCalled();
72+
expect(vi.mocked(compactEmbeddedAgentSession)).not.toHaveBeenCalled();
73+
});
74+
75+
it("waits for an active embedded run before compacting even when abort is rejected", async () => {
76+
vi.mocked(isEmbeddedAgentRunAbortableForCompaction).mockReturnValueOnce(true);
77+
vi.mocked(abortEmbeddedAgentRun).mockReturnValueOnce(false);
78+
vi.mocked(compactEmbeddedAgentSession).mockResolvedValueOnce({
79+
ok: true,
80+
compacted: false,
81+
});
82+
83+
await handleCompactCommand(
84+
{
85+
...buildCompactParams("/compact", {
86+
commands: { text: true },
87+
channels: { whatsapp: { allowFrom: ["*"] } },
88+
} as OpenClawConfig),
89+
sessionEntry: {
90+
sessionId: "session-1",
91+
updatedAt: Date.now(),
92+
},
93+
} as HandleCommandsParams,
94+
true,
95+
);
96+
97+
expect(vi.mocked(abortEmbeddedAgentRun)).toHaveBeenCalledWith("session-1");
98+
expect(vi.mocked(waitForEmbeddedAgentRunEnd)).toHaveBeenCalledWith("session-1", 15_000);
99+
expect(vi.mocked(compactEmbeddedAgentSession)).toHaveBeenCalledOnce();
100+
});
101+
102+
it("does not replace an active run when abort drain times out", async () => {
103+
vi.mocked(isEmbeddedAgentRunAbortableForCompaction).mockReturnValueOnce(true);
104+
vi.mocked(waitForEmbeddedAgentRunEnd).mockResolvedValueOnce(false);
105+
106+
const result = await handleCompactCommand(
107+
{
108+
...buildCompactParams("/compact", {
109+
commands: { text: true },
110+
channels: { whatsapp: { allowFrom: ["*"] } },
111+
} as OpenClawConfig),
112+
sessionEntry: {
113+
sessionId: "session-1",
114+
updatedAt: Date.now(),
115+
},
116+
} as HandleCommandsParams,
117+
true,
118+
);
119+
120+
expect(result).toEqual({
121+
shouldContinue: false,
122+
sessionCompaction: {
123+
compacted: false,
124+
reason: "the previous run is still stopping",
125+
},
126+
reply: {
127+
text: "⚙️ Compaction unavailable: the previous run is still stopping.",
128+
isStatusNotice: true,
129+
},
130+
});
131+
expect(vi.mocked(abortEmbeddedAgentRun)).toHaveBeenCalledWith("session-1");
132+
expect(vi.mocked(waitForEmbeddedAgentRunEnd)).toHaveBeenCalledWith("session-1", 15_000);
133+
expect(vi.mocked(compactEmbeddedAgentSession)).not.toHaveBeenCalled();
134+
});
135+
136+
it("accepts the successor session produced by context-engine accounting", async () => {
137+
let currentSessionId = "native-session";
138+
vi.mocked(isCurrentSessionEntry).mockImplementation(
139+
({ expected }) => expected.sessionId === currentSessionId,
140+
);
141+
vi.mocked(incrementCompactionCount).mockImplementationOnce(async () => {
142+
currentSessionId = "successor-session";
143+
return 1;
144+
});
145+
vi.mocked(compactEmbeddedAgentSession).mockResolvedValueOnce({
146+
ok: true,
147+
compacted: true,
148+
compactionKind: "context-engine",
149+
result: {
150+
summary: "compacted",
151+
firstKeptEntryId: "first-kept",
152+
sessionId: "successor-session",
153+
tokensBefore: 999,
154+
tokensAfter: 321,
155+
},
156+
});
157+
158+
const result = await handleCompactCommand(
159+
{
160+
...buildCompactParams("/compact", {
161+
commands: { text: true },
162+
channels: { whatsapp: { allowFrom: ["*"] } },
163+
} as OpenClawConfig),
164+
sessionEntry: {
165+
sessionId: "native-session",
166+
updatedAt: Date.now(),
167+
},
168+
} as HandleCommandsParams,
169+
true,
170+
);
171+
172+
expect(result?.sessionCompaction).toMatchObject({ compacted: true, tokensAfter: 321 });
173+
});
174+
175+
it("rejects a successor session when compaction accounting did not commit", async () => {
176+
let currentSessionId = "native-session";
177+
vi.mocked(isCurrentSessionEntry).mockImplementation(
178+
({ expected }) => expected.sessionId === currentSessionId,
179+
);
180+
vi.mocked(incrementCompactionCount).mockImplementationOnce(async () => {
181+
currentSessionId = "successor-session";
182+
return undefined;
183+
});
184+
vi.mocked(compactEmbeddedAgentSession).mockResolvedValueOnce({
185+
ok: true,
186+
compacted: true,
187+
compactionKind: "context-engine",
188+
result: {
189+
summary: "compacted",
190+
firstKeptEntryId: "first-kept",
191+
sessionId: "successor-session",
192+
tokensBefore: 999,
193+
tokensAfter: 321,
194+
},
195+
});
196+
197+
const result = await handleCompactCommand(
198+
{
199+
...buildCompactParams("/compact", {
200+
commands: { text: true },
201+
channels: { whatsapp: { allowFrom: ["*"] } },
202+
} as OpenClawConfig),
203+
sessionEntry: { sessionId: "native-session", updatedAt: Date.now() },
204+
} as HandleCommandsParams,
205+
true,
206+
);
207+
208+
expect(result?.sessionCompaction).toEqual({
209+
compacted: false,
210+
reason: "command session changed",
211+
});
212+
});
213+
});
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Shared compact-command mocks and fixtures for focused behavior suites.
2+
import { vi } from "vitest";
3+
import type { OpenClawConfig } from "../../config/config.js";
4+
import {
5+
resolveAgentDirMock,
6+
resolveSessionAgentIdMock,
7+
} from "./commands-agent-scope.test-support.js";
8+
import type { HandleCommandsParams } from "./commands-types.js";
9+
10+
vi.mock("./commands-compact.runtime.js", () => ({
11+
abortEmbeddedAgentRun: vi.fn(),
12+
compactEmbeddedAgentSession: vi.fn(),
13+
enqueueSystemEvent: vi.fn(),
14+
formatContextUsageShort: vi.fn(() => "Context 12.1k"),
15+
formatTokenCount: vi.fn((value: number) => `${value}`),
16+
incrementCompactionCount: vi.fn(),
17+
isCurrentSessionEntry: vi.fn(() => true),
18+
isEmbeddedAgentRunAbortableForCompaction: vi.fn().mockReturnValue(false),
19+
resolveFreshSessionTotalTokens: vi.fn(() => 12_345),
20+
resolveSessionFilePathOptions: vi.fn(() => ({})),
21+
waitForEmbeddedAgentRunEnd: vi.fn().mockResolvedValue(true),
22+
}));
23+
24+
export const {
25+
abortEmbeddedAgentRun,
26+
compactEmbeddedAgentSession,
27+
formatContextUsageShort,
28+
incrementCompactionCount,
29+
isCurrentSessionEntry,
30+
isEmbeddedAgentRunAbortableForCompaction,
31+
waitForEmbeddedAgentRunEnd,
32+
} = await import("./commands-compact.runtime.js");
33+
export const { handleCompactCommand } = await import("./commands-compact.js");
34+
35+
export function buildCompactParams(
36+
commandBodyNormalized: string,
37+
cfg: OpenClawConfig,
38+
): HandleCommandsParams {
39+
return {
40+
cfg,
41+
ctx: {
42+
Provider: "whatsapp",
43+
Surface: "whatsapp",
44+
CommandSource: "text",
45+
CommandBody: commandBodyNormalized,
46+
commandText: commandBodyNormalized,
47+
},
48+
command: {
49+
commandBodyNormalized,
50+
isAuthorizedSender: true,
51+
senderIsOwner: false,
52+
senderId: "owner",
53+
channel: "whatsapp",
54+
ownerList: [],
55+
},
56+
sessionKey: "agent:main:main",
57+
sessionStore: {},
58+
resolveDefaultThinkingLevel: async () => "medium",
59+
} as unknown as HandleCommandsParams;
60+
}
61+
62+
export function resetCompactCommandMocks() {
63+
vi.clearAllMocks();
64+
vi.mocked(incrementCompactionCount).mockResolvedValue(1);
65+
vi.mocked(isCurrentSessionEntry).mockReturnValue(true);
66+
resolveAgentDirMock.mockImplementation(
67+
(_cfg: unknown, agentId: string) => `/tmp/workspace/.openclaw/agents/${agentId}/agent`,
68+
);
69+
resolveSessionAgentIdMock.mockReturnValue("main");
70+
}
71+
72+
export function requireCompactEmbeddedAgentSessionCall(index = 0) {
73+
const call = vi.mocked(compactEmbeddedAgentSession).mock.calls[index]?.[0];
74+
if (!call) {
75+
throw new Error(`compactEmbeddedAgentSession call ${index} missing`);
76+
}
77+
return call;
78+
}
79+
80+
export function requireIncrementCompactionCountCall(index = 0) {
81+
const call = vi.mocked(incrementCompactionCount).mock.calls[index]?.[0];
82+
if (!call) {
83+
throw new Error(`incrementCompactionCount call ${index} missing`);
84+
}
85+
return call;
86+
}
87+
88+
export function requireResolveSessionAgentIdCall(index = 0) {
89+
const call = (
90+
resolveSessionAgentIdMock.mock.calls[index] as unknown as [unknown] | undefined
91+
)?.[0] as { sessionKey?: string; config?: OpenClawConfig } | undefined;
92+
if (!call) {
93+
throw new Error(`resolveSessionAgentId call ${index} missing`);
94+
}
95+
return call;
96+
}
97+
98+
export function requireResolveAgentDirCall(index = 0) {
99+
const call = resolveAgentDirMock.mock.calls[index] as [OpenClawConfig, string] | undefined;
100+
if (!call) {
101+
throw new Error(`resolveAgentDir call ${index} missing`);
102+
}
103+
return call;
104+
}

0 commit comments

Comments
 (0)