test: dedupe gateway browser discord and channel coverage

This commit is contained in:
Peter Steinberger
2026-02-22 17:11:42 +00:00
parent 34ea33f057
commit 296b19e413
29 changed files with 938 additions and 1041 deletions

View File

@@ -150,6 +150,29 @@ function readLastAgentCommandCall():
| undefined;
}
function mockSessionResetSuccess(params: {
reason: "new" | "reset";
key?: string;
sessionId?: string;
}) {
const key = params.key ?? "agent:main:main";
const sessionId = params.sessionId ?? "reset-session-id";
mocks.sessionsResetHandler.mockImplementation(
async (opts: {
params: { key: string; reason: string };
respond: (ok: boolean, payload?: unknown) => void;
}) => {
expect(opts.params.key).toBe(key);
expect(opts.params.reason).toBe(params.reason);
opts.respond(true, {
ok: true,
key,
entry: { sessionId },
});
},
);
}
async function invokeAgent(
params: AgentParams,
options?: {
@@ -321,20 +344,7 @@ describe("gateway agent handler", () => {
});
it("handles bare /new by resetting the same session and sending reset greeting prompt", async () => {
mocks.sessionsResetHandler.mockImplementation(
async (opts: {
params: { key: string; reason: string };
respond: (ok: boolean, payload?: unknown) => void;
}) => {
expect(opts.params.key).toBe("agent:main:main");
expect(opts.params.reason).toBe("new");
opts.respond(true, {
ok: true,
key: "agent:main:main",
entry: { sessionId: "reset-session-id" },
});
},
);
mockSessionResetSuccess({ reason: "new" });
primeMainAgentRun({ sessionId: "reset-session-id" });
@@ -366,20 +376,7 @@ describe("gateway agent handler", () => {
},
},
};
mocks.sessionsResetHandler.mockImplementation(
async (opts: {
params: { key: string; reason: string };
respond: (ok: boolean, payload?: unknown) => void;
}) => {
expect(opts.params.key).toBe("agent:main:main");
expect(opts.params.reason).toBe("reset");
opts.respond(true, {
ok: true,
key: "agent:main:main",
entry: { sessionId: "reset-session-id" },
});
},
);
mockSessionResetSuccess({ reason: "reset" });
mocks.sessionsResetHandler.mockClear();
primeMainAgentRun({
sessionId: "reset-session-id",

View File

@@ -34,6 +34,16 @@ function createInvokeParams(params: Record<string, unknown>) {
};
}
function expectInvalidRequestResponse(
respond: ReturnType<typeof vi.fn>,
expectedMessagePart: string,
) {
const call = respond.mock.calls[0] as RespondCall | undefined;
expect(call?.[0]).toBe(false);
expect(call?.[2]?.code).toBe(ErrorCodes.INVALID_REQUEST);
expect(call?.[2]?.message).toContain(expectedMessagePart);
}
describe("push.test handler", () => {
beforeEach(() => {
vi.mocked(loadApnsRegistration).mockClear();
@@ -45,20 +55,14 @@ describe("push.test handler", () => {
it("rejects invalid params", async () => {
const { respond, invoke } = createInvokeParams({ title: "hello" });
await invoke();
const call = respond.mock.calls[0] as RespondCall | undefined;
expect(call?.[0]).toBe(false);
expect(call?.[2]?.code).toBe(ErrorCodes.INVALID_REQUEST);
expect(call?.[2]?.message).toContain("invalid push.test params");
expectInvalidRequestResponse(respond, "invalid push.test params");
});
it("returns invalid request when node has no APNs registration", async () => {
vi.mocked(loadApnsRegistration).mockResolvedValue(null);
const { respond, invoke } = createInvokeParams({ nodeId: "ios-node-1" });
await invoke();
const call = respond.mock.calls[0] as RespondCall | undefined;
expect(call?.[0]).toBe(false);
expect(call?.[2]?.code).toBe(ErrorCodes.INVALID_REQUEST);
expect(call?.[2]?.message).toContain("has no APNs registration");
expectInvalidRequestResponse(respond, "has no APNs registration");
});
it("sends push test when registration and auth are available", async () => {

View File

@@ -42,6 +42,48 @@ const getInflightMap = (context: GatewayRequestContext) => {
return inflight;
};
async function resolveRequestedChannel(params: {
requestChannel: unknown;
unsupportedMessage: (input: string) => string;
rejectWebchatAsInternalOnly?: boolean;
}): Promise<
| {
cfg: ReturnType<typeof loadConfig>;
channel: string;
}
| {
error: ReturnType<typeof errorShape>;
}
> {
const channelInput =
typeof params.requestChannel === "string" ? params.requestChannel : undefined;
const normalizedChannel = channelInput ? normalizeChannelId(channelInput) : null;
if (channelInput && !normalizedChannel) {
const normalizedInput = channelInput.trim().toLowerCase();
if (params.rejectWebchatAsInternalOnly && normalizedInput === "webchat") {
return {
error: errorShape(
ErrorCodes.INVALID_REQUEST,
"unsupported channel: webchat (internal-only). Use `chat.send` for WebChat UI messages or choose a deliverable channel.",
),
};
}
return {
error: errorShape(ErrorCodes.INVALID_REQUEST, params.unsupportedMessage(channelInput)),
};
}
const cfg = loadConfig();
let channel = normalizedChannel;
if (!channel) {
try {
channel = (await resolveMessageChannelSelection({ cfg })).channel;
} catch (err) {
return { error: errorShape(ErrorCodes.INVALID_REQUEST, String(err)) };
}
}
return { cfg, channel };
}
export const sendHandlers: GatewayRequestHandlers = {
send: async ({ params, respond, context }) => {
const p = params;
@@ -104,38 +146,16 @@ export const sendHandlers: GatewayRequestHandlers = {
);
return;
}
const channelInput = typeof request.channel === "string" ? request.channel : undefined;
const normalizedChannel = channelInput ? normalizeChannelId(channelInput) : null;
if (channelInput && !normalizedChannel) {
const normalizedInput = channelInput.trim().toLowerCase();
if (normalizedInput === "webchat") {
respond(
false,
undefined,
errorShape(
ErrorCodes.INVALID_REQUEST,
"unsupported channel: webchat (internal-only). Use `chat.send` for WebChat UI messages or choose a deliverable channel.",
),
);
return;
}
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, `unsupported channel: ${channelInput}`),
);
const resolvedChannel = await resolveRequestedChannel({
requestChannel: request.channel,
unsupportedMessage: (input) => `unsupported channel: ${input}`,
rejectWebchatAsInternalOnly: true,
});
if ("error" in resolvedChannel) {
respond(false, undefined, resolvedChannel.error);
return;
}
const cfg = loadConfig();
let channel = normalizedChannel;
if (!channel) {
try {
channel = (await resolveMessageChannelSelection({ cfg })).channel;
} catch (err) {
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, String(err)));
return;
}
}
const { cfg, channel } = resolvedChannel;
const accountId =
typeof request.accountId === "string" && request.accountId.trim().length
? request.accountId.trim()
@@ -322,26 +342,15 @@ export const sendHandlers: GatewayRequestHandlers = {
return;
}
const to = request.to.trim();
const channelInput = typeof request.channel === "string" ? request.channel : undefined;
const normalizedChannel = channelInput ? normalizeChannelId(channelInput) : null;
if (channelInput && !normalizedChannel) {
respond(
false,
undefined,
errorShape(ErrorCodes.INVALID_REQUEST, `unsupported poll channel: ${channelInput}`),
);
const resolvedChannel = await resolveRequestedChannel({
requestChannel: request.channel,
unsupportedMessage: (input) => `unsupported poll channel: ${input}`,
});
if ("error" in resolvedChannel) {
respond(false, undefined, resolvedChannel.error);
return;
}
const cfg = loadConfig();
let channel = normalizedChannel;
if (!channel) {
try {
channel = (await resolveMessageChannelSelection({ cfg })).channel;
} catch (err) {
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, String(err)));
return;
}
}
const { cfg, channel } = resolvedChannel;
if (typeof request.durationSeconds === "number" && channel !== "telegram") {
respond(
false,

View File

@@ -109,6 +109,23 @@ async function runSessionsUsageLogs(params: Record<string, unknown>) {
return respond;
}
const BASE_USAGE_RANGE = {
startDate: "2026-02-01",
endDate: "2026-02-02",
limit: 10,
} as const;
function expectSuccessfulSessionsUsage(
respond: ReturnType<typeof vi.fn>,
): Array<{ key: string; agentId: string }> {
expect(respond).toHaveBeenCalledTimes(1);
expect(respond.mock.calls[0]?.[0]).toBe(true);
const result = respond.mock.calls[0]?.[1] as {
sessions: Array<{ key: string; agentId: string }>;
};
return result.sessions;
}
describe("sessions.usage", () => {
beforeEach(() => {
vi.useRealTimers();
@@ -116,28 +133,20 @@ describe("sessions.usage", () => {
});
it("discovers sessions across configured agents and keeps agentId in key", async () => {
const respond = await runSessionsUsage({
startDate: "2026-02-01",
endDate: "2026-02-02",
limit: 10,
});
const respond = await runSessionsUsage(BASE_USAGE_RANGE);
expect(vi.mocked(discoverAllSessions)).toHaveBeenCalledTimes(2);
expect(vi.mocked(discoverAllSessions).mock.calls[0]?.[0]?.agentId).toBe("main");
expect(vi.mocked(discoverAllSessions).mock.calls[1]?.[0]?.agentId).toBe("opus");
expect(respond).toHaveBeenCalledTimes(1);
expect(respond.mock.calls[0]?.[0]).toBe(true);
const result = respond.mock.calls[0]?.[1] as unknown as {
sessions: Array<{ key: string; agentId: string }>;
};
expect(result.sessions).toHaveLength(2);
const sessions = expectSuccessfulSessionsUsage(respond);
expect(sessions).toHaveLength(2);
// Sorted by most recent first (mtime=200 -> opus first).
expect(result.sessions[0].key).toBe("agent:opus:s-opus");
expect(result.sessions[0].agentId).toBe("opus");
expect(result.sessions[1].key).toBe("agent:main:s-main");
expect(result.sessions[1].agentId).toBe("main");
expect(sessions[0].key).toBe("agent:opus:s-opus");
expect(sessions[0].agentId).toBe("opus");
expect(sessions[1].key).toBe("agent:main:s-main");
expect(sessions[1].agentId).toBe("main");
});
it("resolves store entries by sessionId when queried via discovered agent-prefixed key", async () => {
@@ -166,20 +175,10 @@ describe("sessions.usage", () => {
});
// Query via discovered key: agent:<id>:<sessionId>
const respond = await runSessionsUsage({
startDate: "2026-02-01",
endDate: "2026-02-02",
key: "agent:opus:s-opus",
limit: 10,
});
expect(respond).toHaveBeenCalledTimes(1);
expect(respond.mock.calls[0]?.[0]).toBe(true);
const result = respond.mock.calls[0]?.[1] as unknown as {
sessions: Array<{ key: string }>;
};
expect(result.sessions).toHaveLength(1);
expect(result.sessions[0]?.key).toBe(storeKey);
const respond = await runSessionsUsage({ ...BASE_USAGE_RANGE, key: "agent:opus:s-opus" });
const sessions = expectSuccessfulSessionsUsage(respond);
expect(sessions).toHaveLength(1);
expect(sessions[0]?.key).toBe(storeKey);
expect(vi.mocked(loadSessionCostSummary)).toHaveBeenCalled();
expect(
vi.mocked(loadSessionCostSummary).mock.calls.some((call) => call[0]?.agentId === "opus"),
@@ -192,10 +191,8 @@ describe("sessions.usage", () => {
it("rejects traversal-style keys in specific session usage lookups", async () => {
const respond = await runSessionsUsage({
startDate: "2026-02-01",
endDate: "2026-02-02",
...BASE_USAGE_RANGE,
key: "agent:opus:../../etc/passwd",
limit: 10,
});
expect(respond).toHaveBeenCalledTimes(1);