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。

feat(feishu): 群主流 @ 自动开话题 + 话题会话标题 [飞书·群名·话题简介]

Lizi03ff597f011d
diff --git a/apps/desktop/help-knowledge/feishu-bot.md b/apps/desktop/help-knowledge/feishu-bot.md
index 1c86f2feea..207c2768da 100644
--- a/apps/desktop/help-knowledge/feishu-bot.md
+++ b/apps/desktop/help-knowledge/feishu-bot.md
@@ -23,9 +23,10 @@ Cindy can send DMs and take commands through a FeiShu (Lark) bot. (This is unrel
**Group chats:**
-- In a group, @ the bot to ask a question. The bot pages back through recent chat history (newest first, until the messages stop being relevant to your question) and answers with that history as context — including images and files shared in the chat.
-- @-ing the bot inside a thread (话题) uses that thread's own history as context instead of the main group stream.
-- Group sessions are titled `[飞书·群] {group name}` / `[飞书·话题] {group name}` in the sidebar.
+- In a group, @ the bot to ask a question. The bot opens a new thread (话题) for the reply — the main stream stays clean and each thread is its own session, like Slack threads.
+- The bot pages back through recent chat history (newest first, until the messages stop being relevant to your question) and answers with that history as context — including images and files shared in the chat. For a fresh thread opened from the main stream, the context still comes from the main stream history.
+- @-ing the bot inside an existing thread uses that thread's own history as context.
+- Thread sessions are titled `[飞书·{group name}·{topic summary}] {id suffix}` in the sidebar.
**Permissions for group features:**
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 b29052eacd..9a329a25a0 100644
--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts
@@ -214,12 +214,38 @@ describe('feishu group lane adapter hooks', () => {
expect(await adapter.sessions.resolveSessionTitle?.('g/oc_chat3')).toBeNull();
});
- it('skipOneshotTitleFor: 群 lane 不参与 oneshot 起名, DM lane 照常', () => {
+ it('skipOneshotTitleFor: 群主流 lane 不参与 oneshot 起名, 话题 lane 与 DM 照常', () => {
expect(adapter.sessions.skipOneshotTitleFor?.('g/oc_chat1')).toBe(true);
- expect(adapter.sessions.skipOneshotTitleFor?.('g/oc_chat1/omt_t1')).toBe(true);
+ expect(adapter.sessions.skipOneshotTitleFor?.('g/oc_chat1/omt_t1')).toBe(false);
expect(adapter.sessions.skipOneshotTitleFor?.('ou_owner')).toBe(false);
});
+ it('composeGeneratedTitle: 话题 lane 拼 [飞书·{群名}·{简介}] {threadId 后 6 位}', async () => {
+ // 群名缓存是模块级状态, 各用例用独立 chatId 避免串。
+ getChatName.mockResolvedValueOnce('产品交流群');
+ expect(
+ await adapter.sessions.composeGeneratedTitle?.(
+ 'g/oc_chat5/omt_8f9ce6ab',
+ undefined,
+ '周进度总结',
+ 's1',
+ ),
+ ).toBe('[飞书·产品交流群·周进度总结] 9ce6ab');
+ });
+
+ it('composeGeneratedTitle: 群名未知退化为 [飞书·话题·{简介}]; DM/群主流 lane 返回 null 回落', async () => {
+ getChatName.mockResolvedValueOnce(null);
+ expect(
+ await adapter.sessions.composeGeneratedTitle?.('g/oc_chat6/omt_t2', undefined, '简介', 's1'),
+ ).toBe('[飞书·话题·简介] omt_t2');
+ expect(
+ await adapter.sessions.composeGeneratedTitle?.('ou_owner', undefined, 'x', 's1'),
+ ).toBeNull();
+ expect(
+ await adapter.sessions.composeGeneratedTitle?.('g/oc_chat6', undefined, 'x', 's1'),
+ ).toBeNull();
+ });
+
it('群轮次(speaker 存在)挂 channel 强确认策略; DM 不挂', () => {
const policy = adapter.turnPermissionPolicyFor?.(groupEvent());
expect(policy).toBeDefined();
@@ -246,6 +272,26 @@ describe('feishu group lane adapter hooks', () => {
expect(result?.agentText.endsWith('上面说的问题怎么解决')).toBe(true);
});
+ it('prepareAgentTurnText: 群主流 @ 开新话题时按 groupContextLane(群主流)拉上下文', async () => {
+ fetchChatHistoryPage.mockResolvedValueOnce(
+ historyPage([historyEntry({ messageId: 'om_h1', threadId: '', text: '群主流背景' })]),
+ );
+ const result = await adapter.prepareAgentTurnText?.(
+ groupEvent({
+ senderId: 'g/oc_chat1/omt_new1',
+ groupContextLane: { chatId: 'oc_chat1', threadId: '' },
+ }),
+ );
+ // 上下文按群主流 lane 拉取, 不走新话题的 thread 容器
+ expect(fetchChatHistoryPage).toHaveBeenCalledWith(
+ expect.objectContaining({ chatId: 'oc_chat1' }),
+ );
+ expect(fetchChatHistoryPage).not.toHaveBeenCalledWith(
+ expect.objectContaining({ threadId: 'omt_new1' }),
+ );
+ expect(result?.agentText).toContain('群主流背景');
+ });
+
it('prepareAgentTurnText: 话题 lane 按 thread 容器拉取, 只取本话题的消息', async () => {
fetchChatHistoryPage.mockResolvedValueOnce(
historyPage([
diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.ts
index a7fc83e7c3..7bdf4e506d 100644
--- a/apps/desktop/src/main/im/feishu/adapter.ts
+++ b/apps/desktop/src/main/im/feishu/adapter.ts
@@ -8,9 +8,10 @@
* MCP (send_file_to_user)
* - ack emoji: REACTION_PROCESSING
* - 群 lane(senderId = `g/{chatId}[/{threadId}]`, @cindy/im feishu/codec.ts):
- * 每群/每话题一个会话; 群轮次挂强确认策略 + 触发时按页回翻群历史
- * (50/页, 最多 5 页, 模型相关性早停), 图片/文件下载后进上下文,
- * 统一防注入包裹(见 ./groupContext.ts)。
+ * 群主流 @ 入站即开话题(每话题一个会话, 群 lane 仅开话题失败的降级路径);
+ * 群轮次挂强确认策略 + 触发时按页回翻群历史(50/页, 最多 5 页, 模型相关性
+ * 早停), 图片/文件下载后进上下文, 统一防注入包裹(见 ./groupContext.ts)。
+ * 话题会话标题 = [飞书·{群名}·{话题简介}] {threadId 后 6 位}。
* (飞书有拉历史 API, 不需要 telegram 那样的本地群消息池)。
*/
@@ -182,8 +183,9 @@ export function buildFeishuAdapter(
feishuBotAppId: botAppId,
feishuOpenId: userId,
}),
- // 群 lane 建行后异步拉群名把标题升级为 [飞书·群] {群名} /
+ // 群/话题 lane 建行后异步拉群名把标题升级为 [飞书·群] {群名} /
// [飞书·话题] {群名}; 拉不到(无「获取群基本信息」权限)保持后缀回落。
+ // 只对新建行生效(sessionRepo 侧保证), 复活行保留自己的历史标题。
resolveSessionTitle: async (userId) => {
const lane = decodeFeishuLaneUserId(userId);
if (!lane) return null;
@@ -191,9 +193,23 @@ export function buildFeishuAdapter(
if (!name) return null;
return `${groupPrefix(lane.threadId)}${name}`;
},
- // 群 lane 标题是稳定的群名, 不参与首条消息的 oneshot 起名
- // (否则会被首条消息话题标题漂掉, 且拿到的还是 DM 前缀)。
- skipOneshotTitleFor: (userId) => userId.startsWith('g/'),
+ // 群主流 lane(仅开话题失败的降级路径)标题是稳定的群名, 不参与首条消息
+ // oneshot 起名; 话题 lane 需要 oneshot 出「话题简介」, 照常参与。
+ skipOneshotTitleFor: (userId) => {
+ const lane = decodeFeishuLaneUserId(userId);
+ return lane !== null && lane.threadId === '';
+ },
+ // 话题 lane 的 oneshot 标题拼装: [飞书·{群名}·{话题简介}] {threadId 后 6 位}
+ // — 群名拉不到时退化为 [飞书·话题·{简介}]。DM/群主流 lane 返回 null,
+ // 回落默认 generatedTitlePrefix 路径(DM → [飞书·DM] {简介})。
+ composeGeneratedTitle: async (userId, _scopeKey, generated) => {
+ const lane = decodeFeishuLaneUserId(userId);
+ if (!lane || !lane.threadId) return null;
+ const name = await resolveChatName(feishuIm, lane.chatId);
+ const label = isLark() ? 'Lark' : '飞书';
+ const mid = name ? `${label}·${name}·${generated}` : `${label}·话题·${generated}`;
+ return `[${mid}] ${lane.threadId.slice(-6)}`;
+ },
},
processingEmoji: REACTION_PROCESSING,
buildVendorOptions: (userId) => ({ feishuChatId: userId, source: 'feishu' }),
@@ -206,8 +222,12 @@ export function buildFeishuAdapter(
prepareAgentTurnText: async (event) => {
const lane = decodeFeishuLaneUserId(event.senderId);
if (!lane) return null;
+ // 群主流 @ 开新话题: 上下文取数 lane 与路由 lane 分离(见
+ // IMMessageEvent.groupContextLane) — 新话题是空的, 群历史仍按群主流
+ // 拉取, 「总结上面」等依赖上文的消息才能拿到上下文。
+ const contextLane = event.groupContextLane ?? lane;
const built = await buildFeishuGroupContext({
- lane,
+ lane: contextLane,
triggerMessageId: event.messageId,
question: event.text,
deps: {
diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts
index 0f0191d554..7994f52401 100644
--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts
@@ -63,7 +63,7 @@ vi.mock('../../defaultSessionSettings', () => ({
})),
}));
-import { createImSessionRepo, refreshResolvedSessionTitle, type ImSessionRow } from '../sessionRepo';
+import { createImSessionRepo, type ImSessionRow } from '../sessionRepo';
import type { ImOrchestratorConfig, ImSessionNamespace } from '../types';
const ns: ImSessionNamespace = {
@@ -142,31 +142,20 @@ describe('sessionRepo.createSession broadcast', () => {
expect(mocks.updateSet).not.toHaveBeenCalled();
});
- it('refreshResolvedSessionTitle: 解析结果与现名不同才写库+广播; 相同/null 不动', async () => {
- mocks.selectLimit.mockResolvedValueOnce([{ title: '[飞书·群] oc_abc123' }]);
- mocks.updateSet.mockClear();
- await refreshResolvedSessionTitle({
- sessionId: 'feishu_cli_abc_g-oc_abc123',
- resolve: async () => '[飞书·群] 产品交流群',
- });
- expect(mocks.updateSet).toHaveBeenCalledWith({ title: '[飞书·群] 产品交流群' });
- expect(mocks.webContentsSend).toHaveBeenCalledWith('local-db:sessions:patched', {
- sessionId: 'feishu_cli_abc_g-oc_abc123',
- patch: { title: '[飞书·群] 产品交流群' },
+ it('resolveSessionTitle 只对新建行生效 — 复活行保留历史标题不回调解析器', async () => {
+ // upsert 前预检 select 返回已存在的行 → 复活路径, 不解析标题
+ // (oneshot 拼装过的话题名不能被渠道解析结果刷掉)。
+ mocks.selectLimit.mockResolvedValueOnce([{ title: '[飞书·群名·简介] abc123' }]);
+ const resolveSessionTitle = vi.fn<
+ (userId: string, scopeKey?: string) => Promise<string | null>
+ >(async () => '[飞书·群] 产品交流群');
+ const repo = createImSessionRepo({ agentKind: 'claude-code' } as ImOrchestratorConfig, {
+ ...ns,
+ resolveSessionTitle,
});
-
- // 解析结果与现名相同 → 不动行
- mocks.selectLimit.mockResolvedValueOnce([{ title: '[飞书·群] 产品交流群' }]);
mocks.updateSet.mockClear();
- await refreshResolvedSessionTitle({
- sessionId: 'feishu_cli_abc_g-oc_abc123',
- resolve: async () => '[飞书·群] 产品交流群',
- });
- expect(mocks.updateSet).not.toHaveBeenCalled();
-
- // 解析器返回 null(如拉不到群名) → 不动行
- mocks.selectLimit.mockResolvedValueOnce([{ title: 'old' }]);
- await refreshResolvedSessionTitle({ sessionId: 'x', resolve: async () => null });
+ await repo.createSession('bot', 'user', undefined, preparedRow);
+ expect(resolveSessionTitle).not.toHaveBeenCalled();
expect(mocks.updateSet).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/im/shared/fbotTitle.ts b/apps/desktop/src/main/im/shared/fbotTitle.ts
index 7116bc8546..3de1b54107 100644
--- a/apps/desktop/src/main/im/shared/fbotTitle.ts
+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts
@@ -48,9 +48,7 @@ export async function generateAndPersistFbotTitle(
seedText: string,
prefix: string = FBOT_TITLE_PREFIX,
): Promise<string | null> {
- const generated = (
- await generateMakerSessionTitle(seedText, 'claude-code', sessionId)
- )?.trim();
+ const generated = await generateImSessionTitleText(sessionId, seedText);
if (!generated) return null;
const title = fbotTitle(generated, prefix);
@@ -58,3 +56,18 @@ export async function generateAndPersistFbotTitle(
broadcastSessionPatched(sessionId, { title });
return title;
}
+
+/** 只生成标题文本(不落库) — 供渠道自定义拼装(飞书话题标题)复用 oneshot 通道。 */
+export async function generateImSessionTitleText(
+ sessionId: string,
+ seedText: string,
+): Promise<string | null> {
+ const generated = (await generateMakerSessionTitle(seedText, 'claude-code', sessionId))?.trim();
+ return generated || null;
+}
+
+/** 落库 + 广播一个已拼装好的标题(渠道 composeGeneratedTitle 的产物)。 */
+export async function persistGeneratedSessionTitle(sessionId: string, title: string): Promise<void> {
+ await desktopSessionStorage.update(sessionId, { title });
+ broadcastSessionPatched(sessionId, { title });
+}
diff --git a/apps/desktop/src/main/im/shared/sessionRepo.ts b/apps/desktop/src/main/im/shared/sessionRepo.ts
index bc9eee7f13..c7b8c58dfe 100644
--- a/apps/desktop/src/main/im/shared/sessionRepo.ts
+++ b/apps/desktop/src/main/im/shared/sessionRepo.ts
@@ -387,6 +387,16 @@ export function createImSessionRepo(
userSendAt: now,
},
});
+ // upsert 前先判行是否已存在: resolveSessionTitle 只对**新建行**生效 —
+ // 复活行带着自己的历史标题(oneshot 拼装的话题名等), 不能被渠道解析
+ // 结果刷掉(飞书话题 lane 首条消息会把标题升级成 [飞书·群名·简介] 格式,
+ // 复活时再刷回 [飞书·群名] 后缀格式就是数据回退)。
+ const preRows = await db
+ .select({ title: sessions.title })
+ .from(sessions)
+ .where(eq(sessions.id, row.id))
+ .limit(1);
+ const isFreshInsert = preRows.length === 0;
// upsert 可能走冲突分支(残留行的 sdkSessionId / 模型 / 权限被刻意保留),
// 返回值必须以 DB 持久化结果为准——直接返回 prepared 默认值会让 turn 拿
// sdkSessionId=null 新开对话,而 DB 里旧上下文仍标记 active,两边失配。
@@ -395,19 +405,20 @@ export function createImSessionRepo(
.from(sessions)
.where(eq(sessions.id, row.id))
.limit(1);
- return persistedRows[0];
+ return { row: persistedRows[0], isFreshInsert };
});
- const result: ImSessionRow = persisted
+ const persistedRow = persisted?.row;
+ const result: ImSessionRow = persistedRow
? {
- id: persisted.id,
- agentKind: toCoreAgentKind(persisted.agentKind),
- workingDir: persisted.workingDir ?? row.workingDir,
- model: persisted.model,
- effort: persisted.effort,
- permissionMode: persisted.permissionMode,
- fastMode: persisted.fastMode,
- sdkSessionId: persisted.sdkSessionId,
- providerId: persisted.providerId ?? null,
+ id: persistedRow.id,
+ agentKind: toCoreAgentKind(persistedRow.agentKind),
+ workingDir: persistedRow.workingDir ?? row.workingDir,
+ model: persistedRow.model,
+ effort: persistedRow.effort,
+ permissionMode: persistedRow.permissionMode,
+ fastMode: persistedRow.fastMode,
+ sdkSessionId: persistedRow.sdkSessionId,
+ providerId: persistedRow.providerId ?? null,
}
: row;
log.info(
@@ -417,10 +428,11 @@ export function createImSessionRepo(
);
// 通知 renderer sidebar / device-link 控制端有新会话行,否则要手动刷新才出现
broadcastSessionCreated(result.id);
- // 渠道可异步解析正式标题(飞书群 lane → 拉群名拼 [飞书·群] {群名})。
- // 值稳定且幂等, 复活行同样刷新(群改名后下次消息即更新); 失败/无结果
- // 保持 defaultTitle, 不阻塞建行。
- if (ns.resolveSessionTitle) {
+ // 渠道可异步解析正式标题(飞书群/话题 lane → 拉群名拼 [飞书·群/话题] {群名}),
+ // 只对**新建行**生效 — 复活行保留自己的历史标题(首条消息 oneshot 会把
+ // 话题会话升级成 [飞书·群名·简介] 格式, 不能回刷)。失败/无结果保持
+ // defaultTitle, 不阻塞建行。
+ if (ns.resolveSessionTitle && persisted?.isFreshInsert !== false) {
try {
const resolved = await ns.resolveSessionTitle(userId, scopeKey);
if (resolved) {
@@ -460,31 +472,6 @@ function rowFromDefaults(
// ── sessionId 维度的更新操作(渠道无关, 无需工厂) ─────────────────────────────
-/**
- * 存量会话标题自愈: 读行当前 title, 用渠道解析器(飞书群 lane → 群名)
- * 拿正式标题, 只有真的不同才写库 + 广播。旧版本建行的会话标题停在旧格式
- * (id 后缀 / 早前被 oneshot 漂成 DM 前缀), 由 turnRunner 在存量行下次收到
- * 消息时后台调用。解析器返回 null(拉不到)或结果与现名相同都不动行;
- * 失败向上抛, 调用方 swallow — 标题是展示层, 不阻塞 turn。
- */
-export async function refreshResolvedSessionTitle(args: {
- sessionId: string;
- resolve: () => Promise<string | null>;
-}): Promise<void> {
- const db = getDbClient().drizzle;
- const rows = await db
- .select({ title: sessions.title })
- .from(sessions)
- .where(eq(sessions.id, args.sessionId))
- .limit(1);
- const current = rows[0]?.title;
- if (current === undefined) return;
- const resolved = await args.resolve();
- if (!resolved || resolved === current) return;
- await db.update(sessions).set({ title: resolved }).where(eq(sessions.id, args.sessionId));
- broadcastSessionPatched(args.sessionId, { title: resolved });
-}
-
/** Bump userSendAt so sidebar (if ever surfaced) sorts IM sessions correctly. */
export async function touchUserSent(sessionId: string): Promise<void> {
const db = getDbClient().drizzle;
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 27f3292ca2..0e59d12bb5 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -121,7 +121,12 @@ import {
type ImAuthRouteStatus,
type ImAuthCheckDeps,
} from './authCheck';
-import { FBOT_DRAFT_TITLE, generateAndPersistFbotTitle } from './fbotTitle';
+import {
+ FBOT_DRAFT_TITLE,
+ generateAndPersistFbotTitle,
+ generateImSessionTitleText,
+ persistGeneratedSessionTitle,
+} from './fbotTitle';
import { materializeLocalMarkdownImages } from './localMarkdownImages';
import {
createTurnActivity,
@@ -136,7 +141,6 @@ import { createTurnPresenter, DEFAULT_PRESENTER_POLICY, type TurnPresenter } fro
import {
toCoreAgentKind,
readPermissionMode,
- refreshResolvedSessionTitle,
touchUserSent as repoTouchUserSent,
updatePermissionMode,
type ImSessionRepo,
@@ -748,24 +752,6 @@ export function createTurnRunner(
((operation: () => Promise<void>): void => {
void operation();
});
- // 存量会话标题自愈: 旧版本建行的会话标题停在旧格式(id 后缀 / 早前被
- // oneshot 漂成 DM 前缀), 存量行下次收到消息时后台解析正式标题并刷新
- // (飞书群 lane → [飞书·群] {群名})。新建行由 createSession 建行时解析,
- // 这里只补存量; 失败 swallow, 标题是展示层, 不阻塞 turn。
- const resolveSessionTitle = adapter.sessions.resolveSessionTitle;
- if (!target.created && resolveSessionTitle) {
- startBackgroundTask(async () => {
- try {
- await refreshResolvedSessionTitle({
- sessionId: row.id,
- resolve: () => resolveSessionTitle(userId, target.scopeKey),
- });
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.warn(`session title refresh failed (non-fatal): ${msg}`);
- }
- });
- }
// 受保护群的触发消息不能被总结成会话标题。标题是**长期记录**, 会一直挂在
// 侧边栏上 —— 把「禁止保存内容」的正文摘要留在那里, 与把它写进 transcript
// 是同一条边界被绕过, 而且主 turn 最终没被 provider 接受时照样会留下。
@@ -794,7 +780,9 @@ export function createTurnRunner(
// 非 threadScoped 渠道(feishu/discord, 一 (bot,user) 一行长期复用):
// 每条"新对话"的首条消息重新起名 —— sdkSessionId == null 即新上下文
// (首次建行 / /new 重置后), 标题跟随当前话题而不是永远停在第一次。
- startBackgroundTask(() => maybeGenerateImSessionTitle(row.id, text, threadHeaderCardId));
+ startBackgroundTask(() =>
+ maybeGenerateImSessionTitle(row.id, userId, target.scopeKey, text, threadHeaderCardId),
+ );
}
const item: QueuedSend = {
@@ -1701,15 +1689,38 @@ export function createTurnRunner(
*/
async function maybeGenerateImSessionTitle(
sessionId: string,
+ userId: string,
+ scopeKey: string | undefined,
text: string,
headerCardId: string | null,
): Promise<void> {
const threadUiPack = adapter.ui.thread;
const configuredPrefix = adapter.sessions.generatedTitlePrefix;
- if (configuredPrefix === undefined && !(adapter.threadScoped && threadUiPack)) return;
+ const composeTitle = adapter.sessions.composeGeneratedTitle;
+ if (
+ configuredPrefix === undefined &&
+ !composeTitle &&
+ !(adapter.threadScoped && threadUiPack)
+ )
+ return;
const prefix = typeof configuredPrefix === 'function' ? configuredPrefix() : configuredPrefix;
try {
- const title = await generateAndPersistFbotTitle(sessionId, text, prefix);
+ let title: string | null;
+ if (composeTitle) {
+ // 渠道自定义拼装(飞书话题 lane → [飞书·{群名}·{简介}] {threadId 后 6 位}):
+ // oneshot 只负责出「话题简介」文本, 完整标题由渠道按 lane 拼; 返回 null
+ // (该 lane 不适用, 如 DM)回落默认 prefix 路径。
+ const generated = await generateImSessionTitleText(sessionId, text);
+ if (!generated) return;
+ title = await composeTitle(userId, scopeKey, generated, sessionId);
+ if (title) {
+ await persistGeneratedSessionTitle(sessionId, title);
+ } else {
+ title = await generateAndPersistFbotTitle(sessionId, text, prefix);
+ }
+ } else {
+ title = await generateAndPersistFbotTitle(sessionId, text, prefix);
+ }
if (!richIm || !title || !headerCardId || !threadUiPack) return;
await richIm.updateInteractiveCard(headerCardId, {
...threadUiPack.sessionHeaderTitled(title),
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index a3c87d2831..0c881e0012 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -91,10 +91,23 @@ export interface ImSessionNamespace {
*/
resolveSessionTitle?(userId: string, scopeKey?: string): Promise<string | null>;
/**
- * 该 userId 的会话不参与 oneshot 起名(飞书群 lane 的标题是稳定的
- * 「群名」, 不该被首条消息的话题标题漂掉; DM lane 仍照常起名)。
+ * 该 userId 的会话不参与 oneshot 起名(飞书群主流 lane 只剩开话题失败的
+ * 降级路径, 标题是稳定的「群名」, 不该被首条消息的话题标题漂掉;
+ * 话题 lane 与 DM lane 仍照常起名)。
*/
skipOneshotTitleFor?(userId: string): boolean;
+ /**
+ * 渠道自定义 oneshot 标题拼装(飞书话题 lane →
+ * `[飞书·{群名}·{话题简介}] {threadId 后 6 位}`)。收到 oneshot 生成的
+ * 简介文本后返回完整标题; 返回 null = 该 lane 不适用, 回落默认
+ * generatedTitlePrefix 路径。
+ */
+ composeGeneratedTitle?(
+ userId: string,
+ scopeKey: string | undefined,
+ generated: string,
+ sessionId: string,
+ ): Promise<string | null>;
/**
* 非接管会话 oneshot 生成正式标题时的前缀(如 'Slack · ' / '[飞书·DM] ')。
* - threadScoped 渠道(slack): 新 thread 会话的首条消息触发;
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index d8f33a0795..41b137be8c 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -47,7 +47,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
title: "Setting up the FeiShu (Lark) bot",
summary: "Configure the FeiShu bot (App ID / App Secret) in Settings > IM bots to get DM notifications and bot interaction.",
tab: "im-bot",
- content: "Cindy can send DMs and take commands through a FeiShu (Lark) bot. (This is unrelated to signing into Cindy — you sign in with your Cindy account; FeiShu is no longer a login method.)\n\n**Setting up the bot:**\n\n- Open Settings > IM bots, then the FeiShu Bot section.\n- Paste the bot's **App ID** and **App Secret**, then click **Bind**.\n- The status badge updates: **needs-config** → **connecting** → **connected** (or **conflict** / **error**).\n\n**Binding the bot to you:**\n\n- After the badge shows **connected**, the page instructs you to DM the bot a code (or click an action) to complete the binding. Until you bind, the bot won't know which FeiShu user to DM.\n\n**Notifications:**\n\n- Toggle **message notifications** on the same page to get bot DMs when sessions finish, or when the bot has updates for you.\n- The desktop-OS-level \"session finished\" notification is a separate toggle in **Settings > General > Notifications**.\n\n**Group chats:**\n\n- In a group, @ the bot to ask a question. The bot pages back through recent chat history (newest first, until the messages stop being relevant to your question) and answers with that history as context — including images and files shared in the chat.\n- @-ing the bot inside a thread (话题) uses that thread's own history as context instead of the main group stream.\n- Group sessions are titled `[飞书·群] {group name}` / `[飞书·话题] {group name}` in the sidebar.\n\n**Permissions for group features:**\n\nGroup chat context needs an extra app permission that is not part of the default setup:\n\n1. Open the **FeiShu (Lark) Open Platform** → Developer Console → your app → **Permissions & Scopes** (权限管理).\n2. Search for and enable **both** of the following (searching by the scope id works regardless of the console language):\n - **\"Read all messages in associated group chat\" (获取群组中所有消息, `im:message.group_msg`)** — pulls the chat history via API.\n - **\"Read user and bot messages in group chats\" (获取群组中用户和机器人消息, `im:message.group_msg.include_bot:read`)** — needed for group message events, so the history covers messages from other bots too.\n These are sensitive permissions: on FeiShu they are only available to self-built apps (自建应用), not store apps.\n3. Create and publish a new app **version** (self-built apps need admin approval).\n\nWithout it the bot still answers when @-ed, but with no chat context, and it DMs the owner a one-line heads-up pointing here. Optionally, enabling **\"Obtain basic group information\" (获取群基本信息, `im:chat:readonly`)** lets session titles show the real group name instead of an id suffix.\n\n**Notes:**\n\n- The \"conflict\" badge state means another Cindy instance is already bound to the same bot for this user — typical when running dev + release simultaneously. Disconnect on one side to clear it.\n- Settings > IM bots also hosts the Slack and Telegram bindings (the \"Cindy\" tab) and a bring-your-own Discord bot, alongside this FeiShu bot.",
+ content: "Cindy can send DMs and take commands through a FeiShu (Lark) bot. (This is unrelated to signing into Cindy — you sign in with your Cindy account; FeiShu is no longer a login method.)\n\n**Setting up the bot:**\n\n- Open Settings > IM bots, then the FeiShu Bot section.\n- Paste the bot's **App ID** and **App Secret**, then click **Bind**.\n- The status badge updates: **needs-config** → **connecting** → **connected** (or **conflict** / **error**).\n\n**Binding the bot to you:**\n\n- After the badge shows **connected**, the page instructs you to DM the bot a code (or click an action) to complete the binding. Until you bind, the bot won't know which FeiShu user to DM.\n\n**Notifications:**\n\n- Toggle **message notifications** on the same page to get bot DMs when sessions finish, or when the bot has updates for you.\n- The desktop-OS-level \"session finished\" notification is a separate toggle in **Settings > General > Notifications**.\n\n**Group chats:**\n\n- In a group, @ the bot to ask a question. The bot opens a new thread (话题) for the reply — the main stream stays clean and each thread is its own session, like Slack threads.\n- The bot pages back through recent chat history (newest first, until the messages stop being relevant to your question) and answers with that history as context — including images and files shared in the chat. For a fresh thread opened from the main stream, the context still comes from the main stream history.\n- @-ing the bot inside an existing thread uses that thread's own history as context.\n- Thread sessions are titled `[飞书·{group name}·{topic summary}] {id suffix}` in the sidebar.\n\n**Permissions for group features:**\n\nGroup chat context needs an extra app permission that is not part of the default setup:\n\n1. Open the **FeiShu (Lark) Open Platform** → Developer Console → your app → **Permissions & Scopes** (权限管理).\n2. Search for and enable **both** of the following (searching by the scope id works regardless of the console language):\n - **\"Read all messages in associated group chat\" (获取群组中所有消息, `im:message.group_msg`)** — pulls the chat history via API.\n - **\"Read user and bot messages in group chats\" (获取群组中用户和机器人消息, `im:message.group_msg.include_bot:read`)** — needed for group message events, so the history covers messages from other bots too.\n These are sensitive permissions: on FeiShu they are only available to self-built apps (自建应用), not store apps.\n3. Create and publish a new app **version** (self-built apps need admin approval).\n\nWithout it the bot still answers when @-ed, but with no chat context, and it DMs the owner a one-line heads-up pointing here. Optionally, enabling **\"Obtain basic group information\" (获取群基本信息, `im:chat:readonly`)** lets session titles show the real group name instead of an id suffix.\n\n**Notes:**\n\n- The \"conflict\" badge state means another Cindy instance is already bound to the same bot for this user — typical when running dev + release simultaneously. Disconnect on one side to clear it.\n- Settings > IM bots also hosts the Slack and Telegram bindings (the \"Cindy\" tab) and a bring-your-own Discord bot, alongside this FeiShu bot.",
},
{
id: "getting-started",
diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
index 8c6647d794..20f1f0e924 100644
--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
@@ -8,18 +8,34 @@ const larkMocks = vi.hoisted(() => {
void payload;
return { data: { message_id: 'om_created' } };
});
- const reply = vi.fn(async (payload: { path: unknown; data: unknown }) => {
- void payload;
- return { data: { message_id: 'om_replied' } };
- });
- return { create, reply };
+ const reply = vi.fn(
+ async (payload: {
+ path: unknown;
+ data: unknown;
+ }): Promise<{ data: { message_id: string; thread_id?: string } }> => {
+ void payload;
+ return { data: { message_id: 'om_replied', thread_id: 'omt_r1' } };
+ },
+ );
+ const deleteMessage = vi.fn(async () => ({ data: {} }));
+ const getMessage = vi.fn(
+ async (): Promise<{ data: { items: Array<{ thread_id?: string }> } }> => ({
+ data: { items: [] },
+ }),
+ );
+ return { create, reply, deleteMessage, getMessage };
});
vi.mock('@larksuiteoapi/node-sdk', () => ({
Client: class {
im = {
v1: {
- message: { create: larkMocks.create, reply: larkMocks.reply },
+ message: {
+ create: larkMocks.create,
+ reply: larkMocks.reply,
+ delete: larkMocks.deleteMessage,
+ get: larkMocks.getMessage,
+ },
messageReaction: { create: vi.fn(), delete: vi.fn() },
image: { create: vi.fn() },
},
@@ -144,6 +160,68 @@ describe('feishu outbound lane routing', () => {
);
});
+ it('openThread replies with reply_in_thread + uuid and returns the new thread id', async () => {
+ const res = await outbound.openThread('om_root1', '开个话题');
+ expect(larkMocks.reply).toHaveBeenCalledWith(
+ expect.objectContaining({
+ path: { message_id: 'om_root1' },
+ data: expect.objectContaining({
+ msg_type: 'text',
+ reply_in_thread: true,
+ uuid: 'om_root1',
+ }),
+ }),
+ );
+ expect(res).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
+ });
+
+ it('openThread is idempotent per trigger message (duplicate delivery opens no second topic)', async () => {
+ const first = outbound.openThread('om_root2', '开个话题');
+ const second = outbound.openThread('om_root2', '开个话题');
+ expect(await first).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
+ expect(await second).toEqual({ messageId: 'om_replied', threadId: 'omt_r1' });
+ // 并发/重复调用只打一次 API — 飞书重投同一条 @ 事件不会开出多个话题。
+ expect(larkMocks.reply).toHaveBeenCalledTimes(1);
+ });
+
+ it('openThread recovers the thread_id via message.get when the reply response lacks it', async () => {
+ larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
+ larkMocks.getMessage.mockResolvedValueOnce({
+ data: { items: [{ thread_id: 'omt_recovered' }] },
+ });
+ const res = await outbound.openThread('om_root3', '开个话题');
+ expect(res).toEqual({ messageId: 'om_replied', threadId: 'omt_recovered' });
+ expect(larkMocks.getMessage).toHaveBeenCalledWith({
+ path: { message_id: 'om_replied' },
+ });
+ expect(larkMocks.deleteMessage).not.toHaveBeenCalled();
+ });
+
+ it('openThread recalls the opener and returns null when thread_id is unrecoverable', async () => {
+ larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
+ larkMocks.getMessage.mockResolvedValueOnce({ data: { items: [] } });
+ await expect(outbound.openThread('om_root4', 'x')).resolves.toBeNull();
+ // 开场白已发出但拿不到话题 id: 撤回它再降级, 不让「回复都在里面」误导。
+ expect(larkMocks.deleteMessage).toHaveBeenCalledWith({
+ path: { message_id: 'om_replied' },
+ });
+ });
+
+ it('openThread recalls the opener and returns null when message.get itself fails', async () => {
+ larkMocks.reply.mockResolvedValueOnce({ data: { message_id: 'om_replied' } });
+ larkMocks.getMessage.mockRejectedValueOnce(new Error('get failed'));
+ await expect(outbound.openThread('om_root5', 'x')).resolves.toBeNull();
+ expect(larkMocks.deleteMessage).toHaveBeenCalledWith({
+ path: { message_id: 'om_replied' },
+ });
+ });
+
+ it('openThread returns null instead of throwing when the API fails', async () => {
+ larkMocks.reply.mockRejectedValueOnce(new Error('no thread permission'));
+ await expect(outbound.openThread('om_root6', 'x')).resolves.toBeNull();
+ expect(larkMocks.deleteMessage).not.toHaveBeenCalled();
+ });
+
it('unbindClient clears held anchors (no cross-generation mismatch)', async () => {
outbound.pushReplyAnchor('g/oc_g', 'om_old');
outbound.unbindClient();
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
index 9b24649553..0510b7e5a0 100644
--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts
@@ -1,6 +1,6 @@
/**
* 群消息入站门禁: @ 检测、owner 门、非 owner 礼貌回应(冷却)、lane senderId、
- * mention 占位符剥离、thread_id → 话题 lane。
+ * mention 占位符剥离、thread_id → 话题 lane、群主流 @ 入站开话题。
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -18,6 +18,12 @@ const mocks = {
getBoundClient: vi.fn(() => null),
sendText: vi.fn(async () => ({ messageId: 'om_sent' })),
replyText: vi.fn(async () => ({ messageId: 'om_reply' })),
+ openThread: vi.fn(
+ async (): Promise<{ messageId: string; threadId: string } | null> => ({
+ messageId: 'om_opener',
+ threadId: 'omt_new',
+ }),
+ ),
pushReplyAnchor: vi.fn(),
firstAllowed: vi.fn<() => string | null>(() => null),
readOwnerOpenId: vi.fn<() => string | null>(() => null),
@@ -63,6 +69,7 @@ vi.doMock('../outbound.js', () => ({
getBoundClient: mocks.getBoundClient,
sendText: mocks.sendText,
replyText: mocks.replyText,
+ openThread: mocks.openThread,
pushReplyAnchor: mocks.pushReplyAnchor,
}));
@@ -193,28 +200,46 @@ describe('feishu group inbound gate', () => {
expect(events).toHaveLength(0);
});
- it('owner mention emits a lane event with speaker and strips the bot placeholder', async () => {
+ it('owner mention in main stream opens a thread and emits into the new topic lane', async () => {
await connect();
const events = collectEvents();
await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+ expect(mocks.openThread).toHaveBeenCalledWith('om_msg1', expect.any(String));
expect(events).toHaveLength(1);
const event = events[0]!;
- expect(event.senderId).toBe('g/oc_chat1');
+ expect(event.senderId).toBe('g/oc_chat1/omt_new');
expect(event.chatId).toBe('oc_chat1');
expect(event.text).toBe('帮我看看');
expect(event.speaker).toEqual({ id: OWNER, name: '', isOwner: true });
+ // 锚点是开场白消息(话题内合法锚点), 不是触发消息。
+ expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');
+ // 路由进新话题 lane, 但上下文取数 lane 仍是群主流(新话题是空的)。
+ expect(event.groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
+ });
+
+ it('falls back to the plain group lane when thread creation fails', async () => {
+ mocks.openThread.mockResolvedValueOnce(null);
+ await connect();
+ const events = collectEvents();
+ await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));
+
+ expect(events).toHaveLength(1);
+ expect(events[0]!.senderId).toBe('g/oc_chat1');
+ expect(events[0]!.groupContextLane).toBeUndefined();
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1', 'om_msg1');
});
- it('routes topic messages into a topic lane', async () => {
+ it('routes topic messages into a topic lane without opening a new thread', async () => {
await connect();
const events = collectEvents();
await mocks.eventHandlers['im.message.receive_v1']!(
groupMessage({ threadId: 'omt_topic7' }),
);
expect(events[0]!.senderId).toBe('g/oc_chat1/omt_topic7');
+ expect(events[0]!.groupContextLane).toBeUndefined();
expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_topic7', 'om_msg1');
+ expect(mocks.openThread).not.toHaveBeenCalled();
});
it('replaces other-user mention placeholders with sanitized display names', async () => {
diff --git a/packages/lizi-im/src/feishu/messages.ts b/packages/lizi-im/src/feishu/messages.ts
index 3021b86bee..f52b5772fa 100644
--- a/packages/lizi-im/src/feishu/messages.ts
+++ b/packages/lizi-im/src/feishu/messages.ts
@@ -20,6 +20,11 @@ export const messages = {
/** 非 owner 在群里 @bot 的礼貌回应(per-user 冷却防刷屏, 与 telegram 同语义)。 */
strangerNotice:
'👋 我是一位主人的个人 Cindy 助理,只响应主人本人的指令~\nI am a personal Cindy assistant and only respond to my owner.',
+ /**
+ * 群主流 @bot 时以触发消息为根开话题的开场白(reply_in_thread)。此后
+ * 本会话所有回复都落在话题里, 群主流不被刷屏; 每个话题是独立 session。
+ */
+ threadOpener: '🧵 开个话题聊这条, 回复都在里面 ~',
},
// (inbound.skipped removed — orchestrator owns the wording for "pure
// unsupported" / "mixed unsupported" replies; @cindy/im just emits the raw
diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.ts
index c42184c537..ee661a70dc 100644
--- a/packages/lizi-im/src/feishu/outbound.ts
+++ b/packages/lizi-im/src/feishu/outbound.ts
@@ -186,6 +186,130 @@ export async function replyText(
);
}
+// ── openThread (群主流 @ 开话题) ────────────────────────────────────────────
+// 开话题对同一触发消息幂等: 飞书可能重复投递同一条群主流 @ 事件(WS 重连等),
+// 不合并就会同一条消息开出多个话题、重复 agent 回答。进行中的请求共享同一
+// promise, 已完成的按 TTL 短缓存 — 重投事件直接复用同一个话题。缓存键是
+// 触发消息 id(平台内唯一), 不随 unbindClient 清空(换代不会重放别的消息 id)。
+
+interface OpenThreadResult {
+ messageId: string;
+ threadId: string;
+}
+
+const OPEN_THREAD_DEDUP_TTL_MS = 10 * 60_000;
+const OPEN_THREAD_DEDUP_MAX_ENTRIES = 200;
+const openThreadByTrigger = new Map<
+ string,
+ { ts: number; promise: Promise<OpenThreadResult | null> }
+>();
+
+function pruneOpenThreadDedup(): void {
+ const now = Date.now();
+ for (const [triggerId, entry] of openThreadByTrigger) {
+ if (now - entry.ts > OPEN_THREAD_DEDUP_TTL_MS) openThreadByTrigger.delete(triggerId);
+ }
+ while (openThreadByTrigger.size > OPEN_THREAD_DEDUP_MAX_ENTRIES) {
+ let oldestKey: string | undefined;
+ let oldestTs = Number.POSITIVE_INFINITY;
+ for (const [triggerId, entry] of openThreadByTrigger) {
+ if (entry.ts < oldestTs) {
+ oldestTs = entry.ts;
+ oldestKey = triggerId;
+ }
+ }
+ if (oldestKey === undefined) break;
+ openThreadByTrigger.delete(oldestKey);
+ }
+}
+
+/**
+ * 以 reply_in_thread 回复触发消息, 用它作为根开一个新话题。返回开场白消息
+ * id + 新话题 thread_id(话题内合法锚点)。同一触发消息并发/重复调用共享同
+ * 一次开话题 — 防飞书重投事件开出多个话题(含进程重启: uuid 走服务端去重)。
+ *
+ * 失败语义: API 失败或响应缺 message_id → null(没有可确认已发出的开场白);
+ * 响应有 message_id 但缺 thread_id → 用 message.get 补查话题 id, 查不到就
+ * 撤回开场白再返回 null — 不让「回复都在里面」的开场白承诺落空。调用方在
+ * null 时降级回群 lane 旧行为(引用回复 + chat_id 直发)。
+ */
+export function openThread(
+ replyToMessageId: string,
+ text: string,
+): Promise<OpenThreadResult | null> {
+ const now = Date.now();
+ const cached = openThreadByTrigger.get(replyToMessageId);
+ if (cached && now - cached.ts <= OPEN_THREAD_DEDUP_TTL_MS) return cached.promise;
+
+ const promise = doOpenThread(replyToMessageId, text);
+ openThreadByTrigger.set(replyToMessageId, { ts: now, promise });
+ pruneOpenThreadDedup();
+ return promise;
+}
+
+async function doOpenThread(
+ replyToMessageId: string,
+ text: string,
+): Promise<OpenThreadResult | null> {
+ const log = getLog();
+ try {
+ const res = await ensureClient().im.v1.message.reply({
+ path: { message_id: replyToMessageId },
+ data: {
+ content: JSON.stringify({ text }),
+ msg_type: 'text',
+ reply_in_thread: true,
+ // 服务端幂等键: 同一触发消息重复开话题(重投事件、进程重启后重放)时,
+ // 飞书按 uuid 去重(1 小时内同 uuid 至多发一条, 重复调用返回原消息
+ // id), 不会开出第二个话题。
+ uuid: replyToMessageId,
+ },
+ });
+ const messageId = res.data?.message_id ?? '';
+ const threadId = res.data?.thread_id ?? '';
+ if (!messageId) {
+ log.warn(
+ '[feishu/outbound] openThread: no message_id in response — nothing provably sent',
+ );
+ return null;
+ }
+ if (threadId) return { messageId, threadId };
+ // 部分成功: 开场白已发出但响应缺 thread_id — 补查消息详情恢复话题 id。
+ const recovered = await tryFetchMessageThreadId(messageId);
+ if (recovered) return { messageId, threadId: recovered };
+ // 恢复不了: 撤回开场白再降级, 避免「回复都在里面」的开场白留在群里误导。
+ try {
+ await ensureClient().im.v1.message.delete({ path: { message_id: messageId } });
+ log.warn(
+ '[feishu/outbound] openThread: thread_id unrecoverable — opener recalled, fallback to group lane',
+ );
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(
+ `[feishu/outbound] openThread: thread_id unrecoverable, opener recall failed (non-fatal): ${msg}`,
+ );
+ }
+ return null;
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`[feishu/outbound] openThread failed (fallback to group lane): ${msg}`);
+ return null;
+ }
+}
+
+/** 用 message.get 补查开场白消息的 thread_id(部分成功恢复);失败返回 ''。 */
+async function tryFetchMessageThreadId(messageId: string): Promise<string> {
+ const log = getLog();
+ try {
+ const res = await ensureClient().im.v1.message.get({ path: { message_id: messageId } });
+ return res.data?.items?.[0]?.thread_id ?? '';
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`[feishu/outbound] openThread: thread_id recovery via message.get failed: ${msg}`);
+ return '';
+ }
+}
+
// ── reactions (used by host orchestrator to ack user msgs) ────────────────────
/**
diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.ts
index 61cd7e3140..cc5de06482 100644
--- a/packages/lizi-im/src/feishu/wsClient.ts
+++ b/packages/lizi-im/src/feishu/wsClient.ts
@@ -679,13 +679,31 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
return;
}
- // 群 lane: senderId = g/{chatId}[/{threadId}], 出站按 lane 解码回群;
- // 记录回挂锚点让本轮回复(引用式)挂回触发消息(话题内回复顺带落回话题)。
- const laneUserId = isGroup
- ? encodeLaneUserId(chatId, data.message.thread_id)
- : null;
- if (laneUserId) {
- outbound.pushReplyAnchor(laneUserId, messageId);
+ // 群 lane: senderId = g/{chatId}[/{threadId}], 出站按 lane 解码回群。
+ // 话题内触发直接进话题 lane(锚点=触发消息, 回复自动落回话题); 群主流
+ // 触发先以触发消息为根开话题再进新话题 lane(锚点=开场白消息) — 每话题
+ // 独立 session, 群主流保持干净; 开话题失败才降级回群 lane 旧行为。
+ let laneUserId: string | null = null;
+ let groupContextLane: { chatId: string; threadId: string } | undefined;
+ if (isGroup) {
+ const incomingThreadId = data.message.thread_id;
+ if (incomingThreadId) {
+ laneUserId = encodeLaneUserId(chatId, incomingThreadId);
+ outbound.pushReplyAnchor(laneUserId, messageId);
+ } else {
+ const opener = await outbound.openThread(messageId, transportMessages.group.threadOpener);
+ if (opener) {
+ laneUserId = encodeLaneUserId(chatId, opener.threadId);
+ outbound.pushReplyAnchor(laneUserId, opener.messageId);
+ // 上下文取数 lane 与路由 lane 分离: 新话题是空的, 群历史前缀仍按
+ // 触发时所在的群主流拉取(「总结上面」等依赖上文的消息才能拿到
+ // 群主流历史), 由 host adapter 消费(IMMessageEvent.groupContextLane)。
+ groupContextLane = { chatId, threadId: '' };
+ } else {
+ laneUserId = encodeLaneUserId(chatId, null);
+ outbound.pushReplyAnchor(laneUserId, messageId);
+ }
+ }
}
// Emit raw fields — orchestrator decides how to render unsupported (it owns
@@ -704,6 +722,7 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): P
speaker: { id: senderOpenId, name: '', isOwner: true },
}
: {}),
+ ...(groupContextLane ? { groupContextLane } : {}),
attachments,
unsupported,
raw: data,
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index efa8828684..91f7b6bcb7 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -233,6 +233,13 @@ export interface IMMessageEvent {
};
/** Channel-specific raw event for debug. */
raw?: unknown;
+ /**
+ * 群历史上下文的取数 lane, 与路由 lane(senderId)分离。仅 feishu 群主流 @
+ * 开新话题时设置: 出站路由进新话题 lane, 但上下文前缀仍按触发时所在 lane
+ * (群主流, threadId='')拉取 — 新话题是空的, 按它过滤会丢掉「总结上面」等
+ * 依赖的群主流上文。其它场景/渠道恒 undefined(上下文按 senderId lane 取)。
+ */
+ groupContextLane?: { chatId: string; threadId: string };
}
export interface IMCardActionEvent {