Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): 开话题开场白即流式卡 + 权限报错文案 + 私聊授权卡指路
Lizi42e511cd73f0
diff --git a/apps/desktop/src/main/im/feishu/uiText.ts b/apps/desktop/src/main/im/feishu/uiText.tsindex 723559f5ad..4de2316292 100644--- a/apps/desktop/src/main/im/feishu/uiText.ts+++ b/apps/desktop/src/main/im/feishu/uiText.ts@@ -88,6 +88,15 @@ export const ui = {`其它部分收到啦,正在处理~`,},+ // ── pre-dispatch 失败细分文案 ──────────────────────────────────────────────+ error: {+ agentUnsupported:+ '🤔 当前选择的 Agent 在这个渠道需要逐条权限确认,暂时上不了场,换一个 Agent 再试~',+ permissionModeUnsupported:+ '⚠️ 群/话题会话不能用「完全访问」权限档 — 群上下文里有成员可控的内容,必须保留操作确认。\n' ++ '发 /permission 把本会话切回「自动审批」再试~',+ },+// ── card text (sent via @cindy/im InteractiveCardSpec) ──────────────────────cards: {permission: {@@ -96,6 +105,8 @@ export const ui = {btnAllowOnce: '✅ 仅本次允许',btnAllowAlways: '✅ 总是允许',btnDeny: '❌ 拒绝',+ /** 授权卡转投 owner 私聊后, 在原群/话题里留的指路提示。 */+ dmRoutedNotice: '🔐 这个操作需要你确认 — 授权卡片已经发到你的私聊,去那里点一下继续~',resolvedAllowOnce: '✅ 已允许(仅本次)',resolvedAllowAlways: '✅ 已允许(这个工具以后都放行)',resolvedDeny: '❌ 已拒绝',diff --git a/apps/desktop/src/main/im/shared/fbotTitle.ts b/apps/desktop/src/main/im/shared/fbotTitle.tsindex 3de1b54107..5b9c2fca2c 100644--- a/apps/desktop/src/main/im/shared/fbotTitle.ts+++ b/apps/desktop/src/main/im/shared/fbotTitle.ts@@ -57,13 +57,39 @@ export async function generateAndPersistFbotTitle(return title;}-/** 只生成标题文本(不落库) — 供渠道自定义拼装(飞书话题标题)复用 oneshot 通道。 */+/**+ * 只生成标题文本(不落库) — 供渠道自定义拼装(飞书话题标题)复用 oneshot 通道。+ * 标题 oneshot 失败(无 title target / 模型输出校验不过)时, 走 utility 链兜底+ * 再试一次 — 标题是展示层, 失败不阻塞, 但兜底能把 [飞书·话题] 0f9b9b 这类+ * 默认名救回正式话题名。+ */export async function generateImSessionTitleText(sessionId: string,seedText: string,): Promise<string | null> {const generated = (await generateMakerSessionTitle(seedText, 'claude-code', sessionId))?.trim();- return generated || null;+ if (generated) return generated;+ try {+ // 动态 import 保持本模块的静态依赖链不继续膨胀(cindySlot 同款)。+ const [{ requestUtilityText }, { getMaker }] = await Promise.all([+ import('../../utility-model/oneShotCandidates.js'),+ import('../../maker-host/index.js'),+ ]);+ const r = await requestUtilityText(+ getMaker(),+ `给下面这条消息生成一个不超过 12 个字的会话标题, 只输出标题本身:\n\n${seedText+ .trim()+ .slice(0, 300)}`,+ { maxTokens: 24, timeoutMs: 12_000, reasoningEffort: 'minimal' },+ );+ if (r.ok) {+ const text = r.text.trim().replace(/^["'「『]+|["'」』]+$/g, '').slice(0, 40);+ if (text) return text;+ }+ } catch {+ /* swallow — 兜底失败保持原样 */+ }+ return null;}/** 落库 + 广播一个已拼装好的标题(渠道 composeGeneratedTitle 的产物)。 */diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 0e59d12bb5..973a2ea5d3 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -1606,6 +1606,17 @@ export function createTurnRunner(},req.kind === 'permission' ? { toolName: req.toolName } : undefined,);+ // 授权卡已转投 owner 私聊 — 原 lane 留指路提示(与 handleInteractionFor 同款)。+ if (req.kind === 'permission' && adapter.ui.cards.permission.dmRoutedNotice) {+ try {+ await im.sendText(userId, adapter.ui.cards.permission.dmRoutedNotice, {+ threadTs: scopeKey,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ log.warn(`dm routed notice send failed (non-fatal): ${msg}`);+ }+ }} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.error(`publishMigrated registerPendingExternal failed: ${msg}`);@@ -2329,7 +2340,13 @@ export function createTurnRunner(await completeTurnCallbackAfterAck(failure.turn);if (failure.turn.queueMode === 'internal') {try {- const message = `❌ 启动 agent 失败:${failure.reason}`;+ // 群轮次强确认策略与「完全访问」档互斥(maker fail-closed 拒绝) — 给+ // 用户能看懂的说法并指路 /permission, 而不是裸抛策略错误码。+ const policyUnsupported = failure.reason.startsWith('TURN_PERMISSION_POLICY_UNSUPPORTED');+ const message =+ policyUnsupported && adapter.ui.error?.permissionModeUnsupported+ ? adapter.ui.error.permissionModeUnsupported+ : `❌ 启动 agent 失败:${failure.reason}`;if (output.kind === 'chunked-text' &&failure.turn.chunkedReplyBegun@@ -2909,6 +2926,18 @@ export function createTurnRunner(// build permissionUpdates when the user picks 'allow:always'.req.kind === 'permission' ? { toolName: req.toolName } : undefined,);+ // 授权卡已转投 owner 私聊 — 在原群/话题 lane 留一句指路, 否则用户+ // 不知道卡片去了哪、也不知道去哪点。+ if (req.kind === 'permission' && adapter.ui.cards.permission.dmRoutedNotice) {+ try {+ await im.sendText(userId, adapter.ui.cards.permission.dmRoutedNotice, {+ threadTs: scopeKey,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ log.warn(`dm routed notice send failed (non-fatal): ${msg}`);+ }+ }return decision;} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.tsindex 0c881e0012..a1de043a7a 100644--- a/apps/desktop/src/main/im/shared/types.ts+++ b/apps/desktop/src/main/im/shared/types.ts@@ -303,6 +303,11 @@ export interface ImUiTextPack {resolvedAllowOnce: string;resolvedAllowAlways: string;resolvedDeny: string;+ /**+ * 授权卡转投 owner 私聊(deliverToOwnerDm)后, 在原群/话题 lane 里发的+ * 指路提示 — 否则群里的人不知道卡片去了哪。缺省不发。+ */+ dmRoutedNotice?: string;};ask: {title: (header: string) => string;diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.tsindex 20f1f0e924..a2e288c8e4 100644--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts@@ -160,13 +160,13 @@ 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', '开个话题');+ it('openThread replies with a patchable card + reply_in_thread + uuid, 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',+ msg_type: 'interactive',reply_in_thread: true,uuid: 'om_root1',}),@@ -176,8 +176,8 @@ describe('feishu outbound lane routing', () => {});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', '开个话题');+ 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 — 飞书重投同一条 @ 事件不会开出多个话题。@@ -189,7 +189,7 @@ describe('feishu outbound lane routing', () => {larkMocks.getMessage.mockResolvedValueOnce({data: { items: [{ thread_id: 'omt_recovered' }] },});- const res = await outbound.openThread('om_root3', '开个话题');+ 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' },@@ -200,7 +200,7 @@ describe('feishu outbound lane routing', () => {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();+ await expect(outbound.openThread('om_root4')).resolves.toBeNull();// 开场白已发出但拿不到话题 id: 撤回它再降级, 不让「回复都在里面」误导。expect(larkMocks.deleteMessage).toHaveBeenCalledWith({path: { message_id: 'om_replied' },@@ -210,7 +210,7 @@ describe('feishu outbound lane routing', () => {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();+ await expect(outbound.openThread('om_root5')).resolves.toBeNull();expect(larkMocks.deleteMessage).toHaveBeenCalledWith({path: { message_id: 'om_replied' },});@@ -218,7 +218,7 @@ describe('feishu outbound lane routing', () => {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();+ await expect(outbound.openThread('om_root6')).resolves.toBeNull();expect(larkMocks.deleteMessage).not.toHaveBeenCalled();});diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.tsindex 97ee5484d5..994324fbf9 100644--- a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts@@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({sendFile: vi.fn(),sendText: vi.fn(),uploadImage: vi.fn(),+ // 默认无 patchable opener — 走新建流式卡路径+ claimPatchableOpener: vi.fn(() => null),}));vi.mock('../outbound.js', () => mocks);diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.tsindex 0510b7e5a0..b7f0d63227 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroup.test.ts@@ -25,6 +25,7 @@ const mocks = {}),),pushReplyAnchor: vi.fn(),+ pushPatchableOpener: vi.fn(),firstAllowed: vi.fn<() => string | null>(() => null),readOwnerOpenId: vi.fn<() => string | null>(() => null),clearOwner: vi.fn(),@@ -71,6 +72,7 @@ vi.doMock('../outbound.js', () => ({replyText: mocks.replyText,openThread: mocks.openThread,pushReplyAnchor: mocks.pushReplyAnchor,+ pushPatchableOpener: mocks.pushPatchableOpener,}));vi.doMock('../ownerGuard.js', () => ({@@ -205,7 +207,7 @@ describe('feishu group inbound gate', () => {const events = collectEvents();await mocks.eventHandlers['im.message.receive_v1']!(groupMessage({}));- expect(mocks.openThread).toHaveBeenCalledWith('om_msg1', expect.any(String));+ expect(mocks.openThread).toHaveBeenCalledWith('om_msg1');expect(events).toHaveLength(1);const event = events[0]!;expect(event.senderId).toBe('g/oc_chat1/omt_new');@@ -214,6 +216,8 @@ describe('feishu group inbound gate', () => {expect(event.speaker).toEqual({ id: OWNER, name: '', isOwner: true });// 锚点是开场白消息(话题内合法锚点), 不是触发消息。expect(mocks.pushReplyAnchor).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');+ // 开场白卡登记为可补丁锚点 — 本轮流式卡直接 patch 它, 不发占位消息。+ expect(mocks.pushPatchableOpener).toHaveBeenCalledWith('g/oc_chat1/omt_new', 'om_opener');// 路由进新话题 lane, 但上下文取数 lane 仍是群主流(新话题是空的)。expect(event.groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });});diff --git a/packages/lizi-im/src/feishu/messages.ts b/packages/lizi-im/src/feishu/messages.tsindex f52b5772fa..3021b86bee 100644--- a/packages/lizi-im/src/feishu/messages.ts+++ b/packages/lizi-im/src/feishu/messages.ts@@ -20,11 +20,6 @@ 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 rawdiff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex ee661a70dc..45c89713b1 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -23,11 +23,12 @@ import path from 'node:path';import * as Lark from '@larksuiteoapi/node-sdk';import { getLog } from './moduleScope.js';-import { buildInteractiveCardV1 } from './cards.js';+import { buildInteractiveCardV1, buildMarkdownCardV2 } from './cards.js';import { decodeLaneUserId } from './codec.js';import * as ownerGuard from './ownerGuard.js';import { parseIncoming } from './incomingContent.js';import type { AttachmentRef } from './incomingContent.js';+import { messages as transportMessages } from './messages.js';import type { InteractiveCardSpec, SendFileResult } from '../types.js';import type { BotCredentials } from './internal-types.js';@@ -79,6 +80,35 @@ export function pushReplyAnchor(laneUserId: string, messageId: string): void {laneAnchors.set(laneUserId, state);}+// ── patchable opener (开话题开场白卡 = 本轮流式卡) ──────────────────────────+// 群主流 @ 开话题时, 开场白是一张「思考中」占位卡; 本轮流式卡不再新建一条+// 回复, 而是直接 patch 这张卡 — 话题里第一条可见内容就是答案。lane → opener+// 卡的映射由 wsClient 在 openThread 成功后登记, streamingText.start 认领。++const patchableOpeners = new Map<string, string>();++export function pushPatchableOpener(laneUserId: string, messageId: string): void {+ patchableOpeners.set(laneUserId, messageId);+}++/**+ * 认领本 lane 的开场白卡: 存在则把它推进为已持有锚点(后续 reply 挂它, 仍落+ * 在话题内)并返回消息 id, streamingText.start 拿它直接 patch; 不存在(开话题+ * 失败的降级群 lane / 话题内 @)返回 null, 走新建流式卡的老路。+ */+export function claimPatchableOpener(laneUserId: string): string | null {+ const openerId = patchableOpeners.get(laneUserId);+ if (!openerId) return null;+ patchableOpeners.delete(laneUserId);+ const state = laneAnchors.get(laneUserId) ?? { queue: [], held: null, quotedHeld: false };+ // 锚点队列头正常就是这张开场白卡; 对不上说明顺序被破坏, 保守起见仍保留队列。+ if (state.queue[0] === openerId) state.queue.shift();+ state.held = openerId;+ state.quotedHeld = true;+ laneAnchors.set(laneUserId, state);+ return openerId;+}+type SendTarget =| { kind: 'open_id'; id: string }| { kind: 'chat_id'; id: string }@@ -224,40 +254,38 @@ function pruneOpenThreadDedup(): void {}/**- * 以 reply_in_thread 回复触发消息, 用它作为根开一个新话题。返回开场白消息- * id + 新话题 thread_id(话题内合法锚点)。同一触发消息并发/重复调用共享同- * 一次开话题 — 防飞书重投事件开出多个话题(含进程重启: uuid 走服务端去重)。+ * 以 reply_in_thread 回复触发消息, 用它作为根开一个新话题。开场白**就是+ * 本轮流式卡**: 发一张「思考中」占位卡片(message 可被 patch 升级成正文),+ * 之后流式卡直接 patch 它 — 话题里不会多出一条「开个话题聊这条」的占位+ * 消息, 第一条可见内容就是答案本身(streamingText.start 经+ * claimPatchableOpener 认领)。返回开场白卡 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> {+export function openThread(replyToMessageId: 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);+ const promise = doOpenThread(replyToMessageId);openThreadByTrigger.set(replyToMessageId, { ts: now, promise });pruneOpenThreadDedup();return promise;}-async function doOpenThread(- replyToMessageId: string,- text: string,-): Promise<OpenThreadResult | null> {+async function doOpenThread(replyToMessageId: 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',+ content: JSON.stringify(buildMarkdownCardV2(transportMessages.streaming.randomThinking())),+ msg_type: 'interactive',reply_in_thread: true,// 服务端幂等键: 同一触发消息重复开话题(重投事件、进程重启后重放)时,// 飞书按 uuid 去重(1 小时内同 uuid 至多发一条, 重复调用返回原消息diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.tsindex ffbc538434..bafdc02946 100644--- a/packages/lizi-im/src/feishu/streamingText.ts+++ b/packages/lizi-im/src/feishu/streamingText.ts@@ -24,7 +24,14 @@* `[name](xdt-file:///abs/path)`).*/-import { sendCardRaw, patchCardRaw, uploadImage, sendFile, sendText } from './outbound.js';+import {+ sendCardRaw,+ patchCardRaw,+ uploadImage,+ sendFile,+ sendText,+ claimPatchableOpener,+} from './outbound.js';import { buildMarkdownCardV2, buildMixedMarkdownCardV2 } from './cards.js';import { getLog } from './moduleScope.js';import { messages as transportMessages } from './messages.js';@@ -338,6 +345,10 @@ export async function start(openId: string,initial: string = transportMessages.streaming.randomThinking(),): Promise<StreamingTextHandle> {+ // 群主流 @ 开话题时, 开场白卡就是本轮流式卡(openThread 已用它开好话题) —+ // 认领后直接 patch, 不再新建一条「开个话题」占位回复。+ const claimed = claimPatchableOpener(openId);+ if (claimed) return new FeishuStreamingTextHandle(claimed, openId, initial);const { messageId } = await sendCardRaw(openId, buildMarkdownCardV2(initial));return new FeishuStreamingTextHandle(messageId, openId, initial);}diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex cc5de06482..3049498704 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -691,10 +691,13 @@ async function handleIncomingMessage(botAppId: string, data: RawMessageEvent): PlaneUserId = encodeLaneUserId(chatId, incomingThreadId);outbound.pushReplyAnchor(laneUserId, messageId);} else {- const opener = await outbound.openThread(messageId, transportMessages.group.threadOpener);+ 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)。