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。

fix(feishu): 群主流消息在 /ctr 接管期间路由进接管会话

Liziad71b087fa7d
diff --git a/apps/desktop/src/main/im/binding.ts b/apps/desktop/src/main/im/binding.ts
index ea5aa46a02..41935a11fc 100644
--- a/apps/desktop/src/main/im/binding.ts
+++ b/apps/desktop/src/main/im/binding.ts
@@ -204,6 +204,19 @@ export class SqliteBindingStore implements BindingStore<string> {
return out;
}
+ /**
+ * 某 (channel, bot) 名下全部 active 接管的 identity 快照 —— 渠道层做
+ * 「群主流消息落进哪个接管」这类跨 userId 的裁决用(如飞书群 /ctr 接管
+ * 路由)。n 极小(单 owner 同时接管数), O(n) 扫 reverse 即可。
+ */
+ listIdentities(channel: string, botContextId: string): IdentityKey[] {
+ const out: IdentityKey[] = [];
+ for (const id of this.reverse.values()) {
+ if (id.channel === channel && id.botContextId === botContextId) out.push(id);
+ }
+ return out;
+ }
+
attach(
identity: IdentityKey,
value: string,
diff --git a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
index 0cef70e7bc..1f36d2d664 100644
--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
@@ -8,7 +8,7 @@
* - 默认 title / ack emoji
* - 群 lane prepareAgentTurnText: 分页拉历史 + 相关性早停 + 失败通知 owner
*/
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import os from 'node:os';
import path from 'node:path';
@@ -19,6 +19,11 @@ const scopeMocks = vi.hoisted(() => ({
join: null as unknown as (...parts: string[]) => string,
claimLegacy: vi.fn(),
utilityText: vi.fn(),
+ listIdentities: vi.fn<
+ () => Array<{ channel: string; botContextId: string; userId: string }>
+ >(() => []),
+ bindingGet: vi.fn<() => string | null>(() => null),
+ getAttachCardMessageId: vi.fn<() => string | null>(() => null),
}));
vi.mock('electron', () => ({
@@ -41,6 +46,13 @@ vi.mock('../../../utility-model/oneShotCandidates.js', () => ({
vi.mock('../../../maker-host/index.js', () => ({
getMaker: () => ({}),
}));
+vi.mock('../../binding', () => ({
+ bindingStore: {
+ listIdentities: scopeMocks.listIdentities,
+ get: scopeMocks.bindingGet,
+ getAttachCardMessageId: scopeMocks.getAttachCardMessageId,
+ },
+}));
import type {
FeishuChatHistoryPage,
@@ -49,7 +61,7 @@ import type {
IMMessageEvent,
IMStatus,
} from '@cindy/im';
-import { buildFeishuAdapter } from '../adapter';
+import { buildFeishuAdapter, resolveGroupTakeoverLane } from '../adapter';
import { formatHistoryTime } from '../groupContext';
const getService = vi.fn<() => 'feishu' | 'lark'>(() => 'feishu');
@@ -68,6 +80,7 @@ const sendMarkdownText = vi.fn<(_userId: string, _text: string) => Promise<{ mes
);
const getChatName = vi.fn<(chatId: string) => Promise<string | null>>(async () => null);
const getStatus = vi.fn<() => IMStatus>(() => ({ kind: 'connected', appId: 'cli_abc' }));
+const setGroupMainFlowLaneOverride = vi.fn();
const fakeIm = {
getService,
fetchChatHistoryPage,
@@ -76,6 +89,7 @@ const fakeIm = {
sendMarkdownText,
getChatName,
getStatus,
+ setGroupMainFlowLaneOverride,
} as unknown as FeishuIM;
function groupEvent(overrides?: Partial<IMMessageEvent>): IMMessageEvent {
@@ -484,3 +498,81 @@ describe('feishu group lane adapter hooks', () => {
);
});
});
+
+describe('resolveGroupTakeoverLane — 群主流消息的 /ctr 接管路由', () => {
+ beforeEach(() => {
+ scopeMocks.listIdentities.mockReset();
+ scopeMocks.bindingGet.mockReset();
+ scopeMocks.getAttachCardMessageId.mockReset();
+ scopeMocks.listIdentities.mockReturnValue([]);
+ scopeMocks.bindingGet.mockReturnValue(null);
+ scopeMocks.getAttachCardMessageId.mockReturnValue(null);
+ });
+
+ function identity(userId: string) {
+ return { channel: 'feishu', botContextId: 'cli_abc', userId };
+ }
+
+ it('本群唯一话题接管且 binding 存活 → 返回接管 lane + 话题内回复锚点(attach 卡片)', () => {
+ scopeMocks.listIdentities.mockReturnValue([
+ identity('g/oc_chat1/omt_ctr'),
+ identity('ou_dm_user'), // 私聊 identity 不是 lane, 不参与候选
+ ]);
+ scopeMocks.bindingGet.mockReturnValue('sess-1');
+ scopeMocks.getAttachCardMessageId.mockReturnValue('om_card_ctr');
+
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '接着聊' }),
+ ).toEqual({ laneUserId: 'g/oc_chat1/omt_ctr', replyAnchorMessageId: 'om_card_ctr' });
+ });
+
+ it('attach 卡片缺失(旧 binding 行)时返回 lane 但不给锚点(transport 复用 held 锚点)', () => {
+ scopeMocks.listIdentities.mockReturnValue([identity('g/oc_chat1/omt_ctr')]);
+ scopeMocks.bindingGet.mockReturnValue('sess-1');
+ scopeMocks.getAttachCardMessageId.mockReturnValue(null);
+
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '接着聊' }),
+ ).toEqual({ laneUserId: 'g/oc_chat1/omt_ctr' });
+ });
+
+ it('多个话题接管并存 → 歧义, 回落 null(默认开话题)', () => {
+ scopeMocks.listIdentities.mockReturnValue([
+ identity('g/oc_chat1/omt_ctr'),
+ identity('g/oc_chat1/omt_other'),
+ ]);
+ scopeMocks.bindingGet.mockReturnValue('sess-1');
+
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '接着聊' }),
+ ).toBeNull();
+ });
+
+ it('slash 命令恒回落且不查 binding', () => {
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '/ctr' }),
+ ).toBeNull();
+ expect(scopeMocks.listIdentities).not.toHaveBeenCalled();
+ });
+
+ it('binding 已收回(get 为 null)→ 回落 null', () => {
+ scopeMocks.listIdentities.mockReturnValue([identity('g/oc_chat1/omt_ctr')]);
+ scopeMocks.bindingGet.mockReturnValue(null);
+
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '接着聊' }),
+ ).toBeNull();
+ });
+
+ it('非本 chat / 群主流 lane(无话题)的接管不参与候选', () => {
+ scopeMocks.listIdentities.mockReturnValue([
+ identity('g/oc_other_chat/omt_ctr'),
+ identity('g/oc_chat1'), // 群主流 lane(开话题失败的降级路径)
+ ]);
+ scopeMocks.bindingGet.mockReturnValue('sess-1');
+
+ expect(
+ resolveGroupTakeoverLane({ chatId: 'oc_chat1', botAppId: 'cli_abc', text: '接着聊' }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.ts
index 579d9d7fea..4c54d986a9 100644
--- a/apps/desktop/src/main/im/feishu/adapter.ts
+++ b/apps/desktop/src/main/im/feishu/adapter.ts
@@ -19,9 +19,15 @@
import path from 'node:path';
import fs from 'node:fs';
import { app } from 'electron';
-import { decodeFeishuLaneUserId, type FeishuIM, type FeishuLane } from '@cindy/im';
+import {
+ decodeFeishuLaneUserId,
+ encodeFeishuLaneUserId,
+ type FeishuIM,
+ type FeishuLane,
+} from '@cindy/im';
import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';
+import { bindingStore } from '../binding';
import { claimLegacyImPath, ownerScopedImUserDataPath } from '../ownerScopedStorage';
import { createLogger } from '../../logger';
import { buildFeishuGroupContext, sanitizeDisplayText } from './groupContext';
@@ -211,10 +217,45 @@ function takeMainFlowContextLane(topicLaneUserId: string): FeishuLane | undefine
return entry.lane;
}
+/**
+ * 群主流消息的 /ctr 接管路由裁决(transport lane 覆写钩子的 host 侧实现)。
+ *
+ * 本群存在且仅存在一个「话题 lane 的活跃接管」时, 群主流消息直接落进该
+ * 接管话题 —— 不再开新话题, 会话状态进 /ctr 接管的 desktop session, 回复
+ * 也回接管话题(见 wsClient 钩子注释)。多个接管并存时歧义, 回落默认
+ * 开话题行为; slash 命令(如 /ctr 本身)恒回落, 让控制流照常拿新话题 lane。
+ * binding 可能刚被收回(detach 与消息并发) — 确认存活才接管路由。
+ *
+ * 回复锚点用 attach 时记录的 /ctr 控制卡 messageId(attachCardIds, 恒在
+ * 接管话题内) —— 群主流的触发消息不是话题内消息, 拿它当锚点会让回复
+ * 落进群主流(outbound 的 fail-closed 不变量, review P1)。
+ */
+export function resolveGroupTakeoverLane(args: {
+ chatId: string;
+ botAppId: string;
+ text: string;
+}): { laneUserId: string; replyAnchorMessageId?: string } | null {
+ if (args.text.trimStart().startsWith('/')) return null;
+ const candidates = bindingStore
+ .listIdentities('feishu', args.botAppId)
+ .map((id) => decodeFeishuLaneUserId(id.userId))
+ .filter((l): l is FeishuLane => l !== null && l.chatId === args.chatId && l.threadId !== '');
+ if (candidates.length !== 1) return null;
+ const lane = candidates[0];
+ if (!lane) return null;
+ const laneUserId = encodeFeishuLaneUserId(lane.chatId, lane.threadId);
+ const identity = { channel: 'feishu', botContextId: args.botAppId, userId: laneUserId };
+ if (!bindingStore.get(identity)) return null;
+ const anchor = bindingStore.getAttachCardMessageId(identity);
+ return anchor ? { laneUserId, replyAnchorMessageId: anchor } : { laneUserId };
+}
+
export function buildFeishuAdapter(
feishuIm: FeishuIM,
config: ImOrchestratorConfig,
): ImChannelAdapter {
+ // 群主流消息的 /ctr 接管路由: 接管存在时消息落进接管话题, 不再开新话题。
+ feishuIm.setGroupMainFlowLaneOverride(resolveGroupTakeoverLane);
const isLark = () => feishuIm.getService() === 'lark';
const conversationPrefix = () => (isLark() ? '[Lark·DM] ' : '[飞书·DM] ');
const groupPrefix = (threadId: string) =>
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientMainFlowTakeover.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientMainFlowTakeover.test.ts
new file mode 100644
index 0000000000..c1a755df28
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientMainFlowTakeover.test.ts
@@ -0,0 +1,253 @@
+/**
+ * 群主流消息的 /ctr 接管 lane 覆写钩子。
+ *
+ * 语义: host 注入的钩子返回接管 lane 时, 群主流消息不再 openThread 开新
+ * 话题, 直接以接管 lane 路由(senderId = 接管 lane, 出站回复进接管话题);
+ * 上下文取数 lane(groupContextLane)仍指向群主流。钩子返回 null / 未注入 /
+ * 话题消息 = 默认行为。
+ */
+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 () => ({ 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_takeover_test',
+ appSecret: 'secret',
+ service: 'feishu' as const,
+};
+
+const OWNER = 'ou_owner';
+const BOT = 'ou_bot';
+
+function groupMainFlowMessage(text: string): unknown {
+ return {
+ sender: { sender_id: { open_id: OWNER } },
+ message: {
+ message_id: 'om_msg1',
+ chat_id: 'oc_chat1',
+ chat_type: 'group',
+ message_type: 'text',
+ content: JSON.stringify({ text }),
+ mentions: [{ key: '@_user_1', id: { open_id: BOT }, name: 'bot' }],
+ },
+ };
+}
+
+function groupTopicMessage(text: string, threadId: string): unknown {
+ const raw = groupMainFlowMessage(text) as { message: Record<string, unknown> };
+ raw.message.thread_id = threadId;
+ return raw;
+}
+
+async function connect(): Promise<void> {
+ wsClient.setBotOpenIdForTest(BOT);
+ const connecting = wsClient.start(credentials, { announceLifecycle: false });
+ mocks.options.at(-1)?.onReady?.();
+ await connecting;
+}
+
+function collectMessages(): IMMessageEvent[] {
+ const events: IMMessageEvent[] = [];
+ feishuEvents.on('message', (e) => events.push(e));
+ return events;
+}
+
+beforeEach(async () => {
+ await wsClient.stop({ announceOffline: false, reason: 'test-reset' });
+ mocks.options.length = 0;
+ mocks.eventHandlers = {};
+ vi.clearAllMocks();
+ feishuEvents.removeAllListeners('message');
+ wsClient.setGroupMainFlowLaneOverride(null);
+ mocks.firstAllowed.mockReturnValue(OWNER);
+ mocks.checkOwner.mockImplementation((id: string) => id === OWNER);
+});
+
+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 main-flow takeover lane override', () => {
+ it('钩子命中时不开新话题, 消息以接管 lane 路由, 回复锚点用话题内消息', async () => {
+ wsClient.setGroupMainFlowLaneOverride((args) => {
+ expect(args.chatId).toBe('oc_chat1');
+ expect(args.botAppId).toBe('cli_takeover_test');
+ return { laneUserId: 'g/oc_chat1/omt_ctr', replyAnchorMessageId: 'om_card_ctr' };
+ });
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('接着聊'));
+
+ expect(mocks.openThread).not.toHaveBeenCalled();
+ // 锚点必须是话题内消息(/ctr 控制卡), 不能是群主流触发消息 — 否则
+ // 回复会被打进群主流(outbound fail-closed 不变量)。
+ expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_ctr', 'om_card_ctr');
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalledWith('g/oc_chat1/omt_ctr', 'om_msg1');
+ expect(mocks.pushPatchableOpener).not.toHaveBeenCalled();
+ expect(events).toHaveLength(1);
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_ctr');
+ expect(events[0].groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
+ expect(events[0].text).toBe('接着聊');
+ });
+
+ it('钩子未给锚点时也不 push 群主流触发消息(复用该 lane 持有的话题内锚点)', async () => {
+ wsClient.setGroupMainFlowLaneOverride(() => ({ laneUserId: 'g/oc_chat1/omt_ctr' }));
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('接着聊'));
+
+ expect(mocks.openThread).not.toHaveBeenCalled();
+ expect(mocks.pushReplyAnchor).not.toHaveBeenCalled();
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_ctr');
+ expect(events[0].groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
+ });
+
+ it('钩子返回 null 时保持默认开话题行为', async () => {
+ wsClient.setGroupMainFlowLaneOverride(() => null);
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('开个新话题'));
+
+ expect(mocks.openThread).toHaveBeenCalledWith('om_msg1');
+ expect(events).toHaveLength(1);
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_new');
+ expect(events[0].groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
+ });
+
+ it('未注入钩子 = 默认开话题行为', async () => {
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('普通消息'));
+
+ expect(mocks.openThread).toHaveBeenCalledTimes(1);
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_new');
+ });
+
+ it('话题内消息不咨询钩子', async () => {
+ const hook = vi.fn(() => ({ laneUserId: 'g/oc_chat1/omt_ctr' }));
+ wsClient.setGroupMainFlowLaneOverride(hook);
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](
+ groupTopicMessage('话题里回复', 'omt_existing'),
+ );
+
+ expect(hook).not.toHaveBeenCalled();
+ expect(mocks.openThread).not.toHaveBeenCalled();
+ expect(events[0].senderId).toBe('g/oc_chat1/omt_existing');
+ });
+
+ it('钩子返回非法 lane(非 g/ 前缀)时原样透传, 路由裁决交给下游', async () => {
+ // 钩子的返回值由 host 保证形状; transport 不做二次校验, 只透传。
+ wsClient.setGroupMainFlowLaneOverride(() => ({ laneUserId: 'g/oc_chat1' }));
+ const events = collectMessages();
+ await connect();
+
+ await mocks.eventHandlers['im.message.receive_v1'](groupMainFlowMessage('群 lane 接管'));
+
+ expect(events[0].senderId).toBe('g/oc_chat1');
+ });
+});
diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.ts
index 17082f0737..376e0d57ef 100644
--- a/packages/lizi-im/src/feishu/index.ts
+++ b/packages/lizi-im/src/feishu/index.ts
@@ -79,6 +79,16 @@ export class FeishuIM extends BaseIM implements ChannelIM {
});
}
+ /**
+ * 注册群主流消息的 lane 覆写钩子(host 策略, /ctr 接管路由)。
+ * 见 wsClient.setGroupMainFlowLaneOverride。
+ */
+ setGroupMainFlowLaneOverride(
+ fn: wsClient.GroupMainFlowLaneOverride | null,
+ ): void {
+ wsClient.setGroupMainFlowLaneOverride(fn);
+ }
+
registerIpc(): void {
registerFeishuIpc();
}
diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.ts
index c8ff27ff27..d9cd372b5e 100644
--- a/packages/lizi-im/src/feishu/wsClient.ts
+++ b/packages/lizi-im/src/feishu/wsClient.ts
@@ -120,6 +120,46 @@ export function setLifecycleAnnouncement(enabled: boolean): void {
getLog().info(`[feishu/wsClient] lifecycleAnnouncement set to ${enabled}`);
}
+export interface GroupMainFlowLaneOverrideArgs {
+ chatId: string;
+ senderOpenId: string;
+ botAppId: string;
+ /** 群消息原文(已剥 @ 占位符)。 */
+ text: string;
+}
+
+export interface GroupMainFlowLaneOverrideResult {
+ /** 接管话题 lane(g/{chatId}/{threadId} 形态)。 */
+ laneUserId: string;
+ /**
+ * 接管话题**内**的消息 id 作回复锚点(如 /ctr 控制卡的 messageId)。
+ * 群主流的触发消息不是合法锚点: 话题 lane 的回复必须 reply 到话题内
+ * 消息才能落回话题, 用顶层消息当锚点会把回复打进群主流。缺省时不 push
+ * 锚点 —— outbound 会复用该 lane 上一回合持有的话题内锚点; 完全没有时
+ * fail-closed 丢消息(位置错误比丢失更糟, 见 outbound.resolveSendTarget)。
+ */
+ replyAnchorMessageId?: string;
+}
+
+/**
+ * 群主流消息的 lane 覆写钩子(host 注入, /ctr 接管路由用)。
+ *
+ * host(desktop adapter)在本群存在活跃 /ctr 接管时返回接管话题的 lane ——
+ * 这条群主流消息就不开新话题、直接以接管 lane 路由(senderId 与出站回复
+ * 都落在接管话题, 会话状态进接管 desktop session)。返回 null = 默认行为
+ * (开话题 / 群 lane 降级)。未注入 = 默认行为。钩子是模块级单例, 与
+ * 单连接生命周期一致(last-wins, 换账号重建 adapter 时重新注册)。
+ */
+export type GroupMainFlowLaneOverride = (
+ args: GroupMainFlowLaneOverrideArgs,
+) => GroupMainFlowLaneOverrideResult | null;
+
+let groupMainFlowLaneOverride: GroupMainFlowLaneOverride | null = null;
+
+export function setGroupMainFlowLaneOverride(fn: GroupMainFlowLaneOverride | null): void {
+ groupMainFlowLaneOverride = fn;
+}
+
/**
* 拉取 bot 自身 open_id(判群 @ 用)。SDK 无专用封装, 走 Client.request 通用
* 通道。失败只 log warn — 群功能惰性失效(群消息全丢), 私聊不受影响。
@@ -691,20 +731,39 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
laneUserId = encodeLaneUserId(chatId, incomingThreadId);
outbound.pushReplyAnchor(laneUserId, messageId);
} else {
- const opener = await outbound.openThread(messageId);
- if (opener) {
- laneUserId = encodeLaneUserId(chatId, opener.threadId);
- outbound.pushReplyAnchor(laneUserId, opener.messageId);
- // 开场白卡是本轮流式卡: streamingText.start 认领后直接 patch,
- // 话题里不会多出一条占位消息。
- outbound.pushPatchableOpener(laneUserId, opener.messageId);
- // 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按
- // 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到
- // 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。
+ // /ctr 接管路由: host 声明「这条群主流消息应落进接管话题」时不开新
+ // 话题, 直接以接管话题 lane 路由 —— 回复也进同一话题, 群里不会为
+ // 接管期间的主流程消息再冒一个新话题(空开场白卡无处收口)。
+ const takeover =
+ groupMainFlowLaneOverride?.({ chatId, senderOpenId, botAppId, text }) ?? null;
+ if (takeover) {
+ laneUserId = takeover.laneUserId;
+ // 回复锚点必须是接管话题**内**的消息(host 给出, 如 /ctr 控制卡):
+ // 群主流的触发消息不是话题内消息, 拿它当锚点会把回复打进群主流。
+ // host 给不出锚点时也不 push —— outbound 复用该 lane 上一回合
+ // 持有的话题内锚点; 完全没有则 fail-closed 丢消息(不泄漏进主流)。
+ if (takeover.replyAnchorMessageId) {
+ outbound.pushReplyAnchor(laneUserId, takeover.replyAnchorMessageId);
+ }
+ // 上下文取数 lane 仍指向群主流: 接管话题里回复, 历史前缀照旧从
+ // 群主流取(与开话题路径的 groupContextLane 同语义)。
groupContextLane = { chatId, threadId: '' };
} else {
- laneUserId = encodeLaneUserId(chatId, null);
- outbound.pushReplyAnchor(laneUserId, messageId);
+ const opener = await outbound.openThread(messageId);
+ if (opener) {
+ laneUserId = encodeLaneUserId(chatId, opener.threadId);
+ outbound.pushReplyAnchor(laneUserId, opener.messageId);
+ // 开场白卡是本轮流式卡: streamingText.start 认领后直接 patch,
+ // 话题里不会多出一条占位消息。
+ outbound.pushPatchableOpener(laneUserId, opener.messageId);
+ // 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按
+ // 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到
+ // 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。
+ groupContextLane = { chatId, threadId: '' };
+ } else {
+ laneUserId = encodeLaneUserId(chatId, null);
+ outbound.pushReplyAnchor(laneUserId, messageId);
+ }
}
}
}