Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

15.8 KB
Raw Blame
/**
 * 群消息入站门禁: @ 检测、owner 门、非 owner 礼貌回应(冷却)、lane senderId、
 * mention 占位符剥离、thread_id → 话题 lane、群主流 @ 留在群主流。
 */
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';

import { feishuEvents } from '../events.js';
import type { IMMessageEvent } from '../../types.js';

type EventHandler = (data: unknown) => Promise<unknown> | unknown;

const mocks = {
  options: [] as Array<{ onReady?: () => void }>,
  start: vi.fn(async () => undefined),
  close: vi.fn(),
  bindClient: vi.fn(),
  unbindClient: vi.fn(),
  getBoundClient: vi.fn(() => null),
  sendText: vi.fn(async () => ({ messageId: 'om_sent' })),
  replyText: vi.fn(async () => ({ messageId: 'om_reply' })),
  openThread: vi.fn(
    async (): Promise<
      | { kind: 'opened'; messageId: string; threadId: string }
      | { kind: 'degraded' }
      | { kind: 'orphaned'; openerMessageId: string }
      | { kind: 'unconfirmed' }
    > => ({
      kind: 'opened',
      messageId: 'om_opener',
      threadId: 'omt_new',
    }),
  ),
  resolveReplyMessage: vi.fn<
    (
      messageId: string,
      expectedChatId: string,
    ) => Promise<{
      replyContext: {
        author: string;
        text: string;
        isBot?: boolean;
      };
    } | null>
  >(async () => null),
  pushReplyAnchor: vi.fn(),
  pushPatchableOpener: vi.fn(),
  evictOpenThreadOutcome: vi.fn(),
  recallOwnMessage: vi.fn(async () => true),
  firstAllowed: vi.fn<() => string | null>(() => null),
  readOwnerOpenId: vi.fn<() => string | null>(() => null),
  clearOwner: vi.fn(),
  checkOwner: vi.fn((senderOpenId: string) => {
    void senderOpenId;
    return false;
  }),
  tryClaimOwner: vi.fn(() => false),
  eventHandlers: {} as Record<string, EventHandler>,
  log: {
    trace: vi.fn(),
    debug: vi.fn(),
    info: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
    fatal: vi.fn(),
  },
};

vi.doMock('@larksuiteoapi/node-sdk', () => ({
  WSClient: class {
    readonly start = mocks.start;
    readonly close = mocks.close;

    constructor(options: { onReady?: () => void }) {
      mocks.options.push(options);
    }
  },
  EventDispatcher: class {
    register(handlers: Record<string, EventHandler>): this {
      mocks.eventHandlers = handlers;
      return this;
    }
  },
  LoggerLevel: { info: 'info' },
  Domain: { Feishu: 'feishu-domain', Lark: 'lark-domain' },
}));

vi.doMock('../outbound.js', () => ({
  bindClient: mocks.bindClient,
  unbindClient: mocks.unbindClient,
  getBoundClient: mocks.getBoundClient,
  getAccountEpoch: () => 1,
  sendText: mocks.sendText,
  replyText: mocks.replyText,
  openThread: mocks.openThread,
  resolveReplyMessage: mocks.resolveReplyMessage,
  pushReplyAnchor: mocks.pushReplyAnchor,
  pushPatchableOpener: mocks.pushPatchableOpener,
  evictOpenThreadOutcome: mocks.evictOpenThreadOutcome,
  recallOwnMessage: mocks.recallOwnMessage,
}));

vi.doMock('../ownerGuard.js', () => ({
  firstAllowed: mocks.firstAllowed,
  clear: mocks.clearOwner,
  check: mocks.checkOwner,
  tryClaimOwner: mocks.tryClaimOwner,
}));

vi.doMock('../storage.js', () => ({
  readOwnerOpenId: mocks.readOwnerOpenId,
}));

vi.doMock('../moduleScope.js', async (importOriginal) => ({
  ...(await importOriginal<typeof import('../moduleScope.js')>()),
  getLog: () => mocks.log,
}));

let wsClient: typeof import('../wsClient.js');

