mirror of
https://github.com/openclaw/openclaw.git
synced 2026-04-19 11:18:37 +00:00
chore: chore: Fix types in tests 12/N.
This commit is contained in:
@@ -13,7 +13,7 @@ const toRequestUrl = (input: Parameters<typeof fetch>[0]): string =>
|
|||||||
const createAntigravityFetch = (
|
const createAntigravityFetch = (
|
||||||
handler: (url: string, init?: Parameters<typeof fetch>[1]) => Promise<Response> | Response,
|
handler: (url: string, init?: Parameters<typeof fetch>[1]) => Promise<Response> | Response,
|
||||||
) =>
|
) =>
|
||||||
vi.fn<Parameters<typeof fetch>, ReturnType<typeof fetch>>(async (input, init) =>
|
vi.fn(async (input: string | Request | URL, init?: RequestInit) =>
|
||||||
handler(toRequestUrl(input), init),
|
handler(toRequestUrl(input), init),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ function createEndpointFetch(spec: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function runUsage(mockFetch: ReturnType<typeof createAntigravityFetch>) {
|
async function runUsage(mockFetch: ReturnType<typeof createAntigravityFetch>) {
|
||||||
return fetchAntigravityUsage("token-123", 5000, mockFetch);
|
return fetchAntigravityUsage("token-123", 5000, mockFetch as unknown as typeof fetch);
|
||||||
}
|
}
|
||||||
|
|
||||||
function findWindow(snapshot: Awaited<ReturnType<typeof fetchAntigravityUsage>>, label: string) {
|
function findWindow(snapshot: Awaited<ReturnType<typeof fetchAntigravityUsage>>, label: string) {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ function toRequestUrl(input: Parameters<typeof fetch>[0]): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createMinimaxOnlyFetch(payload: unknown) {
|
function createMinimaxOnlyFetch(payload: unknown) {
|
||||||
return vi.fn<Parameters<typeof fetch>, ReturnType<typeof fetch>>(async (input) => {
|
return vi.fn(async (input: string | Request | URL) => {
|
||||||
if (toRequestUrl(input).includes(minimaxRemainsEndpoint)) {
|
if (toRequestUrl(input).includes(minimaxRemainsEndpoint)) {
|
||||||
return makeResponse(200, payload);
|
return makeResponse(200, payload);
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ async function expectMinimaxUsage(
|
|||||||
const summary = await loadProviderUsageSummary({
|
const summary = await loadProviderUsageSummary({
|
||||||
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
||||||
auth: [{ provider: "minimax", token: "token-1b" }],
|
auth: [{ provider: "minimax", token: "token-1b" }],
|
||||||
fetch: mockFetch,
|
fetch: mockFetch as unknown as typeof fetch,
|
||||||
});
|
});
|
||||||
|
|
||||||
const minimax = summary.providers.find((p) => p.provider === "minimax");
|
const minimax = summary.providers.find((p) => p.provider === "minimax");
|
||||||
@@ -113,7 +113,7 @@ describe("provider usage formatting", () => {
|
|||||||
|
|
||||||
describe("provider usage loading", () => {
|
describe("provider usage loading", () => {
|
||||||
it("loads usage snapshots with injected auth", async () => {
|
it("loads usage snapshots with injected auth", async () => {
|
||||||
const mockFetch = vi.fn<Parameters<typeof fetch>, ReturnType<typeof fetch>>(async (input) => {
|
const mockFetch = vi.fn(async (input: string | Request | URL) => {
|
||||||
const url = toRequestUrl(input);
|
const url = toRequestUrl(input);
|
||||||
if (url.includes("api.anthropic.com")) {
|
if (url.includes("api.anthropic.com")) {
|
||||||
return makeResponse(200, {
|
return makeResponse(200, {
|
||||||
@@ -159,7 +159,7 @@ describe("provider usage loading", () => {
|
|||||||
{ provider: "minimax", token: "token-1b" },
|
{ provider: "minimax", token: "token-1b" },
|
||||||
{ provider: "zai", token: "token-2" },
|
{ provider: "zai", token: "token-2" },
|
||||||
],
|
],
|
||||||
fetch: mockFetch,
|
fetch: mockFetch as unknown as typeof fetch,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(summary.providers).toHaveLength(3);
|
expect(summary.providers).toHaveLength(3);
|
||||||
@@ -266,33 +266,27 @@ describe("provider usage loading", () => {
|
|||||||
return new Response(payload, { status, headers });
|
return new Response(payload, { status, headers });
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockFetch = vi.fn<Parameters<typeof fetch>, ReturnType<typeof fetch>>(
|
const mockFetch = vi.fn(async (input: string | Request | URL, init?: RequestInit) => {
|
||||||
async (input, init) => {
|
const url =
|
||||||
const url =
|
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
typeof input === "string"
|
if (url.includes("api.anthropic.com/api/oauth/usage")) {
|
||||||
? input
|
const headers = (init?.headers ?? {}) as Record<string, string>;
|
||||||
: input instanceof URL
|
expect(headers.Authorization).toBe("Bearer token-1");
|
||||||
? input.toString()
|
return makeResponse(200, {
|
||||||
: input.url;
|
five_hour: {
|
||||||
if (url.includes("api.anthropic.com/api/oauth/usage")) {
|
utilization: 20,
|
||||||
const headers = (init?.headers ?? {}) as Record<string, string>;
|
resets_at: "2026-01-07T01:00:00Z",
|
||||||
expect(headers.Authorization).toBe("Bearer token-1");
|
},
|
||||||
return makeResponse(200, {
|
});
|
||||||
five_hour: {
|
}
|
||||||
utilization: 20,
|
return makeResponse(404, "not found");
|
||||||
resets_at: "2026-01-07T01:00:00Z",
|
});
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return makeResponse(404, "not found");
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const summary = await loadProviderUsageSummary({
|
const summary = await loadProviderUsageSummary({
|
||||||
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
||||||
providers: ["anthropic"],
|
providers: ["anthropic"],
|
||||||
agentDir,
|
agentDir,
|
||||||
fetch: mockFetch,
|
fetch: mockFetch as unknown as typeof fetch,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(summary.providers).toHaveLength(1);
|
expect(summary.providers).toHaveLength(1);
|
||||||
@@ -321,7 +315,7 @@ describe("provider usage loading", () => {
|
|||||||
return new Response(payload, { status, headers });
|
return new Response(payload, { status, headers });
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockFetch = vi.fn<Parameters<typeof fetch>, ReturnType<typeof fetch>>(async (input) => {
|
const mockFetch = vi.fn(async (input: string | Request | URL) => {
|
||||||
const url =
|
const url =
|
||||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
if (url.includes("api.anthropic.com/api/oauth/usage")) {
|
if (url.includes("api.anthropic.com/api/oauth/usage")) {
|
||||||
@@ -349,7 +343,7 @@ describe("provider usage loading", () => {
|
|||||||
const summary = await loadProviderUsageSummary({
|
const summary = await loadProviderUsageSummary({
|
||||||
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
now: Date.UTC(2026, 0, 7, 0, 0, 0),
|
||||||
auth: [{ provider: "anthropic", token: "sk-ant-oauth-1" }],
|
auth: [{ provider: "anthropic", token: "sk-ant-oauth-1" }],
|
||||||
fetch: mockFetch,
|
fetch: mockFetch as unknown as typeof fetch,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(summary.providers).toHaveLength(1);
|
expect(summary.providers).toHaveLength(1);
|
||||||
|
|||||||
@@ -2,8 +2,15 @@ import fs from "node:fs";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import readline from "node:readline";
|
import readline from "node:readline";
|
||||||
import type { NormalizedUsage, UsageLike } from "../agents/usage.js";
|
import type { NormalizedUsage, UsageLike } from "../agents/usage.js";
|
||||||
|
import { normalizeUsage } from "../agents/usage.js";
|
||||||
import type { OpenClawConfig } from "../config/config.js";
|
import type { OpenClawConfig } from "../config/config.js";
|
||||||
|
import {
|
||||||
|
resolveSessionFilePath,
|
||||||
|
resolveSessionTranscriptsDirForAgent,
|
||||||
|
} from "../config/sessions/paths.js";
|
||||||
import type { SessionEntry } from "../config/sessions/types.js";
|
import type { SessionEntry } from "../config/sessions/types.js";
|
||||||
|
import { countToolResults, extractToolCallNames } from "../utils/transcript-tools.js";
|
||||||
|
import { estimateUsageCost, resolveModelCostConfig } from "../utils/usage-format.js";
|
||||||
import type {
|
import type {
|
||||||
CostBreakdown,
|
CostBreakdown,
|
||||||
CostUsageTotals,
|
CostUsageTotals,
|
||||||
@@ -24,13 +31,6 @@ import type {
|
|||||||
SessionUsageTimePoint,
|
SessionUsageTimePoint,
|
||||||
SessionUsageTimeSeries,
|
SessionUsageTimeSeries,
|
||||||
} from "./session-cost-usage.types.js";
|
} from "./session-cost-usage.types.js";
|
||||||
import { normalizeUsage } from "../agents/usage.js";
|
|
||||||
import {
|
|
||||||
resolveSessionFilePath,
|
|
||||||
resolveSessionTranscriptsDirForAgent,
|
|
||||||
} from "../config/sessions/paths.js";
|
|
||||||
import { countToolResults, extractToolCallNames } from "../utils/transcript-tools.js";
|
|
||||||
import { estimateUsageCost, resolveModelCostConfig } from "../utils/usage-format.js";
|
|
||||||
|
|
||||||
export type {
|
export type {
|
||||||
CostUsageDailyEntry,
|
CostUsageDailyEntry,
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ import { clearActiveProgressLine } from "./terminal/progress-line.js";
|
|||||||
import { restoreTerminalState } from "./terminal/restore.js";
|
import { restoreTerminalState } from "./terminal/restore.js";
|
||||||
|
|
||||||
export type RuntimeEnv = {
|
export type RuntimeEnv = {
|
||||||
log: typeof console.log;
|
log: (...args: unknown[]) => void;
|
||||||
error: typeof console.error;
|
error: (...args: unknown[]) => void;
|
||||||
exit: (code: number) => never;
|
exit: (code: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
function shouldEmitRuntimeLog(env: NodeJS.ProcessEnv = process.env): boolean {
|
function shouldEmitRuntimeLog(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||||
@@ -46,7 +46,7 @@ export const defaultRuntime: RuntimeEnv = {
|
|||||||
export function createNonExitingRuntime(): RuntimeEnv {
|
export function createNonExitingRuntime(): RuntimeEnv {
|
||||||
return {
|
return {
|
||||||
...createRuntimeIo(),
|
...createRuntimeIo(),
|
||||||
exit: (code: number): never => {
|
exit: (code: number) => {
|
||||||
throw new Error(`exit ${code}`);
|
throw new Error(`exit ${code}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,27 @@
|
|||||||
import { TUI } from "@mariozechner/pi-tui";
|
|
||||||
import { ChatLog } from "./components/chat-log.js";
|
|
||||||
import { asString, extractTextFromMessage, isCommandMessage } from "./tui-formatters.js";
|
import { asString, extractTextFromMessage, isCommandMessage } from "./tui-formatters.js";
|
||||||
import { TuiStreamAssembler } from "./tui-stream-assembler.js";
|
import { TuiStreamAssembler } from "./tui-stream-assembler.js";
|
||||||
import type { AgentEvent, ChatEvent, TuiStateAccess } from "./tui-types.js";
|
import type { AgentEvent, ChatEvent, TuiStateAccess } from "./tui-types.js";
|
||||||
|
|
||||||
|
type EventHandlerChatLog = {
|
||||||
|
startTool: (toolCallId: string, toolName: string, args: unknown) => void;
|
||||||
|
updateToolResult: (
|
||||||
|
toolCallId: string,
|
||||||
|
result: unknown,
|
||||||
|
options?: { partial?: boolean; isError?: boolean },
|
||||||
|
) => void;
|
||||||
|
addSystem: (text: string) => void;
|
||||||
|
updateAssistant: (text: string, runId: string) => void;
|
||||||
|
finalizeAssistant: (text: string, runId: string) => void;
|
||||||
|
dropAssistant: (runId: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type EventHandlerTui = {
|
||||||
|
requestRender: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
type EventHandlerContext = {
|
type EventHandlerContext = {
|
||||||
chatLog: ChatLog;
|
chatLog: EventHandlerChatLog;
|
||||||
tui: TUI;
|
tui: EventHandlerTui;
|
||||||
state: TuiStateAccess;
|
state: TuiStateAccess;
|
||||||
setActivityStatus: (text: string) => void;
|
setActivityStatus: (text: string) => void;
|
||||||
refreshSessionInfo?: () => Promise<void>;
|
refreshSessionInfo?: () => Promise<void>;
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ import {
|
|||||||
resetLoadConfigMock,
|
resetLoadConfigMock,
|
||||||
setLoadConfigMock,
|
setLoadConfigMock,
|
||||||
} from "./auto-reply.test-harness.js";
|
} from "./auto-reply.test-harness.js";
|
||||||
|
import type { WebInboundMessage } from "./inbound.js";
|
||||||
|
|
||||||
installWebAutoReplyTestHomeHooks();
|
installWebAutoReplyTestHomeHooks();
|
||||||
|
|
||||||
describe("web auto-reply", () => {
|
describe("web auto-reply", () => {
|
||||||
installWebAutoReplyUnitTestHooks({ pinDns: true });
|
installWebAutoReplyUnitTestHooks({ pinDns: true });
|
||||||
|
type ListenerFactory = NonNullable<Parameters<typeof monitorWebChannel>[1]>;
|
||||||
|
|
||||||
async function setupSingleInboundMessage(params: {
|
async function setupSingleInboundMessage(params: {
|
||||||
resolverValue: { text: string; mediaUrl: string };
|
resolverValue: { text: string; mediaUrl: string };
|
||||||
@@ -20,16 +22,12 @@ describe("web auto-reply", () => {
|
|||||||
reply?: ReturnType<typeof vi.fn>;
|
reply?: ReturnType<typeof vi.fn>;
|
||||||
}) {
|
}) {
|
||||||
const reply = params.reply ?? vi.fn().mockResolvedValue(undefined);
|
const reply = params.reply ?? vi.fn().mockResolvedValue(undefined);
|
||||||
const sendComposing = vi.fn();
|
const sendComposing = vi.fn(async () => undefined);
|
||||||
const resolver = vi.fn().mockResolvedValue(params.resolverValue);
|
const resolver = vi.fn().mockResolvedValue(params.resolverValue);
|
||||||
|
|
||||||
let capturedOnMessage:
|
let capturedOnMessage: ((msg: WebInboundMessage) => Promise<void>) | undefined;
|
||||||
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
|
const listenerFactory: ListenerFactory = async ({ onMessage }) => {
|
||||||
| undefined;
|
capturedOnMessage = onMessage;
|
||||||
const listenerFactory = async (opts: {
|
|
||||||
onMessage: (msg: import("./inbound.js").WebInboundMessage) => Promise<void>;
|
|
||||||
}) => {
|
|
||||||
capturedOnMessage = opts.onMessage;
|
|
||||||
return { close: vi.fn() };
|
return { close: vi.fn() };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -42,12 +40,16 @@ describe("web auto-reply", () => {
|
|||||||
await capturedOnMessage?.({
|
await capturedOnMessage?.({
|
||||||
body: "hello",
|
body: "hello",
|
||||||
from: "+1",
|
from: "+1",
|
||||||
|
conversationId: "+1",
|
||||||
to: "+2",
|
to: "+2",
|
||||||
|
accountId: "default",
|
||||||
|
chatType: "direct",
|
||||||
|
chatId: "+1",
|
||||||
id,
|
id,
|
||||||
sendComposing,
|
sendComposing,
|
||||||
reply,
|
reply,
|
||||||
sendMedia: params.sendMedia,
|
sendMedia: params.sendMedia,
|
||||||
});
|
} as WebInboundMessage);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -104,19 +106,15 @@ describe("web auto-reply", () => {
|
|||||||
setLoadConfigMock(() => ({ agents: { defaults: { mediaMaxMb: 1 } } }));
|
setLoadConfigMock(() => ({ agents: { defaults: { mediaMaxMb: 1 } } }));
|
||||||
const sendMedia = vi.fn();
|
const sendMedia = vi.fn();
|
||||||
const reply = vi.fn().mockResolvedValue(undefined);
|
const reply = vi.fn().mockResolvedValue(undefined);
|
||||||
const sendComposing = vi.fn();
|
const sendComposing = vi.fn(async () => undefined);
|
||||||
const resolver = vi.fn().mockResolvedValue({
|
const resolver = vi.fn().mockResolvedValue({
|
||||||
text: "hi",
|
text: "hi",
|
||||||
mediaUrl: `https://example.com/big.${fmt.name}`,
|
mediaUrl: `https://example.com/big.${fmt.name}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
let capturedOnMessage:
|
let capturedOnMessage: ((msg: WebInboundMessage) => Promise<void>) | undefined;
|
||||||
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
|
const listenerFactory: ListenerFactory = async ({ onMessage }) => {
|
||||||
| undefined;
|
capturedOnMessage = onMessage;
|
||||||
const listenerFactory = async (opts: {
|
|
||||||
onMessage: (msg: import("./inbound.js").WebInboundMessage) => Promise<void>;
|
|
||||||
}) => {
|
|
||||||
capturedOnMessage = opts.onMessage;
|
|
||||||
return { close: vi.fn() };
|
return { close: vi.fn() };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -129,7 +127,7 @@ describe("web auto-reply", () => {
|
|||||||
arrayBuffer: async () => big.buffer.slice(big.byteOffset, big.byteOffset + big.byteLength),
|
arrayBuffer: async () => big.buffer.slice(big.byteOffset, big.byteOffset + big.byteLength),
|
||||||
headers: { get: () => fmt.mime },
|
headers: { get: () => fmt.mime },
|
||||||
status: 200,
|
status: 200,
|
||||||
} as Response);
|
} as unknown as Response);
|
||||||
|
|
||||||
await monitorWebChannel(false, listenerFactory, false, resolver);
|
await monitorWebChannel(false, listenerFactory, false, resolver);
|
||||||
expect(capturedOnMessage).toBeDefined();
|
expect(capturedOnMessage).toBeDefined();
|
||||||
@@ -137,12 +135,16 @@ describe("web auto-reply", () => {
|
|||||||
await capturedOnMessage?.({
|
await capturedOnMessage?.({
|
||||||
body: "hello",
|
body: "hello",
|
||||||
from: "+1",
|
from: "+1",
|
||||||
|
conversationId: "+1",
|
||||||
to: "+2",
|
to: "+2",
|
||||||
|
accountId: "default",
|
||||||
|
chatType: "direct",
|
||||||
|
chatId: "+1",
|
||||||
id: `msg-${fmt.name}`,
|
id: `msg-${fmt.name}`,
|
||||||
sendComposing,
|
sendComposing,
|
||||||
reply,
|
reply,
|
||||||
sendMedia,
|
sendMedia,
|
||||||
});
|
} as WebInboundMessage);
|
||||||
|
|
||||||
expect(sendMedia).toHaveBeenCalledTimes(1);
|
expect(sendMedia).toHaveBeenCalledTimes(1);
|
||||||
const payload = sendMedia.mock.calls[0][0] as {
|
const payload = sendMedia.mock.calls[0][0] as {
|
||||||
@@ -162,19 +164,15 @@ describe("web auto-reply", () => {
|
|||||||
setLoadConfigMock(() => ({ agents: { defaults: { mediaMaxMb: 1 } } }));
|
setLoadConfigMock(() => ({ agents: { defaults: { mediaMaxMb: 1 } } }));
|
||||||
const sendMedia = vi.fn();
|
const sendMedia = vi.fn();
|
||||||
const reply = vi.fn().mockResolvedValue(undefined);
|
const reply = vi.fn().mockResolvedValue(undefined);
|
||||||
const sendComposing = vi.fn();
|
const sendComposing = vi.fn(async () => undefined);
|
||||||
const resolver = vi.fn().mockResolvedValue({
|
const resolver = vi.fn().mockResolvedValue({
|
||||||
text: "hi",
|
text: "hi",
|
||||||
mediaUrl: "https://example.com/big.png",
|
mediaUrl: "https://example.com/big.png",
|
||||||
});
|
});
|
||||||
|
|
||||||
let capturedOnMessage:
|
let capturedOnMessage: ((msg: WebInboundMessage) => Promise<void>) | undefined;
|
||||||
| ((msg: import("./inbound.js").WebInboundMessage) => Promise<void>)
|
const listenerFactory: ListenerFactory = async ({ onMessage }) => {
|
||||||
| undefined;
|
capturedOnMessage = onMessage;
|
||||||
const listenerFactory = async (opts: {
|
|
||||||
onMessage: (msg: import("./inbound.js").WebInboundMessage) => Promise<void>;
|
|
||||||
}) => {
|
|
||||||
capturedOnMessage = opts.onMessage;
|
|
||||||
return { close: vi.fn() };
|
return { close: vi.fn() };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -197,7 +195,7 @@ describe("web auto-reply", () => {
|
|||||||
bigPng.buffer.slice(bigPng.byteOffset, bigPng.byteOffset + bigPng.byteLength),
|
bigPng.buffer.slice(bigPng.byteOffset, bigPng.byteOffset + bigPng.byteLength),
|
||||||
headers: { get: () => "image/png" },
|
headers: { get: () => "image/png" },
|
||||||
status: 200,
|
status: 200,
|
||||||
} as Response);
|
} as unknown as Response);
|
||||||
|
|
||||||
await monitorWebChannel(false, listenerFactory, false, resolver);
|
await monitorWebChannel(false, listenerFactory, false, resolver);
|
||||||
expect(capturedOnMessage).toBeDefined();
|
expect(capturedOnMessage).toBeDefined();
|
||||||
@@ -205,12 +203,16 @@ describe("web auto-reply", () => {
|
|||||||
await capturedOnMessage?.({
|
await capturedOnMessage?.({
|
||||||
body: "hello",
|
body: "hello",
|
||||||
from: "+1",
|
from: "+1",
|
||||||
|
conversationId: "+1",
|
||||||
to: "+2",
|
to: "+2",
|
||||||
|
accountId: "default",
|
||||||
|
chatType: "direct",
|
||||||
|
chatId: "+1",
|
||||||
id: "msg1",
|
id: "msg1",
|
||||||
sendComposing,
|
sendComposing,
|
||||||
reply,
|
reply,
|
||||||
sendMedia,
|
sendMedia,
|
||||||
});
|
} as WebInboundMessage);
|
||||||
|
|
||||||
expect(sendMedia).toHaveBeenCalledTimes(1);
|
expect(sendMedia).toHaveBeenCalledTimes(1);
|
||||||
const payload = sendMedia.mock.calls[0][0] as {
|
const payload = sendMedia.mock.calls[0][0] as {
|
||||||
@@ -237,7 +239,7 @@ describe("web auto-reply", () => {
|
|||||||
arrayBuffer: async () => Buffer.from("%PDF-1.4").buffer,
|
arrayBuffer: async () => Buffer.from("%PDF-1.4").buffer,
|
||||||
headers: { get: () => "application/pdf" },
|
headers: { get: () => "application/pdf" },
|
||||||
status: 200,
|
status: 200,
|
||||||
} as Response);
|
} as unknown as Response);
|
||||||
|
|
||||||
await dispatch("msg-pdf");
|
await dispatch("msg-pdf");
|
||||||
|
|
||||||
@@ -282,7 +284,7 @@ describe("web auto-reply", () => {
|
|||||||
smallPng.buffer.slice(smallPng.byteOffset, smallPng.byteOffset + smallPng.byteLength),
|
smallPng.buffer.slice(smallPng.byteOffset, smallPng.byteOffset + smallPng.byteLength),
|
||||||
headers: { get: () => "image/png" },
|
headers: { get: () => "image/png" },
|
||||||
status: 200,
|
status: 200,
|
||||||
} as Response);
|
} as unknown as Response);
|
||||||
|
|
||||||
await dispatch("msg1");
|
await dispatch("msg1");
|
||||||
|
|
||||||
@@ -347,7 +349,7 @@ describe("web auto-reply", () => {
|
|||||||
arrayBuffer: async () => png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength),
|
arrayBuffer: async () => png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength),
|
||||||
headers: { get: () => "image/png" },
|
headers: { get: () => "image/png" },
|
||||||
status: 200,
|
status: 200,
|
||||||
} as Response);
|
} as unknown as Response);
|
||||||
|
|
||||||
await dispatch("msg1");
|
await dispatch("msg1");
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import type { getReplyFromConfig } from "../../auto-reply/reply.js";
|
||||||
import { HEARTBEAT_TOKEN } from "../../auto-reply/tokens.js";
|
import { HEARTBEAT_TOKEN } from "../../auto-reply/tokens.js";
|
||||||
|
import type { sendMessageWhatsApp } from "../outbound.js";
|
||||||
|
|
||||||
const state = vi.hoisted(() => ({
|
const state = vi.hoisted(() => ({
|
||||||
visibility: { showAlerts: true, showOk: true, useIndicator: false },
|
visibility: { showAlerts: true, showOk: true, useIndicator: false },
|
||||||
@@ -87,8 +89,10 @@ vi.mock("../session.js", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
describe("runWebHeartbeatOnce", () => {
|
describe("runWebHeartbeatOnce", () => {
|
||||||
let sender: ReturnType<typeof vi.fn>;
|
let senderMock: ReturnType<typeof vi.fn>;
|
||||||
let replyResolver: ReturnType<typeof vi.fn>;
|
let sender: typeof sendMessageWhatsApp;
|
||||||
|
let replyResolverMock: ReturnType<typeof vi.fn>;
|
||||||
|
let replyResolver: typeof getReplyFromConfig;
|
||||||
|
|
||||||
const getModules = async () => await import("./heartbeat-runner.js");
|
const getModules = async () => await import("./heartbeat-runner.js");
|
||||||
|
|
||||||
@@ -105,8 +109,10 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
};
|
};
|
||||||
state.events = [];
|
state.events = [];
|
||||||
|
|
||||||
sender = vi.fn(async () => ({ messageId: "m1" }));
|
senderMock = vi.fn(async () => ({ messageId: "m1" }));
|
||||||
replyResolver = vi.fn(async () => undefined);
|
sender = senderMock as unknown as typeof sendMessageWhatsApp;
|
||||||
|
replyResolverMock = vi.fn(async () => undefined);
|
||||||
|
replyResolver = replyResolverMock as unknown as typeof getReplyFromConfig;
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports manual override body dry-run without sending", async () => {
|
it("supports manual override body dry-run without sending", async () => {
|
||||||
@@ -119,7 +125,7 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
overrideBody: "hello",
|
overrideBody: "hello",
|
||||||
dryRun: true,
|
dryRun: true,
|
||||||
});
|
});
|
||||||
expect(sender).not.toHaveBeenCalled();
|
expect(senderMock).not.toHaveBeenCalled();
|
||||||
expect(state.events).toHaveLength(0);
|
expect(state.events).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -131,7 +137,7 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
sender,
|
sender,
|
||||||
replyResolver,
|
replyResolver,
|
||||||
});
|
});
|
||||||
expect(sender).toHaveBeenCalledWith("+123", HEARTBEAT_TOKEN, { verbose: false });
|
expect(senderMock).toHaveBeenCalledWith("+123", HEARTBEAT_TOKEN, { verbose: false });
|
||||||
expect(state.events).toEqual(
|
expect(state.events).toEqual(
|
||||||
expect.arrayContaining([expect.objectContaining({ status: "ok-empty", silent: false })]),
|
expect.arrayContaining([expect.objectContaining({ status: "ok-empty", silent: false })]),
|
||||||
);
|
);
|
||||||
@@ -147,13 +153,13 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
dryRun: true,
|
dryRun: true,
|
||||||
});
|
});
|
||||||
expect(replyResolver).toHaveBeenCalledTimes(1);
|
expect(replyResolver).toHaveBeenCalledTimes(1);
|
||||||
const ctx = replyResolver.mock.calls[0]?.[0];
|
const ctx = replyResolverMock.mock.calls[0]?.[0];
|
||||||
expect(ctx?.Body).toContain("Ops check");
|
expect(ctx?.Body).toContain("Ops check");
|
||||||
expect(ctx?.Body).toContain("Current time: 2026-02-15T00:00:00Z (mock)");
|
expect(ctx?.Body).toContain("Current time: 2026-02-15T00:00:00Z (mock)");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("treats heartbeat token-only replies as ok-token and preserves session updatedAt", async () => {
|
it("treats heartbeat token-only replies as ok-token and preserves session updatedAt", async () => {
|
||||||
replyResolver.mockResolvedValue({ text: HEARTBEAT_TOKEN });
|
replyResolverMock.mockResolvedValue({ text: HEARTBEAT_TOKEN });
|
||||||
const { runWebHeartbeatOnce } = await getModules();
|
const { runWebHeartbeatOnce } = await getModules();
|
||||||
await runWebHeartbeatOnce({
|
await runWebHeartbeatOnce({
|
||||||
cfg: { agents: { defaults: {} }, session: {} } as never,
|
cfg: { agents: { defaults: {} }, session: {} } as never,
|
||||||
@@ -162,7 +168,7 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
replyResolver,
|
replyResolver,
|
||||||
});
|
});
|
||||||
expect(state.store.k?.updatedAt).toBe(123);
|
expect(state.store.k?.updatedAt).toBe(123);
|
||||||
expect(sender).toHaveBeenCalledWith("+123", HEARTBEAT_TOKEN, { verbose: false });
|
expect(senderMock).toHaveBeenCalledWith("+123", HEARTBEAT_TOKEN, { verbose: false });
|
||||||
expect(state.events).toEqual(
|
expect(state.events).toEqual(
|
||||||
expect.arrayContaining([expect.objectContaining({ status: "ok-token", silent: false })]),
|
expect.arrayContaining([expect.objectContaining({ status: "ok-token", silent: false })]),
|
||||||
);
|
);
|
||||||
@@ -170,7 +176,7 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
|
|
||||||
it("skips sending alerts when showAlerts is disabled but still emits a skipped event", async () => {
|
it("skips sending alerts when showAlerts is disabled but still emits a skipped event", async () => {
|
||||||
state.visibility = { showAlerts: false, showOk: true, useIndicator: true };
|
state.visibility = { showAlerts: false, showOk: true, useIndicator: true };
|
||||||
replyResolver.mockResolvedValue({ text: "ALERT" });
|
replyResolverMock.mockResolvedValue({ text: "ALERT" });
|
||||||
const { runWebHeartbeatOnce } = await getModules();
|
const { runWebHeartbeatOnce } = await getModules();
|
||||||
await runWebHeartbeatOnce({
|
await runWebHeartbeatOnce({
|
||||||
cfg: { agents: { defaults: {} }, session: {} } as never,
|
cfg: { agents: { defaults: {} }, session: {} } as never,
|
||||||
@@ -178,7 +184,7 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
sender,
|
sender,
|
||||||
replyResolver,
|
replyResolver,
|
||||||
});
|
});
|
||||||
expect(sender).not.toHaveBeenCalled();
|
expect(senderMock).not.toHaveBeenCalled();
|
||||||
expect(state.events).toEqual(
|
expect(state.events).toEqual(
|
||||||
expect.arrayContaining([
|
expect.arrayContaining([
|
||||||
expect.objectContaining({ status: "skipped", reason: "alerts-disabled", preview: "ALERT" }),
|
expect.objectContaining({ status: "skipped", reason: "alerts-disabled", preview: "ALERT" }),
|
||||||
@@ -187,8 +193,8 @@ describe("runWebHeartbeatOnce", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("emits failed events when sending throws and rethrows the error", async () => {
|
it("emits failed events when sending throws and rethrows the error", async () => {
|
||||||
replyResolver.mockResolvedValue({ text: "ALERT" });
|
replyResolverMock.mockResolvedValue({ text: "ALERT" });
|
||||||
sender.mockRejectedValueOnce(new Error("nope"));
|
senderMock.mockRejectedValueOnce(new Error("nope"));
|
||||||
const { runWebHeartbeatOnce } = await getModules();
|
const { runWebHeartbeatOnce } = await getModules();
|
||||||
await expect(
|
await expect(
|
||||||
runWebHeartbeatOnce({
|
runWebHeartbeatOnce({
|
||||||
|
|||||||
Reference in New Issue
Block a user