Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): Telegram 群里的授权卡改投宿主私聊,群里补一行等待状态 (#1550)
Chris Zhang4b735a204fbb
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex 81af718cbe..df24ec651a 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -1611,6 +1611,233 @@ describe('交互卡链路(interaction listener 覆盖)', () => {};}+ it('等授权期间过程区挂一行状态, 决策回流后摘掉', async () => {+ vi.useFakeTimers();+ try {+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>+ makeInteractiveSession(opts.id ?? 'sess-x'),+ );+ const emitted: string[] = [];+ const cards: Array<{ interactionId: string }> = [];+ const runner = createMakerHookSessionRunner({ log });+ const p = runner.run(+ baseReq({+ onProgress: (t: string) => emitted.push(t),+ onInteraction: (card: { interactionId: string }) => void cards.push(card),+ }),+ );+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(0);++ const listener = h.interactionListeners.get('sess-new')!;+ const decisionPromise = listener({+ kind: 'ask_user_question',+ requestId: 'int-notice',+ questions: [{ question: '继续吗?', options: [{ label: '继续' }] }],+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(cards).toHaveLength(1);+ // 卡片发出的同时过程区出现状态行: 挂起期间没有任何 agent 事件, 渠道那条消息会+ // 彻底静止, 而卡片可能根本不在这个会话里(群里的授权卡改投宿主私聊)。+ // 它只改已经在发的那条快照, 不新增任何渠道消息。+ // **文案按交互类型分**: 这是问答, 说"等待授权"就把它说成了权限请求。+ expect(emitted.at(-1)).toContain('等待回答');+ expect(emitted.at(-1)).not.toContain('等待授权');++ const { resolveHookInteraction } = await import('../interactions.js');+ expect(resolveHookInteraction('int-notice', 'ask:0')).toBe(true);+ await decisionPromise;+ // 授权通过、agent 继续干活: 后续快照不得再带那行状态(否则它会一直挂在过程区+ // 顶上, 与 review #844 里"重试提示留在终稿正上方"是同一个坑)。+ h.eventCbs.get('sess-new')!({+ type: 'tool_use',+ data: { toolUseId: 'after-1', toolName: 'Read', input: { file_path: '/tmp/a.ts' } },+ });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('读取 a.ts');+ expect(emitted.at(-1)).not.toContain('等待授权');++ h.eventCbs.get('sess-new')!({ type: 'done', data: null });+ await p;+ } finally {+ vi.useRealTimers();+ }+ });++ it('过程区状态行按交互类型分: 授权/问答/计划审阅各自措辞', async () => {+ vi.useFakeTimers();+ try {+ for (const [request, expected] of [+ [+ {+ kind: 'permission' as const,+ requestId: 'int-perm',+ toolName: 'file_change',+ input: {},+ },+ '等待授权',+ ],+ [+ {+ kind: 'plan_review' as const,+ requestId: 'int-plan',+ plan: '第一步…',+ },+ '等待审阅',+ ],+ ] as const) {+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>+ makeInteractiveSession(opts.id ?? 'sess-x'),+ );+ const emitted: string[] = [];+ const runner = createMakerHookSessionRunner({ log });+ const p = runner.run(+ baseReq({+ onProgress: (t: string) => emitted.push(t),+ onInteraction: () => {},+ }),+ );+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(0);+ const listener = h.interactionListeners.get('sess-new')!;+ void listener(request as never);+ await vi.advanceTimersByTimeAsync(0);+ expect(emitted.at(-1)).toContain(expected);+ h.eventCbs.get('sess-new')!({ type: 'done', data: null });+ await p.catch(() => undefined);+ }+ } finally {+ vi.useRealTimers();+ }+ });++ it('待决交互期间的正常进展事件不得抹掉等待提示', async () => {+ vi.useFakeTimers();+ try {+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>+ makeInteractiveSession(opts.id ?? 'sess-x'),+ );+ const emitted: string[] = [];+ const runner = createMakerHookSessionRunner({ log });+ const p = runner.run(+ baseReq({+ onProgress: (t: string) => emitted.push(t),+ onInteraction: () => {},+ }),+ );+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(0);++ const listener = h.interactionListeners.get('sess-new')!;+ const pending = listener({+ kind: 'permission',+ requestId: 'int-progress',+ toolName: 'file_change',+ input: {},+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(emitted.at(-1)).toContain('等待授权');++ // 挂起期间 agent 的其它子任务照样吐事件。这些走的是 clearNotice ——+ // 若等待提示与瞬态 notice 共用一个字段, 每一条都会把它抹掉, 于是剩下的+ // 授权最长要等 30 分钟而过程区一个字都不提。+ const emit = h.eventCbs.get('sess-new')!;+ emit({ type: 'thinking', data: { blockId: 'b1', text: '再查一处引用' } });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('等待授权');++ emit({+ type: 'tool_use',+ data: { toolUseId: 'bg-1', toolName: 'Read', input: { file_path: '/tmp/bg.ts' } },+ });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('读取 bg.ts');+ expect(emitted.at(-1)).toContain('等待授权');++ emit({ type: 'text', data: { text: '我先读了这个文件' } });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('等待授权');++ // 收口后才摘掉+ const { resolveHookInteraction } = await import('../interactions.js');+ expect(resolveHookInteraction('int-progress', 'perm:allow')).toBe(true);+ await pending;+ emit({+ type: 'tool_use',+ data: { toolUseId: 'bg-2', toolName: 'Read', input: { file_path: '/tmp/after.ts' } },+ });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('读取 after.ts');+ expect(emitted.at(-1)).not.toContain('等待授权');++ emit({ type: 'done', data: null });+ await p;+ } finally {+ vi.useRealTimers();+ }+ });++ it('并发交互: 其中一个收口不摘掉状态行, 最后一个结束才摘', async () => {+ vi.useFakeTimers();+ try {+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>+ makeInteractiveSession(opts.id ?? 'sess-x'),+ );+ const emitted: string[] = [];+ const runner = createMakerHookSessionRunner({ log });+ const p = runner.run(+ baseReq({+ onProgress: (t: string) => emitted.push(t),+ onInteraction: () => {},+ }),+ );+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(0);++ // agent 并行发起两个交互: 各自独立挂起, 共用过程区那一行状态。**两者措辞不同**,+ // 这样"回落到仍在等的那条"表现为文字变化 —— 用 tool_use 逼快照反而不行:+ // 真实进展本身就会作废状态行(clearNotice), 那条断言对两种实现都成立。+ const listener = h.interactionListeners.get('sess-new')!;+ const first = listener({+ kind: 'permission',+ requestId: 'int-par-1',+ toolName: 'file_change',+ input: {},+ });+ const second = listener({+ kind: 'ask_user_question',+ requestId: 'int-par-2',+ questions: [{ question: '继续吗?', options: [{ label: '继续' }] }],+ });+ await vi.advanceTimersByTimeAsync(0);+ // 挂起时新卡片覆盖状态行 —— 最新那条(问答)在上。+ expect(emitted.at(-1)).toContain('等待回答');++ const { resolveHookInteraction } = await import('../interactions.js');+ expect(resolveHookInteraction('int-par-2', 'ask:0')).toBe(true);+ await second;+ await vi.advanceTimersByTimeAsync(1500);+ // 权限请求还在等 —— 状态行必须回落到它, 不能整行摘掉: 摘了群里的进度消息又变回+ // 静止, 而剩下那个交互最长要等 30 分钟。+ expect(emitted.at(-1)).toContain('等待授权');++ expect(resolveHookInteraction('int-par-1', 'perm:allow')).toBe(true);+ await first;+ h.eventCbs.get('sess-new')!({+ type: 'tool_use',+ data: { toolUseId: 'after-par', toolName: 'Read', input: { file_path: '/tmp/b.ts' } },+ });+ await vi.advanceTimersByTimeAsync(1500);+ expect(emitted.at(-1)).toContain('读取 b.ts');+ expect(emitted.at(-1)).not.toContain('等待');++ h.eventCbs.get('sess-new')!({ type: 'done', data: null });+ await p;+ } finally {+ vi.useRealTimers();+ }+ });+it('ask 请求 -> 中央 Router 发卡 -> 按钮决策回流 resolve; 收口后释放 route', async () => {fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>makeInteractiveSession(opts.id ?? 'sess-x'),diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 573d62b327..1d3d2f84f5 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -248,6 +248,25 @@ function isRenderableImageUrl(u: string): boolean {return u.startsWith('xdt-image://') || u.startsWith('cindy-media://');}+/**+ * agent 挂起等用户时挂在过程区的状态行, **按交互类型分** —— 都写"等待授权"会把+ * 问答与计划审阅说成权限请求(review 指出)。+ *+ * **刻意不说卡片去了哪**: 投递位置由 hook server 决定(Telegram 群里的授权卡自+ * 2026-08 起改投宿主私聊), 客户端不知道对端版本, 写"已发到私聊"可能是假的。+ */+const AWAITING_INTERACTION_NOTICE: Record<string, string> = {+ permission: '等待授权 · 需要你确认',+ ask_user_question: '等待回答 · 需要你选择',+ plan_review: '等待审阅 · 需要你确认计划',+};+/** 未知 kind(将来新增类型)不编造语义, 只说在等你。 */+const AWAITING_INTERACTION_FALLBACK = '等待你的确认';++function awaitingInteractionNotice(kind: string): string {+ return AWAITING_INTERACTION_NOTICE[kind] ?? AWAITING_INTERACTION_FALLBACK;+}+/** 兜底账本条目是否图片(hook 本期只外发图片):cindy-media 地址按扩展名判。 */const PRODUCED_IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp)$/i;@@ -632,6 +651,12 @@ export function createMakerHookSessionRunner(deps: {// listener 由中央 InteractionRouter 持有;这里只准备本 turn 的 handler,// 真正的 route 在 beforeProviderStart 屏障内登记。const ownInteractionIds = new Set<string>();+ /**+ * 待决交互各自的过程区状态行(requestId → notice, 插入序)。agent 可以并行发起+ * 多个权限请求, 任一个先收口都不能把共享的那一行清掉 —— 否则群里的进度消息又+ * 变回静止, 而其余交互还要等最长 30 分钟。收口后回落到剩余里最新那条。+ */+ const pendingInteractionNotices = new Map<string, string>();let interactionRouteLease: InteractionRouteLease | null = null;const headlessTurn = {closed: false,@@ -643,6 +668,9 @@ export function createMakerHookSessionRunner(deps: {if (headlessTurn.closed || headlessTurn.release) return;headlessTurn.release = beginHeadlessGhostSetupTurn(session.id);};+ // 前向引用: 交互回调只在 turn 跑起来之后才可能被调用, 那时 observer 已就位。+ // 用它给过程区挂「等待授权」, 不新增任何渠道消息。+ let activeObserver: HookTurnObserver | null = null;const handleHookInteraction: InteractionHandler = async (ireq) => {if (req.onInteraction) {const sendCard = req.onInteraction;@@ -670,13 +698,25 @@ export function createMakerHookSessionRunner(deps: {}ownInteractionIds.add(ireq.requestId);sendCard({ interactionId: ireq.requestId, ...composed.card });- const decision = await registerHookInteraction({- interactionId: ireq.requestId,- composed,- onFallback: (reason) => sendCancel?.(ireq.requestId, reason),- });- ownInteractionIds.delete(ireq.requestId);- return decision;+ // 等授权期间没有任何 agent 事件 —— 渠道那条进度消息会彻底静止, 而卡片+ // 可能根本不在这个会话里(Telegram 群里的授权卡改投宿主私聊)。挂一行状态,+ // 收口后摘掉; 全程只改已经在发的那条快照, 不新增群消息。+ pendingInteractionNotices.set(ireq.requestId, awaitingInteractionNotice(ireq.kind));+ activeObserver?.setNotice(awaitingInteractionNotice(ireq.kind));+ try {+ const decision = await registerHookInteraction({+ interactionId: ireq.requestId,+ composed,+ onFallback: (reason) => sendCancel?.(ireq.requestId, reason),+ });+ ownInteractionIds.delete(ireq.requestId);+ return decision;+ } finally {+ pendingInteractionNotices.delete(ireq.requestId);+ // 仍有交互待决时保留状态行, 只有最后一个收口才摘掉。回落到**剩余里最新**+ // 那条 —— 与挂起时"新卡片覆盖状态行"同序(Map 保持插入序)。+ activeObserver?.setNotice([...pendingInteractionNotices.values()].at(-1) ?? null);+ }}if (ireq.kind === 'ask_user_question') {return { kind: 'ask_user_question', answers: {} };@@ -706,6 +746,8 @@ export function createMakerHookSessionRunner(deps: {cancelHookInteraction(iid, '任务已结束, 此交互已失效');}ownInteractionIds.clear();+ // 收口后不再有待决交互: 先清空, 各 handler 的 finally 随后只会摘掉状态行。+ pendingInteractionNotices.clear();};// 新建会话广播 -> 侧边栏实时出现(复用/接管的会话本来就在列表里, 不用发)if (req.isNew) {@@ -754,6 +796,7 @@ export function createMakerHookSessionRunner(deps: {onSilentStopSettled,log,});+ activeObserver = observer;// origin 标注见文件头注释(闭合联合下的 v1 取舍)。scheduleId 用稳定的// hook 连接标识 —— renderer/IM 只拿它做展示与分组, 不回查 schedule 表。diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.tsindex a9b75684d1..6340886f49 100644--- a/apps/desktop/src/main/hook-control/turnObserver.ts+++ b/apps/desktop/src/main/hook-control/turnObserver.ts@@ -30,6 +30,7 @@ import {pushToolStep,renderActivity,setActivityNotice,+ setInteractionNotice,} from '../im/shared/turnActivity.js';import { overloadFailureNotice, turnRetryNotice } from '../im/shared/turnRetryNotice.js';@@ -184,6 +185,17 @@ export interface HookTurnObserver {* 最后一条为空白时回退整轮正文: 公开回帖宁可带上过程, 也不能发成空。*/finalSegment(): string;+ /**+ * 在过程区挂 / 摘一行状态说明(渲染成 `> ⏳ …`, 与过载重试同一个位置)。+ *+ * 用途: agent 挂起等用户授权时, 渠道那条消息除了"工作中"什么都不显示 ——+ * 而卡片可能根本不在这个会话里(Telegram 群里的授权卡改投宿主私聊了), 群里+ * 看起来就是彻底静止。**刻意不写卡片去了哪**: 投递位置由 hook server 决定,+ * 客户端不知道对端版本, 说"已发到私聊"可能是假的。+ *+ * null = 摘掉。不新增任何渠道消息, 只改已经在发的那条快照。+ */+ setNotice(notice: string | null): void;}/** 挂上事件监听并开始观察。调用方必须 await finished 或自己 stop()。 */@@ -443,6 +455,16 @@ export function observeHookTurn(stopListening?.();stopListening = undefined;},+ setNotice(notice: string | null): void {+ // 走**独立**的等交互通道, 不是瞬态 notice: 后者会被 pushToolStep /+ // pushThinkingStep / markActivityWriting 的 clearNotice 抹掉, 而挂起期间+ // agent 的其它子任务照样在吐这些事件。+ if (!setInteractionNotice(activity, notice)) return;+ // ticker 让过程区的「第 N 步 · 42s」继续走时间: 等授权期间没有任何 agent+ // 事件, 不续 ticker 那条消息会连耗时都冻住。+ progress?.ensureTicker();+ progress?.schedule();+ },text(): string {return assistantText;},diff --git a/apps/desktop/src/main/im/shared/__tests__/turnActivity.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnActivity.test.tsindex 87441d9551..74b4c9f8c2 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnActivity.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnActivity.test.ts@@ -11,6 +11,7 @@ import {pushToolStep,renderActivity,setActivityNotice,+ setInteractionNotice,} from '../turnActivity';describe('formatToolStep — shared friendly wording', () => {@@ -115,12 +116,32 @@ describe('rolling window and replay de-duplication', () => {expect(activity.recentSteps.some((step) => step.kind === 'thinking')).toBe(false);});+ it('等交互那一行不被正常进展事件清掉(与瞬态 notice 的关键区别)', () => {+ const activity = createTurnActivity(0);+ expect(setInteractionNotice(activity, '等待授权 · 需要你确认')).toBe(true);+ setActivityNotice(activity, '模型服务繁忙,正在自动重试(1/4)…');++ // 挂起期间 agent 的其它子任务照样吐事件: 瞬态 notice 该被清掉, 等待提示必须留着+ pushThinkingStep(activity, { stage: 'final', blockId: 't1', text: '再查一处引用' });+ pushToolStep(activity, 'Read', { file_path: '/x/bg.ts' }, 'bg-1');+ markActivityWriting(activity);+ expect(activity.notice).toBeNull();+ expect(activity.interactionNotice).toBe('等待授权 · 需要你确认');+ expect(renderActivity(activity, 3_000)).toContain('> ⏳ 等待授权 · 需要你确认');++ // 只由交互收口显式摘掉; 重复内容不算变化(同 setActivityNotice 的配额语义)+ expect(setInteractionNotice(activity, '等待授权 · 需要你确认')).toBe(false);+ expect(setInteractionNotice(activity, null)).toBe(true);+ expect(renderActivity(activity, 3_000)).not.toContain('等待授权');+ });+it('keeps replay bookkeeping out of the serializable card state', () => {const activity = createTurnActivity(0);pushThinkingStep(activity, { stage: 'final', blockId: 't1', text: '检查状态' });pushToolStep(activity, 'Read', { file_path: '/repo/a.ts' }, 'read-a');expect(Object.keys(activity).sort()).toEqual([+ 'interactionNotice','notice','recentSteps','startedAt',diff --git a/apps/desktop/src/main/im/shared/turnActivity.ts b/apps/desktop/src/main/im/shared/turnActivity.tsindex 2f2b528b71..b5fcd72350 100644--- a/apps/desktop/src/main/im/shared/turnActivity.ts+++ b/apps/desktop/src/main/im/shared/turnActivity.ts@@ -46,6 +46,18 @@ export interface TurnActivityState {* ErrorBanner「恢复后由后续正常事件自动清除」同口径。*/notice: string | null;+ /**+ * 一行**等用户**状态(等授权 / 等回答 / 等审阅), 与上面的 notice 分开存。+ *+ * 为什么不能共用 notice: notice 的语义是"这一刻卡在哪, 有真实进展就作废", 所以+ * pushToolStep / pushThinkingStep / markActivityWriting 都会 clearNotice。而"在等+ * 你确认"恰恰要在**有进展的时候也留着** —— 权限请求挂起期间 agent 的其它子任务+ * 照样会吐 thinking / tool_use / 正文, 那些事件一到就把提示抹掉, 于是剩下的授权+ * 最长要等 30 分钟而过程区一个字都不提(2026-08-03 review P2)。+ *+ * 只由交互挂起/收口显式设置与清除, 进展事件一律不动它。+ */+ interactionNotice: string | null;}/** Replay/delta bookkeeping stays private and is never serialized with card state. */@@ -70,6 +82,7 @@ export function createTurnActivity(startedAt: number): TurnActivityState {startedAt,writing: false,notice: null,+ interactionNotice: null,};internalStateByActivity.set(activity, {seenKeys: new Set(),@@ -105,6 +118,20 @@ export function setActivityNotice(activity: TurnActivityState, notice: string |return true;}+/**+ * 设置 / 清除"在等你确认"那一行。返回是否真的变了(同 setActivityNotice 的语义)。+ * 与 setActivityNotice 的区别只有一个: 进展事件不会清掉它。+ */+export function setInteractionNotice(+ activity: TurnActivityState,+ notice: string | null,+): boolean {+ const next = notice && notice.trim().length > 0 ? truncate(notice, STEP_LABEL_MAX) : null;+ if (activity.interactionNotice === next) return false;+ activity.interactionNotice = next;+ return true;+}+/** 有真实进展 = 上一条状态说明(如"正在重试")已过期。 */function clearNotice(activity: TurnActivityState): void {activity.notice = null;@@ -208,7 +235,8 @@ function formatElapsed(ms: number): string {* 此时省掉"N 项"段 —— 报"0 项"没有信息量。*/export function renderActivity(activity: TurnActivityState, now: number): string {- if (activity.totalSteps === 0 && activity.notice === null) return '';+ if (activity.totalSteps === 0 && activity.notice === null && activity.interactionNotice === null)+ return '';const elapsed = formatElapsed(now - activity.startedAt);const lines = [activity.totalSteps > 0@@ -218,11 +246,17 @@ export function renderActivity(activity: TurnActivityState, now: number): stringconst last = activity.recentSteps.length - 1;activity.recentSteps.forEach((step, index) => {// 有状态说明时它才是"当前在做的事", 已完成的工作项一律收成 ✓。- const isTail = index === last && !activity.writing && activity.notice === null;+ const isTail =+ index === last &&+ !activity.writing &&+ activity.notice === null &&+ activity.interactionNotice === null;const marker = isTail ? '▸' : '✓';const prefix = step.kind === 'thinking' ? '✦ ' : '';lines.push(`> ${marker} ${prefix}${step.label}`);});if (activity.notice !== null) lines.push(`> ⏳ ${activity.notice}`);+ // 等用户那一行放最后: 它是此刻唯一需要用户动手的事。+ if (activity.interactionNotice !== null) lines.push(`> ⏳ ${activity.interactionNotice}`);return lines.join('\n');}diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex b0719eb468..f54ab77fa1 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -33,6 +33,16 @@import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';+/**+ * 群里的授权卡改投宿主私聊时, 加在卡片正文顶部的说明。+ *+ * 放在这一层(desktop main)而不是 @cindy/im: 传输层没有 locale、也不该持有产品措辞。+ * 与个人 bot 其它 bot 侧文案(im/telegram/uiText.ts)同口径 —— 那一整套目前是单语中文,+ * 见该文件头部说明; 若要做多语言应连同整套一起改, 不在这一句上开特例。+ */+const GROUP_APPROVAL_OWNER_DM_NOTE =+ '🔐 群聊里的任务需要你授权。授权卡不会发到群里,在这里确认即可。';+import { eq } from 'drizzle-orm';import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import { getMaker } from '../../maker-host';@@ -1373,9 +1383,26 @@ export function createTurnRunner(return;}+ const migratedSourceMessageId =+ sessionStates.get(localSessionId)?.queue[0]?.userMessageId ?? undefined;let messageId: string;try {- const result = await richIm.sendInteractiveCard(userId, spec, { threadTs: scopeKey });+ const result = await richIm.sendInteractiveCard(userId, spec, {+ threadTs: scopeKey,+ // **只有授权卡**转宿主私聊: 群里的授权卡消不掉且只有宿主能答。问答 / 计划审阅+ // 留在原 lane(它们在群里可见是合理的), 命令卡与会话选择卡更不能转 —— 那会让+ // 回调落到私聊锁上。+ ...(req.kind === 'permission'+ ? {+ deliverToOwnerDm: true,+ ownerDmNote: GROUP_APPROVAL_OWNER_DM_NOTE,+ // 迁移路径同样按业务 turn 取来源消息(可能没有进行中的 turn)。+ ...(migratedSourceMessageId !== undefined+ ? { ownerDmSourceMessageId: migratedSourceMessageId }+ : {}),+ }+ : {}),+ });messageId = result.messageId;} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -2577,11 +2604,25 @@ export function createTurnRunner(// (eventually resolved) interaction card — not into the pre-existing card// that sits above it. Without this, the user sees the conclusion stream// into a card chronologically older than the "✅ 已选择" patch.+ // 深链身份必须在 finalizeActiveStream **之后**照样可用: 它取自本 turn 的+ // userMessageId(业务事实), 与流式 handle 生命周期无关 —— 传输层猜不出这个。+ const ownerDmSourceMessageId =+ sessionStates.get(localSessionId)?.queue[0]?.userMessageId ?? undefined;await finalizeActiveStream(localSessionId);let messageId: string;try {- const result = await output.im.sendInteractiveCard(userId, spec, { threadTs: scopeKey });+ const result = await output.im.sendInteractiveCard(userId, spec, {+ threadTs: scopeKey,+ // 同上: 只有 permission 卡转宿主私聊+ ...(req.kind === 'permission'+ ? {+ deliverToOwnerDm: true,+ ownerDmNote: GROUP_APPROVAL_OWNER_DM_NOTE,+ ...(ownerDmSourceMessageId !== undefined ? { ownerDmSourceMessageId } : {}),+ }+ : {}),+ });messageId = result.messageId;} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.tsindex 410103e139..c05620d020 100644--- a/packages/lizi-im/src/channelIM.ts+++ b/packages/lizi-im/src/channelIM.ts@@ -85,7 +85,33 @@ export interface RichChannelIM extends TextChannelIM {sendInteractiveCard(userId: string,spec: InteractiveCardSpec,- opts?: { threadTs?: string },+ opts?: {+ threadTs?: string;+ /**+ * **只有授权类(permission)卡片**可以传 true: 群 lane 里把卡片改投宿主私聊 ——+ * 群里的授权卡消不掉, 而且只有宿主本人能回答它。+ *+ * 命令卡 / 会话选择卡(`/ctr` 等)**绝不能传**: 它们的回调要落在原群 lane+ * (exitControl 释放的是那把群锁), 投到私聊会让锁与卡片对不上。+ * 渠道不支持该语义时忽略即可(按原 lane 投递), 不要吞掉卡片。+ */+ deliverToOwnerDm?: boolean;+ /**+ * `deliverToOwnerDm` 生效时加在卡片正文顶部的说明。**用户可见文案由调用方给**,+ * 传输层不造文案(它没有 locale, 也不该持有产品措辞)。+ */+ ownerDmNote?: string;+ /**+ * 触发本轮的那条渠道消息 id(本接口的 messageId 形态)。`deliverToOwnerDm` 生效时+ * 用来拼「来源」深链 —— 宿主在私聊里收到的卡片否则看不出是哪个群、哪个问题。+ *+ * **必须由调用方给**: 只有它知道这张卡属于哪一轮业务 turn。传输层能看到的只有+ * 回挂状态与流式 handle 生命周期, 两者都不等于业务轮次 —— 回挂目标在+ * `replyQuoteGroup:'first'` 下发出首条回复就被消耗, 而发卡前调用方会主动收口+ * 流式 handle。不传则不渲染深链(不猜)。+ */+ ownerDmSourceMessageId?: string;+ },): Promise<{ messageId: string }>;/** 原地替换一张已发出的交互卡片(spec 全量覆盖)。 */diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex d9f09acc04..85c9df708a 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -475,6 +475,179 @@ describe('TelegramIM', () => {expect((sends[1].params.reply_parameters as { message_id: number }).message_id).toBe(61);});+ it('群里的授权卡改投宿主私聊: 不落群、带触发消息深链、不吃回挂配额', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([+ groupMessage({ text: '改一下代码', fromId: 111, messageId: 70, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(1));++ await im.sendInteractiveCard(+ events[0].senderId,+ {+ title: '需要授权',+ body: '要修改 src/app.ts 吗?',+ buttons: [{ id: 'allow', label: '允许', type: 'primary' }],+ },+ // 授权卡由调用方点名转私聊, 并把用户可见说明与**本轮触发消息 id** 一起传进来+ // (传输层不造文案, 也不猜这张卡属于哪一轮)+ {+ deliverToOwnerDm: true,+ ownerDmNote: '群聊里的任务需要你授权。',+ ownerDmSourceMessageId: events[0].messageId,+ },+ );+ const card = api.calls.filter((c) => c.method === 'sendMessage').at(-1)!;+ // 群里的授权卡消不掉, 且只有 owner 能回答它 —— 一律投宿主私聊, 群里一条都不发+ expect(card.params.chat_id).toBe(OWNER_ID);+ expect(+ api.calls.some((c) => c.method === 'sendMessage' && c.params.chat_id === '-100200'),+ ).toBe(false);+ // 私聊里看不出是哪个群问的, 所以带触发消息深链(-100 前缀私有超级群)+ expect(String(card.params.text)).toContain('https://t.me/c/200/70');+ // 群里的回挂目标不被卡片消耗: 本轮真正的回答仍然挂回那条提问+ expect(card.params.reply_parameters).toBeUndefined();+ await im.sendText(events[0].senderId, '改完了');+ const answer = api.calls+ .filter((c) => c.method === 'sendMessage' && c.params.chat_id === '-100200')+ .at(-1)!;+ expect(answer.params.reply_parameters).toEqual({+ message_id: 70,+ allow_sending_without_reply: true,+ });+ });++ it('私聊的授权卡照旧落在私聊、正文不加群来源说明', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([privateMessage('needs approval', 111, 71)]);+ await vi.waitFor(() => expect(events).toHaveLength(1));++ await im.sendInteractiveCard(+ events[0].senderId,+ {+ title: 'Approval',+ body: 'Continue?',+ buttons: [{ id: 'yes', label: 'Yes' }],+ },+ { deliverToOwnerDm: true, ownerDmNote: '群聊里的任务需要你授权。' },+ );+ const card = api.calls.filter((c) => c.method === 'sendMessage').at(-1)!;+ expect(card.params.chat_id).toBe(OWNER_ID);+ expect(String(card.params.text)).not.toContain('t.me/c/');+ expect(String(card.params.text)).not.toContain('群聊里的任务需要你授权');+ });++ it('未点名转私聊的卡片(命令卡 / 会话选择卡)留在原群 lane', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([+ groupMessage({ text: '/ctr', fromId: 111, messageId: 72, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(1));++ // 不传 deliverToOwnerDm: 这类卡的回调要落在原群 lane, 转到私聊会让+ // exitControl 释放宿主私聊那把锁而不是原群锁。+ await im.sendInteractiveCard(events[0].senderId, {+ title: '选择要接管的任务',+ body: '挑一个',+ buttons: [{ id: 'sess-1', label: '任务 A' }],+ });+ const card = api.calls.filter((c) => c.method === 'sendMessage').at(-1)!;+ expect(card.params.chat_id).toBe('-100200');+ expect(String(card.params.text)).not.toContain('t.me/c/');+ });++ it('授权卡深链认调用方指定的那一轮, 同 lane 后到的消息不影响它', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ // 群里连发两问 —— 处理中的是 80, 81 已在队列里等下一轮+ api.pushUpdates([+ groupMessage({ text: '第一问', fromId: 111, messageId: 80, mentionBot: true }),+ groupMessage({ text: '第二问', fromId: 111, messageId: 81, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(2));++ await im.sendInteractiveCard(+ events[0].senderId,+ { title: '需要授权', body: '改文件?', buttons: [{ id: 'allow', label: '允许' }] },+ {+ deliverToOwnerDm: true,+ ownerDmNote: '群聊里的任务需要你授权。',+ ownerDmSourceMessageId: events[0].messageId,+ },+ );+ const card = api.calls.filter((c) => c.method === 'sendMessage').at(-1)!;+ expect(String(card.params.text)).toContain('https://t.me/c/200/80');+ expect(String(card.params.text)).not.toContain('/81');+ });++ it('深链只认同群的来源 id: 缺省或跨 chat 一律不渲染链接(不猜, 也不链错群)', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([+ groupMessage({ text: '问题', fromId: 111, messageId: 85, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(1));++ // 不传来源 id: 传输层不得靠回挂状态/流式回合猜, 直接不渲染深链+ await im.sendInteractiveCard(+ events[0].senderId,+ { title: '需要授权', body: '改文件?', buttons: [{ id: 'allow', label: '允许' }] },+ { deliverToOwnerDm: true, ownerDmNote: '群聊里的任务需要你授权。' },+ );+ expect(+ String(api.calls.filter((c) => c.method === 'sendMessage').at(-1)!.params.text),+ ).not.toContain('t.me/c/');++ // 来源 id 属于别的 chat: 链到别的会话比没有链更糟 —— 同样不渲染+ await im.sendInteractiveCard(+ events[0].senderId,+ { title: '需要授权', body: '改文件?', buttons: [{ id: 'allow', label: '允许' }] },+ {+ deliverToOwnerDm: true,+ ownerDmNote: '群聊里的任务需要你授权。',+ ownerDmSourceMessageId: '-100999|85',+ },+ );+ expect(+ String(api.calls.filter((c) => c.method === 'sendMessage').at(-1)!.params.text),+ ).not.toContain('t.me/c/');+ });++ it("授权卡深链在本轮已发过群回复后仍然有效('first' 档会消耗回挂目标)", async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([+ groupMessage({ text: '改一下配置', fromId: 111, messageId: 90, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(1));++ // 正常时序: agent 先流式回一句, 再请求授权。默认 replyQuoteGroup='first' 下这条+ // 群回复会把 turnReplyTargets 消耗掉 —— 深链身份不能借用回挂状态。+ const handle = await im.startStreamingText(events[0].senderId, '我看一下');+ await handle.finalize('先读配置文件');+ await im.sendInteractiveCard(+ events[0].senderId,+ { title: '需要授权', body: '改文件?', buttons: [{ id: 'allow', label: '允许' }] },+ {+ deliverToOwnerDm: true,+ ownerDmNote: '群聊里的任务需要你授权。',+ ownerDmSourceMessageId: events[0].messageId,+ },+ );+ const card = api.calls.filter((c) => c.method === 'sendMessage').at(-1)!;+ expect(card.params.chat_id).toBe('111');+ expect(String(card.params.text)).toContain('https://t.me/c/200/90');+ });+it('私聊出站不回挂 reply', async () => {const events: IMMessageEvent[] = [];im.onMessage((e) => events.push(e));@@ -1486,6 +1659,39 @@ describe('TelegramIM', () => {});});+ it('授权卡转私聊时也停掉原群的 typing loop(否则群里一直显示正在输入)', async () => {+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([+ groupMessage({ text: '改个文件', fromId: 111, messageId: 99, mentionBot: true }),+ ]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ await vi.waitFor(() => {+ expect(+ api.calls.some((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200'),+ ).toBe(true);+ });++ // 卡片投的是宿主私聊 —— callSend 只会停它自己那条 chat 的 typing loop,+ // 群里那条必须由转发分支显式停掉, 否则每 4.5s 继续打一次 sendChatAction。+ await im.sendInteractiveCard(+ events[0].senderId,+ { title: '需要授权', body: '改 src/app.ts?', buttons: [{ id: 'allow', label: '允许' }] },+ { deliverToOwnerDm: true, ownerDmNote: '群聊里的任务需要你授权。' },+ );+ const groupTypingAfterCard = api.calls.filter(+ (c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200',+ ).length;+ // **必须跨过一个 TYPING_REFRESH_MS(4.5s)**: loop 每 4.5s 才刷一次, 只等 100ms 的话+ // 循环还没来得及打下一枪, 断言对「有没有真的停掉」没有判别力(反向验证时会假通过)。+ await new Promise((r) => setTimeout(r, 4_700));+ expect(+ api.calls.filter((c) => c.method === 'sendChatAction' && c.params.chat_id === '-100200')+ .length,+ ).toBe(groupTypingAfterCard);+ });+it('disconnect 清空凭证并回 idle', async () => {await connect();await ctx.handlers.get('telegramBot:disconnect')!();diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.tsindex 266103d70f..9d0c27e1b6 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -57,6 +57,7 @@ import { startTelegramStreaming } from './streamingText.js';const TOKEN_SECRET_KEY = 'telegram-bot-token';const OWNER_USER_ID_SECRET_KEY = 'telegram-owner-user-id';+/** 历史遗留 key(上下线播报机制已移除), disconnect 时顺手清掉。 */const LEGACY_RUNTIME_ACTIVE_SECRET_KEY = 'telegram-bot-runtime-active';/**@@ -127,6 +128,21 @@ function hasNewerTrigger(queue: Array<{ id: string }>, current: string): booleanreturn queue.some((entry) => Number(entry.id) > currentId);}+/**+ * 调用方给的「本轮触发消息」编码 id → 同群的原生 message_id(给私聊授权卡拼深链)。+ *+ * 解不开、或解出来属于**别的 chat** 时返回 null(不渲染深链): 链到别的会话比没有链更糟。+ */+function sourceMessageIdIn(chatId: string, encoded: string | undefined): string | null {+ if (encoded === undefined) return null;+ try {+ const decoded = decodeMessageId(encoded);+ return decoded.chatId === chatId ? decoded.messageId : null;+ } catch {+ return null;+ }+}+/** settle 缓冲/处理中的相册(见 albumsInFlight 注释)。 */interface PendingAlbum {messages: TgMessage[];@@ -639,7 +655,54 @@ export class TelegramIM extends BaseIM implements ChannelIM {async sendInteractiveCard(userId: string,spec: InteractiveCardSpec,+ opts?: {+ threadTs?: string;+ deliverToOwnerDm?: boolean;+ ownerDmNote?: string;+ ownerDmSourceMessageId?: string;+ },): Promise<{ messageId: string }> {+ // **只有授权类卡片**转宿主私聊(调用方用 deliverToOwnerDm 点名): 群里的授权卡消不掉,+ // 且只有 owner 能回答它。命令卡 / 会话选择卡(/ctr 等)不传这个开关 —— 它们的回调必须+ // 落在原群 lane, 否则 exitControl 释放的是宿主私聊那把锁而不是原群锁。+ // owner 未知时(理论上不该发生: 群 lane 的触发条件本身就是 owner @bot / reply)保持原+ // lane 投递, 不吞掉这次交互。+ const groupLane =+ opts?.deliverToOwnerDm === true && this.ownerUserId ? decodeLaneUserId(userId) : null;+ if (groupLane) {+ // 来源深链只认调用方给的那条触发消息 id —— 只有它知道这张卡属于哪一轮业务 turn。+ // 传输层能看到的两个信号都不等于业务轮次: 回挂目标在 'first' 档发出首条回复即被+ // consumeReplyParams 消耗, 而调用方在发卡前会主动收口流式 handle(turnRunner 的+ // finalizeActiveStream), 所以"有活动流式回合"同样为假。宁可不渲染深链, 不猜。+ const link = groupMessageLink(+ groupLane.chatId,+ sourceMessageIdIn(groupLane.chatId, opts?.ownerDmSourceMessageId),+ );+ // 卡片不再发到群里 —— callSend 只停它自己那条 chat 的 typing loop(这里是宿主私聊),+ // 群里那条会继续每 4.5s 打一次 sendChatAction, 于是群里一直显示「正在输入…」。+ // 手动停掉原群的那条(review 指出的回归)。+ this.stopTypingLoopsForChat(groupLane.chatId);+ // 说明文案由调用方给(传输层不造用户可见措辞); 深链是 URL 不是文案, 在这里拼。+ const notice = [opts?.ownerDmNote, link].filter((line) => line).join('\n');+ const { html, replyMarkup } = buildCardPayload({+ ...spec,+ body: notice.length > 0 ? `${notice}\n\n${spec.body}` : spec.body,+ });+ const sent = await this.callSend<TgMessage>('sendMessage', {+ chat_id: this.ownerUserId,+ text: html,+ parse_mode: 'HTML',+ ...(replyMarkup ? { reply_markup: replyMarkup } : {}),+ });+ // 刻意不动群 lane 的回挂目标: 那条触发消息在私聊里不存在, 消耗掉还会让本轮真正的+ // 回答失去引用。回声按**实际落地**的私聊维度记, 否则群窗口会以为 bot 在群里说过这段。+ this.recordOwnEcho(+ this.ownerUserId,+ spec.title ? `[${spec.title}]` : spec.body.slice(0, 100),+ sent,+ );+ return { messageId: encodeMessageId(String(sent.chat.id), String(sent.message_id)) };+ }this.claimTurnReplyTargetIfIdle(userId);const target = this.targetOf(userId);const { html, replyMarkup } = buildCardPayload(spec);@@ -1962,6 +2025,20 @@ export type { TelegramGroupWindowEntry } from './inbound.js';* reason 保留原文供日志/诊断; code 是给 UI 用的稳定分类 —— 渲染层按 code 取* i18n 文案, 不再把这些英文技术串直接怼给用户看。*/+/**+ * 私有超级群里某条消息的深链(`t.me/c/<internal>/<messageId>`) —— 授权卡改投宿主私聊后,+ * 用它告诉宿主「是哪个群的哪条消息」。+ *+ * 只对 `-100` 前缀的私有超级群成立(公开群要 username, 这一层没有持久化群名/username)。+ * 形状对不上返回 null, 调用方省掉那一行, 不拼一个点不开的链接。+ */+function groupMessageLink(chatId: string, messageId: string | null): string | null {+ if (messageId === null || !chatId.startsWith('-100')) return null;+ const internal = chatId.slice(4);+ if (!/^\d+$/.test(internal) || !/^\d+$/.test(messageId)) return null;+ return `https://t.me/c/${internal}/${messageId}`;+}+function mapConnectErrorToStatus(err: unknown): IMStatus {if (err instanceof TelegramApiError) {if (err.errorCode === 401 || err.errorCode === 404) {