const credentials = {
  appId: 'cli_group_test',
  appSecret: 'secret',
  service: 'feishu' as const,
};

const BOT_OPEN_ID = 'ou_bot_self';
const OWNER = 'ou_owner';
const STRANGER = 'ou_stranger';

function groupMessage(overrides: {
  sender?: string;
  text?: string;
  mentions?: Array<{ key: string; id?: { open_id?: string }; name?: string }>;
  threadId?: string;
  parentId?: string;
  rootId?: string;
  messageId?: string;
  chatId?: string;
}) {
  return {
    sender: { sender_id: { open_id: overrides.sender ?? OWNER } },
    message: {
      message_id: overrides.messageId ?? 'om_msg1',
      chat_id: overrides.chatId ?? 'oc_chat1',
      ...(overrides.threadId ? { thread_id: overrides.threadId } : {}),
      ...(overrides.parentId ? { parent_id: overrides.parentId } : {}),
      ...(overrides.rootId ? { root_id: overrides.rootId } : {}),
      chat_type: 'group',
      message_type: 'text',
      content: JSON.stringify({ text: overrides.text ?? '@_user_1 帮我看看' }),
      mentions: overrides.mentions ?? [
        { key: '@_user_1', id: { open_id: BOT_OPEN_ID }, name: 'Cindy' },
      ],
    },
  };
}

async function connect(): Promise<void> {
  const connecting = wsClient.start(credentials, { announceLifecycle: false });
  mocks.options.at(-1)?.onReady?.();
  await connecting;
  wsClient.setBotOpenIdForTest(BOT_OPEN_ID);
}

function collectEvents(): IMMessageEvent[] {
  const events: IMMessageEvent[] = [];
  feishuEvents.on('message', (e) => events.push(e));
  return events;
}

beforeEach(async () => {
  await wsClient.stop({ announceOffline: false, reason: 'test-reset' });
  // 入站去重账本按设计跨 stop/start 保留(重推高发在重连前后), 所以用例之间
  // 想复用同一个 message_id 必须显式清账。
  wsClient.resetInboundDedupeForTest();
  mocks.options.length = 0;
  mocks.eventHandlers = {};
  vi.clearAllMocks();
  feishuEvents.removeAllListeners('message');
  mocks.firstAllowed.mockReturnValue(OWNER);
  mocks.checkOwner.mockImplementation((id: string) => id === OWNER);
  // 恢复 openThread / replyText 默认实现 — 个别用例会覆盖它们
  // (含持续的 mockRejectedValue), 不能泄漏到后续用例。
  mocks.openThread.mockImplementation(async () => ({
    kind: 'opened',
    messageId: 'om_opener',
    threadId: 'omt_new',
  }));
  mocks.resolveReplyMessage.mockResolvedValue(null);
  mocks.replyText.mockImplementation(async () => ({ messageId: 'om_reply' }));
});

afterEach(async () => {
  await wsClient.stop({ announceOffline: false, reason: 'test-cleanup' });
  feishuEvents.removeAllListeners('message');
});

beforeAll(async () => {
  wsClient = await import('../wsClient.js');
});

afterAll(() => {
  vi.doUnmock('@larksuiteoapi/node-sdk');
  vi.doUnmock('../outbound.js');
  vi.doUnmock('../ownerGuard.js');
  vi.doUnmock('../storage.js');
  vi.doUnmock('../moduleScope.js');
});

