Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): 卡片回调 senderId 归一成发卡 lane, 修群 /ctr 锁键错配
Lizi9150ecd4a544
diff --git a/apps/desktop/src/main/im/shared/__tests__/controlState.test.ts b/apps/desktop/src/main/im/shared/__tests__/controlState.test.tsnew file mode 100644index 0000000000..907e0dbe90--- /dev/null+++ b/apps/desktop/src/main/im/shared/__tests__/controlState.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { enterControl, exitControl, getControlScope, isInControl } from '../controlState';++/**+ * /ctr 锁的键语义契约。飞书群消息侧的 key 是话题 lane(g/{chatId}/{threadId}),+ * 卡片回调侧必须归一成同一条 lane 才能解锁 — 用 operator.open_id 解锁会落空,+ * 该 lane 永远锁在「选择中」(曾导致「明明创建了还提示还在选择中」的线上 bug,+ * 传输层修复见 packages/lizi-im feishu 的 cardLanes 登记反查)。+ */+describe('controlState key semantics', () => {+ it('group lane and owner open_id are distinct keys — exit must use the enter key', () => {+ enterControl('bot1', 'g/oc_chat/omt_t1');+ expect(isInControl('bot1', 'g/oc_chat/omt_t1')).toBe(true);+ expect(isInControl('bot1', 'ou_owner')).toBe(false);++ // 旧 bug 的解锁键(operator.open_id): 删不中, lane 保持锁定。+ exitControl('bot1', 'ou_owner');+ expect(isInControl('bot1', 'g/oc_chat/omt_t1')).toBe(true);++ // 与消息侧同键的 lane 解锁生效。+ exitControl('bot1', 'g/oc_chat/omt_t1');+ expect(isInControl('bot1', 'g/oc_chat/omt_t1')).toBe(false);+ });++ it('same identity across bots stays independent', () => {+ enterControl('bot1', 'ou_owner');+ expect(isInControl('bot1', 'ou_owner')).toBe(true);+ expect(isInControl('bot2', 'ou_owner')).toBe(false);+ exitControl('bot1', 'ou_owner');+ expect(isInControl('bot1', 'ou_owner')).toBe(false);+ });++ it('thread-model scope is returned separately from the lock itself', () => {+ enterControl('bot1', 'ou_owner', 'omt_anchor');+ expect(isInControl('bot1', 'ou_owner')).toBe(true);+ expect(getControlScope('bot1', 'ou_owner')).toBe('omt_anchor');+ exitControl('bot1', 'ou_owner');+ expect(isInControl('bot1', 'ou_owner')).toBe(false);+ expect(getControlScope('bot1', 'ou_owner')).toBeNull();+ });+});diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.tsindex a2e288c8e4..3e0b49f27b 100644--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts@@ -233,3 +233,70 @@ describe('feishu outbound lane routing', () => {);});});++describe('feishu card lane registry', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ outbound.unbindClient(); // clears lane anchors + card registry+ outbound.bindClient(creds);+ });++ it('registers topic-lane cards and resolves them back to the same lane', async () => {+ outbound.pushReplyAnchor('g/oc_group1/omt_t1', 'om_topic_trigger');+ const { messageId } = await outbound.sendInteractive('g/oc_group1/omt_t1', {+ body: 'pick',+ buttons: [{ id: 'control:exit', label: '退出', payload: { botAppId: 'cli_x' } }],+ });+ expect(messageId).toBe('om_replied');+ expect(outbound.resolveCardLane('om_replied', 'oc_group1')).toBe('g/oc_group1/omt_t1');+ });++ it('registers plain group-lane cards (openThread 失败降级路径)', async () => {+ outbound.pushReplyAnchor('g/oc_group1', 'om_trigger1');+ const { messageId } = await outbound.sendInteractive('g/oc_group1', {+ body: 'pick',+ buttons: [{ id: 'control:exit', label: '退出' }],+ });+ expect(outbound.resolveCardLane(messageId, 'oc_group1')).toBe('g/oc_group1');+ });++ it('does not register p2p (DM) cards — callback keeps the open_id', async () => {+ await outbound.sendInteractive('ou_dm_user', {+ body: 'hi',+ buttons: [{ id: 'control:exit', label: '退出' }],+ });+ expect(outbound.resolveCardLane('om_created', 'ou_dm_user')).toBeNull();+ });++ it('does not register deliverToOwnerDm cards (they live in the owner DM)', async () => {+ outbound.pushReplyAnchor('g/oc_g', 'om_t');+ const { messageId } = await outbound.sendInteractive(+ 'g/oc_g',+ { body: '要执行危险操作', buttons: [{ id: 'permission:allow:once', label: '允许' }] },+ { deliverToOwnerDm: true },+ );+ expect(larkMocks.create).toHaveBeenCalledWith(+ expect.objectContaining({ data: expect.objectContaining({ receive_id: 'ou_owner' }) }),+ );+ expect(outbound.resolveCardLane(messageId, 'oc_g')).toBeNull();+ });++ it('rejects a lane lookup whose chatId does not match the callback chat', async () => {+ outbound.pushReplyAnchor('g/oc_group1/omt_t1', 'om_topic_trigger');+ await outbound.sendInteractive('g/oc_group1/omt_t1', {+ body: 'pick',+ buttons: [{ id: 'control:exit', label: '退出' }],+ });+ expect(outbound.resolveCardLane('om_replied', 'oc_another_group')).toBeNull();+ });++ it('unbindClient clears the registry (no cross-generation mismatch)', async () => {+ outbound.pushReplyAnchor('g/oc_group1/omt_t1', 'om_topic_trigger');+ await outbound.sendInteractive('g/oc_group1/omt_t1', {+ body: 'pick',+ buttons: [{ id: 'control:exit', label: '退出' }],+ });+ outbound.unbindClient();+ expect(outbound.resolveCardLane('om_replied', 'oc_group1')).toBeNull();+ });+});diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.tsnew file mode 100644index 0000000000..b159fe84a8--- /dev/null+++ b/packages/lizi-im/src/feishu/__tests__/wsClientCardAction.test.ts@@ -0,0 +1,201 @@+/**+ * 卡片回调入站: 白名单门 + 群卡片 senderId 归一成发卡 lane(消息侧同键,+ * /ctr 锁与接管 binding 才能对齐);私聊卡保持 operator.open_id。+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { feishuEvents } from '../events.js';+import type { IMCardActionEvent } 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 () => ({ messageId: 'om_opener', threadId: 'omt_new' })),+ pushReplyAnchor: vi.fn(),+ pushPatchableOpener: vi.fn(),+ resolveCardLane: vi.fn<(messageId: string, chatId: string) => string | null>(+ () => null,+ ),+ 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,+ sendText: mocks.sendText,+ replyText: mocks.replyText,+ openThread: mocks.openThread,+ pushReplyAnchor: mocks.pushReplyAnchor,+ pushPatchableOpener: mocks.pushPatchableOpener,+ resolveCardLane: mocks.resolveCardLane,+}));++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', () => ({+ getLog: () => mocks.log,+}));++let wsClient: typeof import('../wsClient.js');++const credentials = {+ appId: 'cli_card_test',+ appSecret: 'secret',+ service: 'feishu' as const,+};++const OWNER = 'ou_owner';++function cardActionPayload(overrides: {+ operatorOpenId?: string;+ messageId?: string;+ chatId?: string;+ buttonId?: string;+} = {}) {+ return {+ operator: { open_id: overrides.operatorOpenId ?? OWNER },+ context: {+ open_message_id: overrides.messageId ?? 'om_card1',+ open_chat_id: overrides.chatId ?? 'oc_chat1',+ },+ action: {+ value: { id: overrides.buttonId ?? 'control:exit', botAppId: 'cli_card_test' },+ },+ };+}++async function connect(): Promise<void> {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ mocks.options.at(-1)?.onReady?.();+ await connecting;+}++function collectCardActions(): IMCardActionEvent[] {+ const events: IMCardActionEvent[] = [];+ feishuEvents.on('cardAction', (e) => events.push(e));+ return events;+}++/** handleCardAction 用 setImmediate 延迟一 tick 再 emit, 等它落地。 */+async function settleImmediate(): Promise<void> {+ await new Promise((resolve) => setImmediate(resolve));+}++beforeEach(async () => {+ await wsClient.stop({ announceOffline: false, reason: 'test-reset' });+ mocks.options.length = 0;+ mocks.eventHandlers = {};+ vi.clearAllMocks();+ feishuEvents.removeAllListeners('cardAction');+ mocks.firstAllowed.mockReturnValue(OWNER);+ mocks.checkOwner.mockImplementation((id: string) => id === OWNER);+ mocks.resolveCardLane.mockReturnValue(null);+});++afterEach(async () => {+ await wsClient.stop({ announceOffline: false, reason: 'test-cleanup' });+ feishuEvents.removeAllListeners('cardAction');+});++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 card action inbound', () => {+ it('normalizes group card senderId to the registered lane', async () => {+ mocks.resolveCardLane.mockReturnValue('g/oc_chat1/omt_t1');+ await connect();+ const events = collectCardActions();+ await mocks.eventHandlers['card.action.trigger']!(cardActionPayload());+ await settleImmediate();++ expect(mocks.resolveCardLane).toHaveBeenCalledWith('om_card1', 'oc_chat1');+ expect(events).toHaveLength(1);+ expect(events[0]!.senderId).toBe('g/oc_chat1/omt_t1');+ expect(events[0]!.buttonId).toBe('control:exit');+ expect(events[0]!.payload).toEqual({ botAppId: 'cli_card_test' });+ });++ it('keeps operator open_id when no lane is registered (p2p / owner DM cards)', async () => {+ await connect();+ const events = collectCardActions();+ await mocks.eventHandlers['card.action.trigger']!(cardActionPayload());+ await settleImmediate();++ expect(events).toHaveLength(1);+ expect(events[0]!.senderId).toBe(OWNER);+ });++ it('drops card actions from non-whitelisted operators', async () => {+ mocks.resolveCardLane.mockReturnValue('g/oc_chat1/omt_t1');+ await connect();+ const events = collectCardActions();+ await mocks.eventHandlers['card.action.trigger']!(+ cardActionPayload({ operatorOpenId: 'ou_stranger' }),+ );+ await settleImmediate();++ expect(events).toHaveLength(0);+ });+});diff --git a/packages/lizi-im/src/feishu/cardActionParser.ts b/packages/lizi-im/src/feishu/cardActionParser.tsindex 9456e6950f..6463ab9c9c 100644--- a/packages/lizi-im/src/feishu/cardActionParser.ts+++ b/packages/lizi-im/src/feishu/cardActionParser.ts@@ -6,6 +6,11 @@* cards.ts (which puts business id+payload into `value`) and the orchestrator* (which reads them back here).*+ * senderId is always the operator's raw open_id here; wsClient additionally+ * resolves group cards to their lane id via the outbound messageId→lane+ * registry (see outbound.resolveCardLane) — callback context carries no thread+ * info, so the registry is the only way to recover the topic lane.+ ** Returns null when the payload is malformed or when the sender is not on the* whitelist (caller should drop silently).*/diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex 45c89713b1..7665e88201 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -53,6 +53,7 @@ export function unbindClient(): void {client = null;creds = null;laneAnchors.clear();+ cardLanes.clear();}// ── group lane reply anchors ──────────────────────────────────────────────────@@ -379,6 +380,59 @@ export async function removeReaction(messageId: string, reactionId: string): Pro// ── interactive cards ─────────────────────────────────────────────────────────+// ── card lane registry (发卡登记 messageId → lane) ────────────────────────────+// 卡片回调(card.action.trigger)的 context 只带 open_message_id / open_chat_id,+// 不带话题 thread_id — 编排层按 (bot, senderId) 记 /ctr 锁与接管 binding, 消息+// 侧 senderId 是群话题 lane(g/{chatId}/{threadId}), 回调侧只有 operator.open_id,+// 键对不上会让 /ctr 锁永远清不掉。发往 lane 的卡在发送成功后把 messageId 登记+// 回发卡 lane, 回调时反查归一成同一条 lane;私聊卡(open_id)与改投 owner DM 的卡+// 不登记, 回调保持 open_id。飞书卡片回调有效期 30 天, 过期条目不会再有点击,+// 按 31 天 TTL + 上限淘汰;unbindClient 随连接换代清空(与 laneAnchors 同口径)。++const CARD_LANE_TTL_MS = 31 * 24 * 60 * 60 * 1000;+const CARD_LANE_MAX_ENTRIES = 512;+const cardLanes = new Map<string, { ts: number; lane: string }>();++function pruneCardLanes(): void {+ const now = Date.now();+ for (const [messageId, entry] of cardLanes) {+ if (now - entry.ts > CARD_LANE_TTL_MS) cardLanes.delete(messageId);+ }+ while (cardLanes.size > CARD_LANE_MAX_ENTRIES) {+ let oldestKey: string | undefined;+ let oldestTs = Number.POSITIVE_INFINITY;+ for (const [messageId, entry] of cardLanes) {+ if (entry.ts < oldestTs) {+ oldestTs = entry.ts;+ oldestKey = messageId;+ }+ }+ if (oldestKey === undefined) break;+ cardLanes.delete(oldestKey);+ }+}++/** 发卡成功后在 lane 通道登记 card messageId → laneUserId;私聊发送不登记。 */+function registerCardLane(userId: string, messageId: string): void {+ if (!decodeLaneUserId(userId)) return;+ cardLanes.set(messageId, { ts: Date.now(), lane: userId });+ pruneCardLanes();+}++/**+ * 按卡片回调的 open_message_id 反查发卡 lane。chatId 兜底比对防串(卡在话题里+ * 时 open_chat_id 是群 id, 与 lane 的 chatId 恒一致)。查不到返回 null — 私聊卡、+ * 改投 DM 卡或已过期淘汰的条目, 回调 senderId 保持 operator.open_id。+ */+export function resolveCardLane(messageId: string, chatId: string): string | null {+ pruneCardLanes();+ const entry = cardLanes.get(messageId);+ if (!entry) return null;+ const lane = decodeLaneUserId(entry.lane);+ if (!lane || lane.chatId !== chatId) return null;+ return entry.lane;+}+export async function sendInteractive(userId: string,spec: InteractiveCardSpec,@@ -395,7 +449,13 @@ export async function sendInteractive(return createMessage({ kind: 'open_id', id: owner }, 'interactive', JSON.stringify(card));}const card = buildInteractiveCardV1(spec);- return createMessage(requireSendTarget(userId), 'interactive', JSON.stringify(card));+ const result = await createMessage(+ requireSendTarget(userId),+ 'interactive',+ JSON.stringify(card),+ );+ registerCardLane(userId, result.messageId);+ return result;}export async function updateInteractive(diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex 3049498704..c8ff27ff27 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -742,6 +742,16 @@ async function handleCardAction(data: unknown): Promise<unknown> {try {const event = parseCardAction({ raw: data });if (event) {+ // 群卡片的回调 senderId 归一成发卡 lane(与消息侧 /ctr 锁、接管 binding+ // 的键一致, 否则锁永远清不掉);私聊卡 / 改投 DM 卡没有登记, 保持+ // operator.open_id。白名单校验仍以 operator.open_id 为准(parser 内)。+ const lane = outbound.resolveCardLane(event.messageId, event.chatId);+ if (lane) {+ event.senderId = lane;+ log.info(+ `[feishu/wsClient] card action sender normalized to lane ...${lane.slice(-8)}`,+ );+ }// Keep the Feishu callback path short: card handlers often patch the// same message, and doing that before the action ACK returns can race// the client-side card action state. Dispatch on the next tick so thediff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.tsindex 91f7b6bcb7..b8fe714add 100644--- a/packages/lizi-im/src/types.ts+++ b/packages/lizi-im/src/types.ts@@ -244,7 +244,12 @@ export interface IMMessageEvent {export interface IMCardActionEvent {channelName: string;- /** open_id of the user who pressed the button. */+ /**+ * Identity of the user who pressed the button. For group cards on lane+ * channels (feishu) this is the card's lane id `g/{chatId}[/{threadId}]` —+ * transport resolves it from a messageId→lane registry so card actions share+ * the same identity key as inbound messages; p2p cards keep the open_id.+ */senderId: string;/** Chat where the card lives (p2p only). */chatId: string;