refactor(tests): dedupe agent handler test scaffolding

This commit is contained in:
Peter Steinberger
2026-03-03 02:15:38 +00:00
parent 369646a513
commit d068fc9f9d

View File

@@ -118,6 +118,51 @@ function captureUpdatedMainEntry() {
return () => capturedEntry;
}
function buildExistingMainStoreEntry(overrides: Record<string, unknown> = {}) {
return {
sessionId: "existing-session-id",
updatedAt: Date.now(),
...overrides,
};
}
async function runMainAgentAndCaptureEntry(idempotencyKey: string) {
const getCapturedEntry = captureUpdatedMainEntry();
mocks.agentCommand.mockResolvedValue({
payloads: [{ text: "ok" }],
meta: { durationMs: 100 },
});
await runMainAgent("test", idempotencyKey);
expect(mocks.updateSessionStore).toHaveBeenCalled();
return getCapturedEntry();
}
function setupNewYorkTimeConfig(isoDate: string) {
vi.useFakeTimers();
vi.setSystemTime(new Date(isoDate)); // Wed Jan 28, 8:30 PM EST
mocks.agentCommand.mockClear();
mocks.loadConfigReturn = {
agents: {
defaults: {
userTimezone: "America/New_York",
},
},
};
}
function resetTimeConfig() {
mocks.loadConfigReturn = {};
vi.useRealTimers();
}
async function expectResetCall(expectedMessage: string) {
await vi.waitFor(() => expect(mocks.agentCommand).toHaveBeenCalled());
expect(mocks.sessionsResetHandler).toHaveBeenCalledTimes(1);
const call = readLastAgentCommandCall();
expect(call?.message).toBe(expectedMessage);
return call;
}
function primeMainAgentRun(params?: { sessionId?: string; cfg?: Record<string, unknown> }) {
mockMainSessionEntry(
{ sessionId: params?.sessionId ?? "existing-session-id" },
@@ -242,11 +287,7 @@ describe("gateway agent handler", () => {
let capturedEntry: Record<string, unknown> | undefined;
mocks.updateSessionStore.mockImplementation(async (_path, updater) => {
const store: Record<string, unknown> = {
"agent:main:main": {
sessionId: "existing-session-id",
updatedAt: Date.now(),
acp: existingAcpMeta,
},
"agent:main:main": buildExistingMainStoreEntry({ acp: existingAcpMeta }),
};
const result = await updater(store);
capturedEntry = store["agent:main:main"] as Record<string, unknown>;
@@ -274,34 +315,14 @@ describe("gateway agent handler", () => {
claudeCliSessionId: existingClaudeCliSessionId,
});
const getCapturedEntry = captureUpdatedMainEntry();
mocks.agentCommand.mockResolvedValue({
payloads: [{ text: "ok" }],
meta: { durationMs: 100 },
});
await runMainAgent("test", "test-idem");
expect(mocks.updateSessionStore).toHaveBeenCalled();
const capturedEntry = getCapturedEntry();
const capturedEntry = await runMainAgentAndCaptureEntry("test-idem");
expect(capturedEntry).toBeDefined();
expect(capturedEntry?.cliSessionIds).toEqual(existingCliSessionIds);
expect(capturedEntry?.claudeCliSessionId).toBe(existingClaudeCliSessionId);
});
it("injects a timestamp into the message passed to agentCommand", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-29T01:30:00.000Z")); // Wed Jan 28, 8:30 PM EST
mocks.agentCommand.mockClear();
mocks.loadConfigReturn = {
agents: {
defaults: {
userTimezone: "America/New_York",
},
},
};
setupNewYorkTimeConfig("2026-01-29T01:30:00.000Z");
primeMainAgentRun({ cfg: mocks.loadConfigReturn });
@@ -321,8 +342,7 @@ describe("gateway agent handler", () => {
const callArgs = mocks.agentCommand.mock.calls[0][0];
expect(callArgs.message).toBe("[Wed 2026-01-28 20:30 EST] Is it the weekend?");
mocks.loadConfigReturn = {};
vi.useRealTimers();
resetTimeConfig();
});
it.each([
@@ -396,12 +416,10 @@ describe("gateway agent handler", () => {
});
mocks.updateSessionStore.mockImplementation(async (_path, updater) => {
const store: Record<string, unknown> = {
"agent:main:main": {
sessionId: "existing-session-id",
updatedAt: Date.now(),
"agent:main:main": buildExistingMainStoreEntry({
lastChannel: "telegram",
lastTo: "12345",
},
}),
};
return await updater(store);
});
@@ -441,17 +459,7 @@ describe("gateway agent handler", () => {
it("handles missing cliSessionIds gracefully", async () => {
mockMainSessionEntry({});
const getCapturedEntry = captureUpdatedMainEntry();
mocks.agentCommand.mockResolvedValue({
payloads: [{ text: "ok" }],
meta: { durationMs: 100 },
});
await runMainAgent("test", "test-idem-2");
expect(mocks.updateSessionStore).toHaveBeenCalled();
const capturedEntry = getCapturedEntry();
const capturedEntry = await runMainAgentAndCaptureEntry("test-idem-2");
expect(capturedEntry).toBeDefined();
// Should be undefined, not cause an error
expect(capturedEntry?.cliSessionIds).toBeUndefined();
@@ -517,25 +525,13 @@ describe("gateway agent handler", () => {
{ reqId: "4" },
);
await vi.waitFor(() => expect(mocks.agentCommand).toHaveBeenCalled());
expect(mocks.sessionsResetHandler).toHaveBeenCalledTimes(1);
const call = readLastAgentCommandCall();
expect(call?.message).toBe(BARE_SESSION_RESET_PROMPT);
const call = await expectResetCall(BARE_SESSION_RESET_PROMPT);
expect(call?.message).toContain("Execute your Session Startup sequence now");
expect(call?.sessionId).toBe("reset-session-id");
});
it("uses /reset suffix as the post-reset message and still injects timestamp", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-29T01:30:00.000Z")); // Wed Jan 28, 8:30 PM EST
mocks.agentCommand.mockClear();
mocks.loadConfigReturn = {
agents: {
defaults: {
userTimezone: "America/New_York",
},
},
};
setupNewYorkTimeConfig("2026-01-29T01:30:00.000Z");
mockSessionResetSuccess({ reason: "reset" });
mocks.sessionsResetHandler.mockClear();
primeMainAgentRun({
@@ -552,14 +548,10 @@ describe("gateway agent handler", () => {
{ reqId: "4b" },
);
await vi.waitFor(() => expect(mocks.agentCommand).toHaveBeenCalled());
expect(mocks.sessionsResetHandler).toHaveBeenCalledTimes(1);
const call = readLastAgentCommandCall();
expect(call?.message).toBe("[Wed 2026-01-28 20:30 EST] check status");
const call = await expectResetCall("[Wed 2026-01-28 20:30 EST] check status");
expect(call?.sessionId).toBe("reset-session-id");
mocks.loadConfigReturn = {};
vi.useRealTimers();
resetTimeConfig();
});
it("rejects malformed agent session keys early in agent handler", async () => {