describe('feishu group inbound gate', () => {
  it('drops group messages that do not mention the bot', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(
      groupMessage({ mentions: [{ key: '@_user_1', id: { open_id: 'ou_other' }, name: 'X' }] }),
    );
    expect(events).toHaveLength(0);
  });

  it('drops all group messages while bot open_id is unknown', async () => {
    await connect();
    wsClient.setBotOpenIdForTest(null);
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
    expect(events).toHaveLength(0);
  });

  it('never TOFU-claims owner from a group mention', async () => {
    mocks.firstAllowed.mockReturnValue(null);
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
    expect(mocks.tryClaimOwner).not.toHaveBeenCalled();
    expect(events).toHaveLength(0);
  });

  it('replies politely to a non-owner mention with per-user cooldown, no turn', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({ sender: STRANGER }));
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({ sender: STRANGER }));
    expect(mocks.replyText).toHaveBeenCalledTimes(1);
    expect(events).toHaveLength(0);
  });

  it('owner mention stays in the main timeline without creating a topic', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));

    expect(mocks.openThread).not.toHaveBeenCalled();
    expect(events).toHaveLength(1);
    const event = events[0]!;
    expect(event.senderId).toBe('g/oc_chat1');
    expect(event.chatId).toBe('oc_chat1');
    expect(event.text).toBe('帮我看看');
    expect(event.speaker).toEqual({ id: OWNER, name: '', isOwner: true });
    expect(event.replyContext).toBeUndefined();
    expect(mocks.resolveReplyMessage).not.toHaveBeenCalled();
    // Quote the actual trigger without creating a topic.
    expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1', 'om_msg1');

    expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();

    expect(event.groupContextLane).toBeUndefined();
  });

  it('main-stream reply mention resolves parent_id as exact context without turning a quoted reply into a topic', async () => {
    mocks.resolveReplyMessage.mockResolvedValueOnce({
      replyContext: {
        author: '张乾',
        text: 'Omarchy Quattro 发布了!https://omarchy.org',
      },
    });
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(
      groupMessage({ parentId: 'om_parent', rootId: 'om_root_ignored' }),
    );

    expect(mocks.resolveReplyMessage).toHaveBeenCalledWith('om_parent', 'oc_chat1');
    expect(events).toHaveLength(1);
    expect(events[0]!.replyContext).toEqual({
      author: '张乾',
      text: 'Omarchy Quattro 发布了!https://omarchy.org',
    });
    // Quoting supplies context without changing the reply location.
    expect(events[0]!.senderId).toBe('g/oc_chat1');
    expect(mocks.openThread).not.toHaveBeenCalled();
  });

  // A private quote used to bypass parent resolution altogether.
  it('delivers private reply context without changing the direct lane', async () => {
    mocks.resolveReplyMessage.mockResolvedValueOnce({ replyContext: { author: 'Alice', text: 'quoted text' } });
    await connect();
    const events = collectEvents();
    const incoming = groupMessage({ parentId: 'om_parent', text: 'explain this' });
    incoming.message.chat_type = 'p2p';
    await mocks.eventHandlers['im.message.receive_v1']!(incoming);
    expect(events[0]).toMatchObject({ senderId: OWNER, replyContext: { text: 'quoted text' } });
    expect(mocks.resolveReplyMessage).toHaveBeenCalledWith('om_parent', 'oc_chat1');
  });

  it('fetches directly received merged forwards instead of silently dropping them', async () => {
    mocks.resolveReplyMessage.mockResolvedValueOnce({ replyContext: { author: 'Alice', text: 'forwarded content' } });
    await connect();
    const events = collectEvents();
    const incoming = groupMessage({});
    incoming.message.chat_type = 'p2p';
    incoming.message.message_type = 'merge_forward';
    incoming.message.content = 'Merged and Forwarded Message';
    await mocks.eventHandlers['im.message.receive_v1']!(incoming);
    expect(events[0]).toMatchObject({ text: '[合并转发消息]', replyContext: { text: 'forwarded content' } });
    expect(mocks.resolveReplyMessage).toHaveBeenCalledWith('om_msg1', 'oc_chat1');
  });

  it('main-stream reply fetch failure keeps the existing group-history fallback', async () => {
    mocks.resolveReplyMessage.mockResolvedValueOnce(null);
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(
      groupMessage({ parentId: 'om_deleted_parent' }),
    );

    expect(events).toHaveLength(1);
    expect(events[0]!.replyContext).toBeUndefined();
    expect(events[0]!.groupContextLane).toBeUndefined();
    expect(mocks.openThread).not.toHaveBeenCalled();
  });

  it('releases unfinished quoted-message lookup on reconnect without duplicating the turn', async () => {
    let resolveOld!: (value: null) => void;
    mocks.resolveReplyMessage.mockReturnValueOnce(new Promise((resolve) => { resolveOld = resolve; }));
    await connect();
    const events = collectEvents();
    const message = groupMessage({ parentId: 'om_parent' });
    const oldHandling = mocks.eventHandlers['im.message.receive_v1']!(message);
    await vi.waitFor(() => expect(mocks.resolveReplyMessage).toHaveBeenCalledTimes(1));
    await wsClient.stop({ announceOffline: false, reason: 'test-reconnect' });
    await connect();
    await mocks.eventHandlers['im.message.receive_v1']!(message);
    expect(events).toHaveLength(1);
    resolveOld(null);
    await oldHandling;
    await mocks.eventHandlers['im.message.receive_v1']!(message);
    expect(events).toHaveLength(1);
    expect(mocks.pushReplyAnchor).toHaveBeenCalledExactlyOnceWith('g/oc_chat1', 'om_msg1');
  });

  it('drops duplicate delivery of the same message (one turn per message)', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
    // 飞书重投同一条 @ 事件: 入站去重直接丢弃, 第二次 turn 不会启动
    // (重复锚点 + 两份回答)。
    await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));

    expect(events).toHaveLength(1);
    expect(mocks.openThread).not.toHaveBeenCalled();
    expect(mocks.pushReplyAnchor).toHaveBeenCalledTimes(1);
  });

  it('routes topic mentions unchanged even when Feishu also supplies parent_id', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(
      groupMessage({ threadId: 'omt_topic7', parentId: 'om_topic_parent' }),
    );
    expect(events[0]!.senderId).toBe('g/oc_chat1/omt_topic7');
    expect(events[0]!.groupContextLane).toBeUndefined();
    expect(events[0]!.replyContext).toBeUndefined();
    expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_topic7', 'om_msg1');
    expect(mocks.openThread).not.toHaveBeenCalled();
    expect(mocks.resolveReplyMessage).not.toHaveBeenCalled();
  });

  it('replaces other-user mention placeholders with sanitized display names', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!(
      groupMessage({
        text: '@_user_1 问下 @_user_2 的进度',
        mentions: [
          { key: '@_user_1', id: { open_id: BOT_OPEN_ID }, name: 'Cindy' },
          { key: '@_user_2', id: { open_id: 'ou_alice' }, name: 'Al\u0007ice' },
        ],
      }),
    );
    expect(events[0]!.text).toBe('问下 @Al ice 的进度');
  });

  it('keeps p2p flow unchanged (owner gate + plain senderId, no speaker)', async () => {
    await connect();
    const events = collectEvents();
    await mocks.eventHandlers['im.message.receive_v1']!({
      sender: { sender_id: { open_id: OWNER } },
      message: {
        message_id: 'om_dm',
        chat_id: 'oc_p2p',
        chat_type: 'p2p',
        message_type: 'text',
        content: JSON.stringify({ text: '私聊消息' }),
      },
    });
    expect(events).toHaveLength(1);
    expect(events[0]!.senderId).toBe(OWNER);
    expect(events[0]!.speaker).toBeUndefined();
    expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
  });
});

describe('private topic notification ancestry', () => {
  it('preserves root and thread separately while keeping the real owner identity', async () => {
    await connect();
    const events = collectEvents();
    const raw = groupMessage({ rootId: 'om_notification', parentId: 'om_previous_reply', threadId: 'omt_topic' });
    raw.message.chat_type = 'p2p';
    await mocks.eventHandlers['im.message.receive_v1']!(raw);
    expect(events).toHaveLength(1);
    expect(events[0]).toMatchObject({
      senderId: OWNER, chatId: 'oc_chat1',
      replyThread: { rootMessageId: 'om_notification', threadId: 'omt_topic' },
    });
    expect(events[0].speaker).toBeUndefined();
  });

  it('does not treat an ordinary quoted reply without thread_id as a topic', async () => {
    await connect();
    const events = collectEvents();
    const raw = groupMessage({ rootId: 'om_notification', parentId: 'om_notification' });
    raw.message.chat_type = 'p2p';
    await mocks.eventHandlers['im.message.receive_v1']!(raw);
    expect(events).toHaveLength(1);
    expect(events[0].replyThread).toBeUndefined();
  });
});