🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as PublicUrlFetchModule from '../publicUrlFetch';
// These tests stub `fetch` directly; the SSRF guard in front of it resolves DNS
// for real, which has nothing to do with what they assert. Its own behaviour is
// covered in publicUrlFetch.test.ts.
vi.mock('../publicUrlFetch', async () => ({
// Spread the real module: a full mock silently drops every export it
// does not name, so adding one to publicUrlFetch breaks suites that
// never cared about it.
...(await vi.importActual<typeof PublicUrlFetchModule>('../publicUrlFetch')),
fetchPublicUrl: async (url: string, timeoutMs: number) => ({
dispose: async () => undefined,
response: await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }),
}),
}));
const MessageItemType = vi.hoisted(() => ({
FILE: 4,
IMAGE: 1,
TEXT: 0,
VIDEO: 3,
VOICE: 2,
}));
const WechatUploadMediaType = vi.hoisted(() => ({
FILE: 4,
IMAGE: 1,
VIDEO: 3,
VOICE: 2,
}));
vi.mock('@lobechat/chat-adapter-wechat', () => ({
getWechatTextSendCount: (text: string) => Math.max(1, Math.ceil(text.length / 2000)),
MessageItemType,
WechatUploadMediaType,
}));
const mockRedisGet = vi.hoisted(() => vi.fn().mockResolvedValue(null));
// Window bookkeeping commands used by contextWindow (legacy-token seeding path).
const mockWindowRedis = vi.hoisted(() => ({
expire: vi.fn().mockResolvedValue(1),
hgetall: vi.fn().mockResolvedValue({}),
hincrby: vi.fn().mockResolvedValue(9),
hset: vi.fn().mockResolvedValue(1),
pttl: vi.fn().mockResolvedValue(-1),
}));
vi.mock('@/server/modules/AgentRuntime/redis', () => ({
getAgentRuntimeRedisClient: () => ({ get: mockRedisGet, ...mockWindowRedis }),
}));
const { WechatMessageService } = await import('./service');
const makeApi = () => ({
sendItem: vi.fn().mockResolvedValue({ ret: 0 }),
sendMessage: vi.fn().mockResolvedValue({ ret: 0 }),
uploadCdnMedia: vi.fn().mockResolvedValue({
aesKey: 'aes-key',
cipherSize: 64,
encryptQueryParam: 'enc-param',
}),
});
describe('WechatMessageService.sendMessage', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal('fetch', vi.fn());
mockRedisGet.mockResolvedValue(null);
});
it('forwards text via api.sendMessage', async () => {
const api = makeApi();
const service = new WechatMessageService(api as any, 'app-1');
await service.sendMessage({
channelId: '[email protected]',
content: 'hello',
platform: 'wechat',
});
expect(api.sendMessage).toHaveBeenCalledWith('[email protected]', 'hello', '');
expect(api.uploadCdnMedia).not.toHaveBeenCalled();
expect(api.sendItem).not.toHaveBeenCalled();
});
it('consumes one send-window credit per long-text chunk', async () => {
const api = makeApi();
const service = new WechatMessageService(api as any, 'app-1');
mockWindowRedis.hgetall.mockResolvedValueOnce({
refreshedAt: '1',
remaining: '10',
token: 'ctx-1',
});
mockWindowRedis.hincrby.mockResolvedValueOnce(7);
await service.sendMessage({
channelId: '[email protected]',
content: 'a'.repeat(4500),
platform: 'wechat',
});
expect(mockWindowRedis.hincrby).toHaveBeenCalledWith(
'wechat:ctx-window:app-1:[email protected]',
'remaining',
-3,
);
});
it('uploads + sends attachments as separate iLink items (text + image)', async () => {
const api = makeApi();
mockRedisGet.mockResolvedValueOnce('ctx-1');
const service = new WechatMessageService(api as any, 'app-1');
await service.sendMessage({
attachments: [
{
data: Buffer.from('image-bytes').toString('base64'),
mimeType: 'image/png',
name: 'foo.png',
type: 'image',
},
],
channelId: '[email protected]',
content: 'here you go',
platform: 'wechat',
});
expect(api.sendMessage).toHaveBeenCalledWith('[email protected]', 'here you go', 'ctx-1');
expect(api.uploadCdnMedia).toHaveBeenCalledWith(
'[email protected]',
WechatUploadMediaType.IMAGE,
expect.any(Buffer),
);
expect(api.sendItem).toHaveBeenCalledWith(
'[email protected]',
expect.objectContaining({
image_item: expect.objectContaining({
media: expect.objectContaining({
aes_key: 'aes-key',
encrypt_query_param: 'enc-param',
}),
}),
type: MessageItemType.IMAGE,
}),
'ctx-1',
);
});
it('skips the text leg when content is empty but still sends attachments', async () => {
const api = makeApi();
const service = new WechatMessageService(api as any, 'app-1');
await service.sendMessage({
attachments: [
{ data: Buffer.from('pdf-bytes').toString('base64'), name: 'a.pdf', type: 'file' },
],
channelId: '[email protected]',
content: '',
platform: 'wechat',
});
expect(api.sendMessage).not.toHaveBeenCalled();
expect(api.uploadCdnMedia).toHaveBeenCalledTimes(1);
expect(api.sendItem).toHaveBeenCalledTimes(1);
});
it('reports an attachment whose bytes could not be fetched instead of swallowing it', async () => {
// Regression: the runtime returned `success: true` while the file never
// left the server, so the model told the user "see attached".
const api = makeApi();
const service = new WechatMessageService(api as any, 'app-1');
const error = new TypeError('fetch failed');
(error as any).cause = new TypeError('Invalid IP address: undefined');
vi.mocked(fetch).mockRejectedValueOnce(error);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await service.sendMessage({
attachments: [
{ fetchUrl: 'https://app.example.com/f/file_1', name: 'report.docx', type: 'file' },
],
channelId: '[email protected]',
content: 'docx attached',
platform: 'wechat',
});
expect(api.sendMessage).toHaveBeenCalledTimes(1);
expect(api.sendItem).not.toHaveBeenCalled();
expect(result).toEqual({
attachmentFailures: [
{
detail: 'fetch failed: fetch failed (Invalid IP address: undefined)',
name: 'report.docx',
reason: 'source-unavailable',
type: 'file',
},
],
attachmentsDelivered: 0,
channelId: '[email protected]',
platform: 'wechat',
});
expect(warn).toHaveBeenCalledWith(expect.stringContaining('report.docx'));
} finally {
warn.mockRestore();
}
});
it('fetches attachments delivered as fetchUrl', async () => {
const api = makeApi();
const service = new WechatMessageService(api as any, 'app-1');
const fetchMock = vi.mocked(fetch);
fetchMock.mockResolvedValueOnce(
new Response(new Uint8Array([9, 9, 9, 9]), {
headers: { 'Content-Type': 'image/png' },
status: 200,
}) as any,
);
await service.sendMessage({
attachments: [{ fetchUrl: 'https://cdn.example.com/pic.png', type: 'image' }],
channelId: '[email protected]',
content: '',
platform: 'wechat',
});
expect(fetchMock).toHaveBeenCalledWith('https://cdn.example.com/pic.png', expect.any(Object));
expect(api.uploadCdnMedia).toHaveBeenCalledTimes(1);
expect(api.sendItem).toHaveBeenCalledTimes(1);
});
});