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(im): 统一多端授权确认并展示来源消息 (#5414)

Dash09f30b36ccce
diff --git a/AGENTS.md b/AGENTS.md
index 782a9bc3d6..347636f887 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -54,6 +54,9 @@
前,必须先读 `docs/product-rules/core-product-principles.md`。
- 修改共享任务、跨账号访客邀请、共享上下文或共享成员权限前,必须先读
`docs/product-rules/shared-task-mode.md`;复用 device-link,同账号远控行为不变。
+- 修改 IM 工具授权、来源消息、多端确认或暂停期间的确认回执,或新增 IM 渠道前,
+ 必须先读 `docs/product-rules/im-permission-confirmation.md`;Desktop、Mobile 与共享
+ packages 共用同一最终决定,渠道收到回答不代表执行已恢复。
- 修改伙伴(Bot)的身份、Session 生命周期、模型 fallback、工作目录、Skill / MCP 装配、
委派协作或伙伴设置前,必须先读 `docs/product-rules/cindy-bots-runtime.md`。
- 新增或修改伙伴群聊的数据、发言编排、群专线 Session、分工(负责人、安排、分工 Session、群工作目录)、
diff --git a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts
index 82d0f855a1..eeef1ba100 100644
--- a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts
+++ b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts
@@ -2,6 +2,8 @@ import { readFileSync } from 'node:fs';
import ts from 'typescript';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import { createSharedPermission, type SharedPermission } from '../maker-ipc/sharedPermission';
+import { beginInteractionRoute, installDesktopInteractionHandler, type InteractionHandler, type InteractionSession } from '../maker-ipc/interactionRouter';
import { assertSharedTaskInteractionResolveCurrent, assertSharedTaskInvoke, setSharedTaskInteractionReader, type SharedTaskPeerCapture } from '../device-link/sharedTaskDispatch.js';
// Execute the production listener and control adapter without booting Electron.
@@ -12,6 +14,7 @@ const names = new Set([
'schedulePendingPermissionTimeout', 'setPendingInteractionTimeoutsPaused',
'resolvePendingInteraction', 'defaultDecisionForPending',
'cleanupPendingAgentInteractionsForSession', 'takePendingInteractionsForSession',
+ 'bindSharedPermission',
]);
const functions = ast.statements.filter((node) => ts.isFunctionDeclaration(node)
&& node.name && names.has(node.name.text)).map(node => node.getText(ast).replace(/^export /, ''));
@@ -56,6 +59,7 @@ function harness() {
const entries = new Map();
const dismiss = vi.fn();
const deps = {
+ createSharedPermission,
getDeviceLinkInvokeContext: () => ({ sharedTask }),
assertSharedTaskInteractionResolveCurrent,
setSharedTaskInteractionReader,
@@ -64,7 +68,7 @@ function harness() {
pendingInteractionResolvers: entries,
agentInputCoordinatorHolder: coordinator, inputCoordinator: coordinator,
PERMISSION_INTERACTION_TIMEOUT_MS: 10 * MINUTE,
- installDesktopInteractionHandler: (session: { id: string }, handler: (request: InteractionRequest) => Promise<InteractionDecision>) => listeners.set(session.id, handler),
+ installDesktopInteractionHandler,
shouldNotifyAgentIslandForSession: () => false,
flushAssistantBlock: vi.fn(), onInteractionMessage: vi.fn(),
redactToolInputForUntrustedBoundary: (_tool: string, input: unknown) => input,
@@ -75,19 +79,26 @@ function harness() {
goalAskAnswerObserver: null, ghostSetupInteractionBridge: { cleanupForSession: vi.fn() },
};
const runtime = new Function(...Object.keys(deps), compiled)(...Object.values(deps)) as {
- install: (session: { id: string }) => void;
+ install: (session: InteractionSession) => void;
hold: (id: string, held: boolean) => string[];
answer: (id: string, decision: InteractionDecision) => boolean;
cleanup: (id: string, reason: string) => void;
- take: (id: string) => Array<{ resolve: (decision: InteractionDecision) => void }>;
+ take: (id: string) => Array<{ resolve: (decision: InteractionDecision) => void; sharedPermission?: SharedPermission }>;
resolveFromIpc: (event: unknown, id: string, decision: InteractionDecision) => Promise<{ accepted: boolean }>;
};
- const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission') => {
- runtime.install({ id: sessionId });
+ const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission', channel?: InteractionHandler) => {
+ const session: InteractionSession = { id: sessionId, setInteractionListener: handler => { if (handler) listeners.set(sessionId, handler); } };
+ runtime.install(session);
+ const lease = channel ? beginInteractionRoute(session, {
+ route: { sessionId, turnId: 'turn', origin: { kind: 'hook', source: 'test' }, interactionSurface: 'channel-card', timeoutMs: 10 * MINUTE },
+ handle: channel,
+ // A presentation acknowledges cancellation; Router must still finalize it.
+ onCancel: () => true,
+ }) : undefined;
const settled = vi.fn();
const promise = listeners.get(sessionId)!({ kind, requestId: id, toolName: 'Shell', input: {} } as InteractionRequest);
void promise.then(settled);
- return { promise, settled };
+ return { promise, settled, lease };
};
return { ...runtime, request, entries, dismiss, setSharedTask: (peer?: SharedTaskPeerCapture) => { sharedTask = peer; } };
}
@@ -120,7 +131,7 @@ it('does not consume the pending decision when membership is revoked after dispa
expect(h.dismiss).toHaveBeenCalledTimes(1);
});
-it.each(['permission', 'ask_user_question', 'plan_review'] as const)('rejects guest decisions after %s is handed to Feishu, including already-admitted requests', async (kind) => {
+it.each(['ask_user_question', 'plan_review'] as const)('rejects guest decisions after %s is handed to Feishu, including already-admitted requests', async (kind) => {
const h = harness();
const p = h.request(kind, 'task', kind);
const peer: SharedTaskPeerCapture = {
@@ -144,6 +155,22 @@ it.each(['permission', 'ask_user_question', 'plan_review'] as const)('rejects gu
expect(h.entries.has(kind)).toBe(false);
});
+it('keeps an authorized shared-task permission answer available after IM takeover', async () => {
+ const h = harness();
+ const p = h.request();
+ const [taken] = h.take('task');
+ expect(h.entries.get('permission').migrated).not.toBe(true);
+ h.setSharedTask({
+ author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'guest', accountId: 'guest', displayName: 'Guest' },
+ isCurrent: () => true, authorize: () => true,
+ });
+ const answer = { kind: 'permission', behavior: 'allow' } as const;
+ await expect(h.resolveFromIpc({}, 'permission', answer)).resolves.toEqual({ accepted: true });
+ taken.resolve({ kind: 'permission', behavior: 'deny' });
+ await expect(p.promise).resolves.toEqual(answer);
+ expect(h.dismiss).toHaveBeenCalledTimes(1);
+});
+
it('rejects a guest replacement tool input without consuming the pending request', async () => {
const h = harness();
const p = h.request();
@@ -163,6 +190,59 @@ it('rejects a guest replacement tool input without consuming the pending request
});
describe('permission timeout follows the task pause lifecycle', () => {
+ it('holds a shared route timeout until resume without closing either surface early', async () => {
+ const h = harness();
+ h.hold('task', true);
+ let shared!: SharedPermission;
+ const p = h.request('permission', 'task', 'permission', (_req, permission) => {
+ shared = permission!;
+ return shared.result;
+ });
+ await vi.advanceTimersByTimeAsync(30 * MINUTE);
+ expect(p.settled).not.toHaveBeenCalled();
+ expect(shared.decision).toBeUndefined();
+ expect(h.dismiss).not.toHaveBeenCalled();
+ h.hold('task', false);
+ await expect(p.promise).resolves.toMatchObject({ behavior: 'deny', reason: 'interaction_timeout' });
+ await expect(shared.result).resolves.toMatchObject({ behavior: 'deny', reason: 'interaction_timeout' });
+ p.lease!.release();
+ });
+
+ it.each(['resume', 'session_aborted', 'session_closed', 'release'] as const)(
+ 'keeps a new IM answer provisional until %s and converges every surface', async finish => {
+ const h = harness();
+ h.hold('task', true);
+ let shared!: SharedPermission;
+ const presented = vi.fn();
+ const p = h.request('permission', 'task', 'permission', (_req, permission) => {
+ shared = permission!;
+ void shared.result.then(presented);
+ // Synchronous channel answers must already see the Host pause gate.
+ expect(shared.decide({ kind: 'permission', behavior: 'allow' })).toBe(true);
+ expect(shared.decide({ kind: 'permission', behavior: 'deny' })).toBe(false);
+ return shared.result;
+ });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(p.settled).not.toHaveBeenCalled();
+ expect(presented).not.toHaveBeenCalled();
+ expect(h.dismiss).not.toHaveBeenCalled();
+ expect(shared.decision).toBeUndefined();
+ if (finish === 'resume') h.hold('task', false);
+ else if (finish === 'release') p.lease!.release();
+ else h.cleanup('task', finish);
+ const expected = finish === 'resume'
+ ? { kind: 'permission', behavior: 'allow' }
+ : { kind: 'permission', behavior: 'deny', reason: finish === 'release' ? 'interaction_route_released' : finish };
+ await expect(p.promise).resolves.toEqual(expected);
+ await expect(shared.result).resolves.toEqual(expected);
+ expect(presented).toHaveBeenCalledExactlyOnceWith(expected);
+ expect(h.dismiss).toHaveBeenCalledTimes(1);
+ h.hold('task', false);
+ expect(shared.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);
+ p.lease!.release();
+ },
+ );
+
it('keeps the permission pending across its original deadline and resumes only the remaining budget', async () => {
const h = harness();
const p = h.request();
@@ -268,12 +348,14 @@ describe('permission timeout follows the task pause lifecycle', () => {
const [taken] = h.take('task');
h.hold('task', true);
taken.resolve({ kind: 'permission', behavior: 'allow' });
+ expect(taken.sharedPermission!.decision).toBeUndefined();
h.cleanup('task', reason);
h.cleanup('task', reason);
h.hold('task', false);
taken.resolve({ kind: 'permission', behavior: 'allow' });
await vi.advanceTimersByTimeAsync(30 * MINUTE);
expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason });
+ await expect(taken.sharedPermission!.result).resolves.toEqual({ kind: 'permission', behavior: 'deny', reason });
expect(h.entries.size).toBe(0);
});
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.ts
index 68cec2efd4..20f2f2b114 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
@@ -97,6 +97,7 @@ vi.mock('@cindy/maker-core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@cindy/maker-core')>();
return {
Session: actual.Session,
+ hasSessionPermissionUpdates: actual.hasSessionPermissionUpdates,
isAutoReviewUnavailableNotice: actual.isAutoReviewUnavailableNotice,
isAutoReviewConfirmUndeliveredNotice: actual.isAutoReviewConfirmUndeliveredNotice,
isTerminalAgentErrorEvent: actual.isTerminalAgentErrorEvent,
@@ -2809,9 +2810,11 @@ describe('交互卡链路(interaction listener 覆盖)', () => {
await expect(decisionPromise).resolves.toEqual({
kind: 'permission',
behavior: 'deny',
- reason: 'hook_interaction_timeout',
+ reason: 'hook_turn_terminal',
});
- expect(cancels).toEqual([{ interactionId: 'int-pd', reason: '任务已结束, 此交互已失效' }]);
+ expect(cancels).toEqual([{ interactionId: 'int-pd', reason: expect.stringContaining('来源:') }]);
+ expect(cancels[0].reason).toContain('Bash');
+ expect(cancels[0].reason).toContain('已失效');
});
it('turn 收口时未决交互按默认自决并发 cancel(改写 server 卡片)', async () => {
diff --git a/apps/desktop/src/main/hook-control/__tests__/sharedPermission.test.ts b/apps/desktop/src/main/hook-control/__tests__/sharedPermission.test.ts
new file mode 100644
index 0000000000..bfbcb2985b
--- /dev/null
+++ b/apps/desktop/src/main/hook-control/__tests__/sharedPermission.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createSharedPermission } from '../../maker-ipc/sharedPermission';
+import {
+ composeInteractionCard,
+ cancelHookInteraction,
+ registerHookInteraction,
+ resolveHookInteraction,
+} from '../interactions';
+
+describe('hook permission mirrors', () => {
+ it('publishes cancellation instead of a held approval when the turn ends', async () => {
+ const permission = createSharedPermission();
+ permission.decide = vi.fn(() => true); // Host has stored the answer while paused.
+ const composed = composeInteractionCard({ kind: 'permission', requestId: 'held', toolName: 'Read', input: {} })!;
+ const onFallback = vi.fn();
+ const pending = registerHookInteraction({ interactionId: 'held', composed, onFallback, sharedPermission: permission });
+ resolveHookInteraction('held', 'perm:allow');
+ expect(permission.decision).toBeUndefined();
+ expect(onFallback).not.toHaveBeenCalled();
+ cancelHookInteraction('held', '任务已结束');
+ await expect(pending).resolves.toMatchObject({ behavior: 'deny', reason: 'turn_terminal' });
+ expect(onFallback).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('确认已失效'));
+ });
+
+ it.each(['desktop', 'hook'])(
+ 'settles from %s, retains origin and rejects the other surface',
+ async (surface) => {
+ const permission = createSharedPermission();
+ const id = `shared-${surface}`;
+ const composed = composeInteractionCard({
+ kind: 'permission',
+ requestId: id,
+ toolName: 'Read',
+ input: {},
+ description: '来源:开发群\n原消息:检查仓库',
+ })!;
+ const onFallback = vi.fn();
+ const pending = registerHookInteraction({
+ interactionId: id,
+ composed,
+ onFallback,
+ sharedPermission: permission,
+ });
+ if (surface === 'desktop')
+ expect(permission.decide({ kind: 'permission', behavior: 'allow' })).toBe(true);
+ else expect(resolveHookInteraction(id, 'perm:allow')).toBe(true);
+ expect(resolveHookInteraction(id, 'perm:deny')).toBe(false);
+ await expect(pending).resolves.toMatchObject({ behavior: 'allow' });
+ expect(onFallback).toHaveBeenCalledWith(expect.stringContaining('来源:开发群'));
+ expect(onFallback).toHaveBeenCalledWith(expect.stringContaining('已允许'));
+ },
+ );
+});
diff --git a/apps/desktop/src/main/hook-control/interactions.ts b/apps/desktop/src/main/hook-control/interactions.ts
index 5dc1d2fb8d..882701a363 100644
--- a/apps/desktop/src/main/hook-control/interactions.ts
+++ b/apps/desktop/src/main/hook-control/interactions.ts
@@ -33,6 +33,8 @@
import type { InteractionButton, InteractionRequestPayload } from '@cindy/slack-hook-protocol';
import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import type { SharedPermission } from '../maker-ipc/sharedPermission';
+import { permissionOutcomeText } from '../im/shared/permissionPresentation';
import {
composeInteractionModel,
@@ -161,6 +163,7 @@ export function composeInteractionCard(req: InteractionRequest): ComposedInterac
/** 挂起交互条目。 */
interface PendingHookInteraction {
+ sharedPermission?: SharedPermission;
decisions: Map<string, InteractionDecision>;
defaultDecision: InteractionDecision;
fallbackReason: string;
@@ -183,18 +186,24 @@ export function registerHookInteraction(opts: {
composed: ComposedInteractionCard;
onFallback: (reason: string) => void;
timeoutMs?: number;
+ sharedPermission?: SharedPermission;
}): Promise<InteractionDecision> {
const { interactionId, composed, onFallback } = opts;
return new Promise<InteractionDecision>((resolve) => {
const timer = setTimeout(() => {
const entry = pending.get(interactionId);
if (!entry) return;
+ if (entry.sharedPermission) {
+ entry.sharedPermission.decide(entry.defaultDecision);
+ return;
+ }
pending.delete(interactionId);
entry.onFallback(entry.fallbackReason);
entry.resolve(entry.defaultDecision);
}, opts.timeoutMs ?? HOOK_INTERACTION_TIMEOUT_MS);
timer.unref?.();
pending.set(interactionId, {
+ sharedPermission: opts.sharedPermission,
decisions: composed.decisions,
defaultDecision: composed.defaultDecision,
fallbackReason: composed.fallbackReason,
@@ -202,6 +211,18 @@ export function registerHookInteraction(opts: {
timer,
onFallback,
});
+ if (opts.sharedPermission) {
+ void opts.sharedPermission.result.then((decision) => {
+ const entry = pending.get(interactionId);
+ if (entry?.sharedPermission !== opts.sharedPermission) return;
+ pending.delete(interactionId);
+ clearTimeout(timer);
+ const result = permissionOutcomeText(decision);
+ try { onFallback(`${composed.card.body ?? ''}\n\n${result}`); }
+ catch { /* A channel update cannot change an accepted decision. */ }
+ finally { resolve(decision); }
+ });
+ }
});
}
@@ -214,6 +235,7 @@ export function resolveHookInteraction(interactionId: string, buttonId: string):
if (!entry) return false;
const decision = entry.decisions.get(buttonId);
if (!decision) return false; // 未知按钮(伪造/陈旧卡片), 保持挂起等真实决策
+ if (entry.sharedPermission) return entry.sharedPermission.decide(decision);
pending.delete(interactionId);
clearTimeout(entry.timer);
entry.resolve(decision);
@@ -227,6 +249,9 @@ export function resolveHookInteraction(interactionId: string, buttonId: string):
export function cancelHookInteraction(interactionId: string, reason: string): boolean {
const entry = pending.get(interactionId);
if (!entry) return false;
+ if (entry.sharedPermission) {
+ return entry.sharedPermission.settle({ kind: 'permission', behavior: 'deny', reason: 'turn_terminal' });
+ }
pending.delete(interactionId);
clearTimeout(entry.timer);
entry.onFallback(reason);
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index 852c75b207..2867806431 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -109,6 +109,8 @@ import { beginHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInter
import { observeHookTurn, type HookTurnObserver } from './turnObserver.js';
import { bindRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';
import { beginGroupHistoryAccess } from '../im/shared/groupHistoryAccess.js';
+import { describeInteractionSource } from '../im/shared/interactionSource';
+import { groupLaneOf } from './groupWindow';
import type {
HookContinuationWatchRequest,
@@ -780,7 +782,7 @@ export function createMakerHookSessionRunner(deps: {
// 前向引用: 交互回调只在 turn 跑起来之后才可能被调用, 那时 observer 已就位。
// 用它给过程区挂「等待授权」, 不新增任何渠道消息。
let activeObserver: HookTurnObserver | null = null;
- const handleHookInteraction: InteractionHandler = async (ireq) => {
+ const handleHookInteraction: InteractionHandler = async (ireq, sharedPermission) => {
if (req.onInteraction) {
const sendCard = req.onInteraction;
const sendCancel = req.onInteractionCancel;
@@ -806,7 +808,6 @@ export function createMakerHookSessionRunner(deps: {
return { kind: 'ask_user_question', answers: {} };
}
ownInteractionIds.add(ireq.requestId);
- sendCard({ interactionId: ireq.requestId, ...composed.card });
// 等授权期间没有任何 agent 事件 —— 渠道那条进度消息会彻底静止, 而卡片
// 可能根本不在这个会话里(Telegram 群里的授权卡改投宿主私聊)。挂一行状态,
// 收口后摘掉; 全程只改已经在发的那条快照, 不新增群消息。
@@ -814,11 +815,14 @@ export function createMakerHookSessionRunner(deps: {
activeObserver?.markInteractionBoundary();
activeObserver?.setNotice(awaitingInteractionNotice(ireq.kind));
try {
- const decision = await registerHookInteraction({
+ const pendingDecision = registerHookInteraction({
+ sharedPermission,
interactionId: ireq.requestId,
composed,
onFallback: (reason) => sendCancel?.(ireq.requestId, reason),
});
+ sendCard({ interactionId: ireq.requestId, ...composed.card });
+ const decision = await pendingDecision;
ownInteractionIds.delete(ireq.requestId);
return decision;
} finally {
@@ -1208,6 +1212,23 @@ export function createMakerHookSessionRunner(deps: {
turnId: randomUUID(),
origin: routeOrigin,
interactionSurface: req.onInteraction ? 'channel-card' : 'headless',
+ sourceDescription: describeInteractionSource({
+ channelName: req.source?.im ?? req.origin.connectionName,
+ chatId: req.source?.channelName ?? req.title ?? req.source?.im ?? 'IM',
+ text: req.source?.userText ?? '',
+ interactionSource: {
+ senderName: req.source?.threadContext?.find((message) =>
+ message.messageId === req.source?.triggerMessageId && !!message.messageId)?.author,
+ ...(() => {
+ const lane = groupLaneOf(req.origin.externalKey);
+ const id = req.source?.triggerMessageId;
+ return lane && /^-100\d+$/.test(lane.chatId) && id && /^\d+$/.test(id)
+ ? { messageUrl: `https://t.me/c/${lane.chatId.slice(4)}/${id}`,
+ ...(lane.threadId ? { threadName: lane.threadId } : {}) }
+ : {};
+ })(),
+ },
+ }),
},
handle: handleHookInteraction,
onCancel: (requestId) => {
diff --git a/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts b/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts
index c5cb11fee2..787ed53aa4 100644
--- a/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts
+++ b/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts
@@ -2,8 +2,22 @@ import { describe, expect, it, vi } from 'vitest';
import type { DingTalkIM } from '@cindy/im';
import { __testing, handleDingTalkTextInteraction } from '../interaction';
+import { createSharedPermission } from '../../../maker-ipc/sharedPermission';
describe('dingtalk text interactions', () => {
+ it('settles the shared permission when the text reply times out', async () => {
+ const sharedPermission = createSharedPermission();
+ const im = {
+ requestTextReply: vi.fn(async () => { throw new Error('DINGTALK_INTERACTION_TIMEOUT'); }),
+ sendText: vi.fn(async () => {}),
+ } as unknown as DingTalkIM;
+ await expect(handleDingTalkTextInteraction(im, 'owner', {
+ kind: 'permission', requestId: 'timeout', toolName: 'Bash', input: {},
+ }, { sharedPermission })).resolves.toMatchObject({ kind: 'permission', behavior: 'deny' });
+ expect(sharedPermission.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);
+ await expect(sharedPermission.result).resolves.toMatchObject({ reason: 'dingtalk_interaction_timeout_or_cancelled' });
+ });
+
it('parses explicit allow and deny replies', () => {
const request = {
kind: 'permission' as const,
diff --git a/apps/desktop/src/main/im/dingtalk/adapter.ts b/apps/desktop/src/main/im/dingtalk/adapter.ts
index 8cfd51412d..89a10eaa3a 100644
--- a/apps/desktop/src/main/im/dingtalk/adapter.ts
+++ b/apps/desktop/src/main/im/dingtalk/adapter.ts
@@ -70,8 +70,8 @@ export function buildDingTalkAdapter(
},
processingEmoji: '',
buildVendorOptions: (userId) => ({ dingtalkChatId: userId, source: 'dingtalk' }),
- handleTextInteraction: (userId, request) =>
- handleDingTalkTextInteraction(dingtalkIm, userId, request),
+ handleTextInteraction: (userId, request, options) =>
+ handleDingTalkTextInteraction(dingtalkIm, userId, request, options),
// 对齐 Telegram / 飞书的边界:主人私聊完全遵循 session.permissionMode,
// 因而可以显式选择 bypassPermissions(完全访问);群聊携带成员可控上下文,
// 无论谁 @ bot 都附加强确认策略,危险操作仍须主人在群里确认。
diff --git a/apps/desktop/src/main/im/dingtalk/interaction.ts b/apps/desktop/src/main/im/dingtalk/interaction.ts
index 714c9ebf9e..213e05acf7 100644
--- a/apps/desktop/src/main/im/dingtalk/interaction.ts
+++ b/apps/desktop/src/main/im/dingtalk/interaction.ts
@@ -2,18 +2,33 @@ import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core'
import type { DingTalkIM } from '@cindy/im';
import { autoReviewUnavailablePromptLine } from '../shared/autoReviewUnavailablePrompt';
+import type { SharedPermission } from '../../maker-ipc/sharedPermission';
+import { permissionOutcomeText } from '../shared/permissionPresentation';
export function handleDingTalkTextInteraction(
im: DingTalkIM,
userId: string,
request: InteractionRequest,
+ options?: { timeoutMs?: number; sharedPermission?: SharedPermission },
): Promise<InteractionDecision> {
+ const shared = options?.sharedPermission;
+ if (shared?.decision) return shared.result;
if (request.kind === 'ask_user_question') {
return answerQuestions(im, userId, request);
}
- return im.requestTextReply(userId, formatInteractionPrompt(request), (text) =>
+ const result = im.requestTextReply(userId, formatInteractionPrompt(request), (text) =>
parseInteractionReply(request, text),
- );
+ options?.timeoutMs,
+ shared,
+ ).catch((error) => {
+ if (!shared) throw error;
+ shared.decide({ kind: 'permission', behavior: 'deny', reason: 'dingtalk_interaction_timeout_or_cancelled' });
+ return shared.result;
+ });
+ if (shared) void result.then((decision) => im.sendText(userId,
+ permissionOutcomeText(decision, request.kind === 'permission' ? request.toolName : undefined),
+ )).catch(() => {});
+ return result;
}
async function answerQuestions(
@@ -37,6 +52,7 @@ function formatInteractionPrompt(request: InteractionRequest): string {
const unavailable = autoReviewUnavailablePromptLine(request);
return [
`需要确认操作:${request.toolName}`,
+ ...(request.description ? [request.description] : []),
...(unavailable ? [unavailable] : []),
'回复“允许”继续,或回复“拒绝”取消。',
].join('\n');
diff --git a/apps/desktop/src/main/im/shared/__tests__/permissionPresentation.test.ts b/apps/desktop/src/main/im/shared/__tests__/permissionPresentation.test.ts
new file mode 100644
index 0000000000..40538aae83
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/permissionPresentation.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { InteractiveCardSpec } from '@cindy/im';
+import { createSharedPermission } from '../../../maker-ipc/sharedPermission';
+import { presentSharedPermissionCard } from '../permissionPresentation';
+import {
+ cancelPending,
+ lookupPending,
+ rejectAllPending,
+ resolvePending,
+} from '../pendingInteractions';
+import { describeInteractionSource } from '../interactionSource';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+function presentation(requestId: string, send = vi.fn(async () => ({ messageId: 'dm|7' }))) {
+ const permission = createSharedPermission();
+ const update = vi.fn<(messageId: string, spec: InteractiveCardSpec) => Promise<void>>(
+ async () => {},
+ );
+ const onError = vi.fn();
+ const result = presentSharedPermissionCard({
+ requestId,
+ toolName: 'Bash',
+ owner: Symbol(),
+ permission,
+ send,
+ update,
+ onError,
+ resolved: (decision) => ({
+ title: 'Bash',
+ body: `来源:群 A\n原消息:检查仓库\n${decision.kind === 'permission' && decision.behavior}`,
+ buttons: [],
+ }),
+ });
+ return { permission, update, result, onError };
+}
+
+describe('shared IM permission presentation', () => {
+ it('retains source and the Desktop result when the card arrives after confirmation', async () => {
+ const sent = deferred<{ messageId: string }>();
+ const p = presentation(
+ 'late-send',
+ vi.fn(() => sent.promise),
+ );
+ expect(lookupPending('late-send')).not.toBeNull();
+ expect(p.permission.decide({ kind: 'permission', behavior: 'allow' })).toBe(true);
+ await expect(p.result).resolves.toMatchObject({ behavior: 'allow' });
+ expect(resolvePending('late-send', { kind: 'permission', behavior: 'deny' })).toBeNull();
+ expect(p.update).not.toHaveBeenCalled();
+ sent.resolve({ messageId: 'dm|8' });
+ await vi.waitFor(() =>
+ expect(p.update).toHaveBeenCalledWith('dm|8', {
+ title: 'Bash',
+ body: '来源:群 A\n原消息:检查仓库\nallow',
+ buttons: [],
+ }),
+ );
+ });
+
+ it('accepts only the first IM/Desktop answer, including back-to-back synchronous clicks', async () => {
+ const p = presentation('double-click');
+ expect(resolvePending('double-click', { kind: 'permission', behavior: 'deny' })).toMatchObject({
+ shared: true,
+ });
+ expect(p.permission.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);
+ await expect(p.result).resolves.toMatchObject({ behavior: 'deny' });
+ await vi.waitFor(() => expect(p.update).toHaveBeenCalledOnce());
+ expect(p.update.mock.calls[0][1].body).toContain('deny');
+ expect(lookupPending('double-click')).toBeNull();
+ });
+
+ it('cancels both presentations and closes a late card without losing its source', async () => {
+ const sent = deferred<{ messageId: string }>();
+ const p = presentation(
+ 'cancel-send',
+ vi.fn(() => sent.promise),
+ );
+ cancelPending('cancel-send', 'session_disposed');
+ await expect(p.result).resolves.toMatchObject({ behavior: 'deny', reason: 'session_disposed' });
+ sent.resolve({ messageId: 'dm|9' });
+ await vi.waitFor(() => expect(p.update).toHaveBeenCalledOnce());
+ expect(p.update.mock.calls[0][1].body).toContain('来源:群 A');
+ expect(p.permission.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);
+ });
+
+ it('keeps Cindy usable if the IM send fails, without retrying or rejecting execution', async () => {
+ const p = presentation(
+ 'send-failed',
+ vi.fn(async () => {
+ throw new Error('offline');
+ }),
+ );
+ await vi.waitFor(() => expect(p.onError).toHaveBeenCalledOnce());
+ expect(p.permission.decision).toBeUndefined();
+ p.permission.decide({ kind: 'permission', behavior: 'allow' });
+ await expect(p.result).resolves.toMatchObject({ behavior: 'allow' });
+ expect(p.update).not.toHaveBeenCalled();
+ });
+
+ it('lets the shared presenter close the card when its runner is disposed', async () => {
+ const p = presentation('disposed');
+ expect(rejectAllPending('session_disposed')).toEqual([]);
+ await expect(p.result).resolves.toMatchObject({ behavior: 'deny', reason: 'session_disposed' });
+ await vi.waitFor(() => expect(p.update).toHaveBeenCalledOnce());
+ expect(p.update.mock.calls[0][1].body).toContain('来源:群 A');
+ });
+});
+
+describe('IM permission source', () => {
+ it('uses the admitted message and provider metadata, bounded independently of later messages', () => {
+ const text = describeInteractionSource({
+ channelName: 'telegram',
+ chatId: '-100200',
+ text: '检查仓库'.repeat(100),
+ interactionSource: {
+ chatName: '开发群',
+ threadName: '日常讨论',
+ senderName: 'Dash',
+ messageUrl: 'https://t.me/c/200/7',
+ },
+ });
+ expect(text).toContain('开发群');
+ expect(text).toContain('日常讨论');
+ expect(text).toContain('Dash');
+ expect(text).toContain('https://t.me/c/200/7');
+ expect(text.length).toBeLessThan(350);
+ });
+
+ it('supports a future channel without metadata and never copies protected message text', () => {
+ expect(
+ describeInteractionSource({ channelName: 'future-im', chatId: 'group-1', text: 'hello' }),
+ ).toContain('future-im · group-1');
+ const text = describeInteractionSource({
+ channelName: 'telegram',
+ chatId: '1',
+ text: 'secret source',
+ protectedContent: true,
+ interactionSource: { messageUrl: 'javascript:alert(1)' },
+ });
+ expect(text).not.toContain('secret source');
+ expect(text).not.toContain('javascript:');
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 84dc4bc42b..70471e8746 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -887,7 +887,12 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
kind: 'permission',
behavior: 'allow',
});
- expect(handleTextInteraction).toHaveBeenCalledWith('ou_user', request, {
+ expect(handleTextInteraction).toHaveBeenCalledWith('ou_user', expect.objectContaining({
+ ...request,
+ description: expect.stringContaining('来源:'),
+ metadata: expect.objectContaining({ imSourceDescription: expect.stringContaining('来源:') }),
+ }), {
+ sharedPermission: expect.objectContaining({ decide: expect.any(Function) }),
timeoutMs: 12_345,
});
expect(states).toEqual(['waiting', 'resolved']);
diff --git a/apps/desktop/src/main/im/shared/cardActionHandler.ts b/apps/desktop/src/main/im/shared/cardActionHandler.ts
index d64a3509a0..9f0105467f 100644
--- a/apps/desktop/src/main/im/shared/cardActionHandler.ts
+++ b/apps/desktop/src/main/im/shared/cardActionHandler.ts
@@ -1646,6 +1646,7 @@ export function createCardActionHandler(
// 授权卡保留原始正文(工具名 + 参数预览)再追加决策结果 — 用户要能
// 回看自己批准的是什么; 其它交互卡维持整卡替换的旧形态。
const resolvedLabel = describeDecision(decision);
+ if (resolved.shared) return; // Shared presenter updates every surface once.
const spec = resolved.permissionCard
? cards.buildResolvedPermissionCard(resolved.permissionCard, resolvedLabel)
: cards.buildResolvedCard(resolvedLabel);
diff --git a/apps/desktop/src/main/im/shared/cardBuilders.ts b/apps/desktop/src/main/im/shared/cardBuilders.ts
index ca3af99fa9..e3917752d6 100644
--- a/apps/desktop/src/main/im/shared/cardBuilders.ts
+++ b/apps/desktop/src/main/im/shared/cardBuilders.ts
@@ -202,7 +202,7 @@ export function createCardBuilders(
const unavailable = autoReviewUnavailablePromptLine(req);
return {
title: ui.cards.permission.title(model.toolName),
- body: unavailable ? `${unavailable}\n\n${params}` : params,
+ body: [req.description, unavailable, params].filter(Boolean).join('\n\n'),
buttons: [
{
id: 'permission:allow:once',
diff --git a/apps/desktop/src/main/im/shared/interactionSource.ts b/apps/desktop/src/main/im/shared/interactionSource.ts
new file mode 100644
index 0000000000..edc1815643
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/interactionSource.ts
@@ -0,0 +1,35 @@
+import type { IMMessageEvent } from '@cindy/im';
+
+function excerpt(value: string | undefined, max: number): string {
+ const text = (value ?? '')
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
+ // Display an excerpt as text, not user-controlled Markdown or an @all ping.
+ .replace(/[\\`*_[\]<>@]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 0xfee0))
+ .trim();
+ return text.length > max ? `${text.slice(0, max)}…` : text;
+}
+
+/** Transport metadata + the exact admitted message, never the latest chat message. */
+export function describeInteractionSource(
+ event: Pick<
+ IMMessageEvent,
+ 'channelName' | 'chatId' | 'text' | 'interactionSource' | 'speaker' | 'protectedContent'
+ >,
+): string {
+ const source = event.interactionSource;
+ const lines = [
+ `来源:${excerpt(event.channelName, 40)} · ${excerpt(source?.chatName ?? event.chatId, 100)}`,
+ ...(source?.threadName ? [`话题:${excerpt(source.threadName, 80)}`] : []),
+ ...(source?.senderName || event.speaker?.name
+ ? [`发起人:${excerpt(source?.senderName ?? event.speaker?.name, 80)}`]
+ : []),
+ event.protectedContent
+ ? '原消息:受保护内容'
+ : `原消息:${excerpt(event.text, 200) || '(无文字内容)'}`,
+ ];
+ // Only transport-produced HTTP links may appear here; never copy model URLs.
+ if (source?.messageUrl && /^https:\/\/[^\s<>]+$/.test(source.messageUrl)) {
+ lines.push(`查看原消息:${source.messageUrl}`);
+ }
+ return lines.join('\n');
+}
diff --git a/apps/desktop/src/main/im/shared/messageHandler.ts b/apps/desktop/src/main/im/shared/messageHandler.ts
index 5caac1a5a0..e3d28b4511 100644
--- a/apps/desktop/src/main/im/shared/messageHandler.ts
+++ b/apps/desktop/src/main/im/shared/messageHandler.ts
@@ -32,6 +32,7 @@ import type { ImSlashHandlers } from './slashCommands';
import { looksLikeSlashCommand } from './slashCommands';
import type { ImTurnRunner } from './turnRunner';
import type { ImChannelAdapter } from './types';
+import { describeInteractionSource } from './interactionSource';
/**
* `!stop` 控制指令 — 半角/全角感叹号、大小写不敏感(issue #867)。
@@ -383,6 +384,7 @@ export function createMessageHandler(
botContextId: event.contextId,
userId: event.senderId,
userMessageId: event.messageId,
+ sourceDescription: describeInteractionSource(event),
text: event.text,
// 受保护群的触发消息照常起 turn, 但不进会话存档(渠道侧已挡住群历史池,
// 这里挡住第二条路径)。
diff --git a/apps/desktop/src/main/im/shared/pendingInteractions.ts b/apps/desktop/src/main/im/shared/pendingInteractions.ts
index 72741c4ab8..2c02729193 100644
--- a/apps/desktop/src/main/im/shared/pendingInteractions.ts
+++ b/apps/desktop/src/main/im/shared/pendingInteractions.ts
@@ -11,6 +11,7 @@
*/
import type { AskUserQuestionItem, InteractionDecision } from '@cindy/maker-core';
+import type { SharedPermission } from '../../maker-ipc/sharedPermission';
import {
buildAskNoAnswerDecision,
@@ -19,6 +20,7 @@ import {
} from './interactionCardModel';
interface PendingEntry {
+ sharedPermission?: SharedPermission;
/** Runtime runner identity; never shared across channels or reconnect instances. */
owner?: symbol;
resolve: (decision: InteractionDecision) => void;
@@ -61,6 +63,7 @@ export function registerPending(
kind: InteractionDecision['kind'],
messageId: string,
extras?: {
+ sharedPermission?: SharedPermission;
owner?: symbol;
toolName?: string;
permissionCard?: { title: string; body: string };
@@ -92,6 +95,7 @@ export function registerPendingExternal(
resolve: (decision: InteractionDecision) => void,
reject: (err: Error) => void,
extras?: {
+ sharedPermission?: SharedPermission;
owner?: symbol;
toolName?: string;
permissionCard?: { title: string; body: string };
@@ -103,6 +107,7 @@ export function registerPendingExternal(
throw new Error(`pending interaction already exists for requestId=${requestId}`);
}
pending.set(requestId, {
+ sharedPermission: extras?.sharedPermission,
resolve,
reject,
messageId,
@@ -122,9 +127,13 @@ export function lookupPending(requestId: string): PendingEntry | null {
export function resolvePending(
requestId: string,
decision: InteractionDecision,
-): { messageId: string; permissionCard?: { title: string; body: string } } | null {
+): { messageId: string; permissionCard?: { title: string; body: string }; shared?: boolean } | null {
const entry = pending.get(requestId);
if (!entry) return null;
+ if (entry.sharedPermission) {
+ if (!entry.sharedPermission.decide(decision)) return null;
+ return { messageId: entry.messageId, shared: true };
+ }
pending.delete(requestId);
entry.resolve(decision);
return { messageId: entry.messageId, permissionCard: entry.permissionCard };
@@ -142,6 +151,10 @@ export function resolvePending(
export function cancelPending(requestId: string, reason: string): { messageId: string } | null {
const entry = pending.get(requestId);
if (!entry) return null;
+ if (entry.sharedPermission) {
+ entry.sharedPermission.settle(buildPermissionDenyDecision(reason));
+ return null; // The shared presenter owns the final card, including its source.
+ }
pending.delete(requestId);
if (entry.kind === 'ask_user_question') {
entry.resolve(buildAskNoAnswerDecision());
@@ -153,6 +166,11 @@ export function cancelPending(requestId: string, reason: string): { messageId: s
return { messageId: entry.messageId };
}
+/** Remove a shared presentation after the authoritative decision has settled. */
+export function forgetSharedPending(requestId: string, permission: SharedPermission): void {
+ if (pending.get(requestId)?.sharedPermission === permission) pending.delete(requestId);
+}
+
/** Reject all pending interactions (used on session close / error). */
export function rejectAllPending(
reason: string,
@@ -162,7 +180,9 @@ export function rejectAllPending(
// Remove the selected entries before callbacks can register another request.
for (const [requestId] of entries) pending.delete(requestId);
for (const [, entry] of entries) entry.reject(new Error(reason));
- return entries.map(([requestId, entry]) => ({ requestId, messageId: entry.messageId }));
+ // Shared presenters update their own final card, including cards still being sent.
+ return entries.filter(([, entry]) => !entry.sharedPermission)
+ .map(([requestId, entry]) => ({ requestId, messageId: entry.messageId }));
}
export function getPendingCount(): number {
diff --git a/apps/desktop/src/main/im/shared/permissionPresentation.ts b/apps/desktop/src/main/im/shared/permissionPresentation.ts
new file mode 100644
index 0000000000..e19c563f3d
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/permissionPresentation.ts
@@ -0,0 +1,58 @@
+import type { InteractionDecision } from '@cindy/maker-core';
+import type { InteractiveCardSpec } from '@cindy/im';
+import {
+ isExpiredPermissionDecision,
+ type SharedPermission,
+} from '../../maker-ipc/sharedPermission';
+import { hasSessionPermissionUpdates } from '@cindy/maker-core';
+import { forgetSharedPending, registerPendingExternal } from './pendingInteractions';
+
+/** Receipt only: the Host may hold the choice until the task resumes. */
+export const INTERACTION_CHOICE_RECEIVED_TEXT = '已收到你的选择。';
+
+/** Text-only channels and Hook share the same final permission wording. */
+export function permissionOutcomeText(decision: InteractionDecision, toolName?: string): string {
+ const status =
+ decision.kind === 'permission' && decision.behavior === 'allow'
+ ? hasSessionPermissionUpdates(decision)
+ ? '✅ 已允许(本任务)'
+ : '✅ 已允许(仅本次)'
+ : isExpiredPermissionDecision(decision)
+ ? '⌛ 本次确认已失效'
+ : '❌ 已拒绝';
+ return toolName ? `${status}:${toolName}` : status;
+}
+
+/** Register before network IO; a Desktop decision may arrive while send is in flight. */
+export function presentSharedPermissionCard(args: {
+ requestId: string;
+ toolName: string;
+ owner: symbol;
+ permission: SharedPermission;
+ send(): Promise<{ messageId: string }>;
+ resolved(decision: InteractionDecision): InteractiveCardSpec;
+ update(messageId: string, spec: InteractiveCardSpec): Promise<void>;
+ onError(error: unknown): void;
+}): Promise<InteractionDecision> {
+ const { permission, requestId } = args;
+ if (permission.decision) return permission.result;
+ registerPendingExternal(
+ requestId,
+ 'permission',
+ '',
+ permission.decide,
+ () => {
+ permission.settle({ kind: 'permission', behavior: 'deny', reason: 'session_disposed' });
+ },
+ { owner: args.owner, toolName: args.toolName, sharedPermission: permission },
+ );
+ void permission.result.then(() => forgetSharedPending(requestId, permission));
+ // Sending and updating are presentation only: neither delays execution nor
+ // rejects a permission that can still be answered in Cindy.
+ void (async () => {
+ const { messageId } = await args.send();
+ const decision = await permission.result;
+ await args.update(messageId, args.resolved(decision));
+ })().catch(args.onError);
+ return permission.result;
+}
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index ed3e0f8d7d..8eca35c9e2 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -35,6 +35,10 @@ import { createHash, randomUUID } from 'node:crypto';
import path from 'node:path';
import { isImAccountScopeClosedError } from '../accountBoundary';
import { bindRuntimeRecoveryNotice } from './runtimeRecoveryNotice';
+import { isExpiredPermissionDecision, type SharedPermission } from '../../maker-ipc/sharedPermission';
+import { presentSharedPermissionCard } from './permissionPresentation';
+import { describeInteractionSource } from './interactionSource';
+import { hasSessionPermissionUpdates } from '@cindy/maker-core';
/**
* 群里的授权卡改投宿主私聊时, 加在卡片正文顶部的说明。
@@ -197,6 +201,7 @@ interface TurnState {
/** thread = session 模型的会话维度键(slack thread root ts);feishu undefined。 */
scopeKey?: string;
initialMessageText: string;
+ sourceDescription?: string;
reusesExistingSession?: boolean;
notificationReply?: boolean;
revalidateNotificationReply?: () => Promise<void>;
@@ -396,6 +401,7 @@ type DefaultRouteTargetResolution =
| { target: null; missingAuth: ImAuthRouteStatus & { agentKind: AgentKind; model: string } };
export interface ImRunAgentTurnArgs {
+ sourceDescription?: string;
contextSnapshot?: ImContextSnapshot;
/** Main-owned, resolved from an authenticated provider notification receipt. */
notificationSessionId?: string;
@@ -896,6 +902,9 @@ export function createTurnRunner(
userId,
scopeKey: target.scopeKey,
initialMessageText: text,
+ sourceDescription: args.sourceDescription ?? describeInteractionSource({
+ channelName: channel, chatId: userId, text, protectedContent: args.protectedContent,
+ }),
reusesExistingSession: target.attached || target.notificationReply,
notificationReply: target.notificationReply,
revalidateNotificationReply: args.revalidateNotificationReply,
@@ -1354,6 +1363,7 @@ export function createTurnRunner(
turnId: item.turn.turnId,
origin: effectiveTurnPolicy?.origin ?? { kind: 'im', channel },
interactionSurface: 'channel-card',
+ sourceDescription: item.turn.sourceDescription,
...(effectiveTurnPolicy?.confirmationTimeoutMs
? { timeoutMs: effectiveTurnPolicy.confirmationTimeoutMs }
: {}),
@@ -1367,6 +1377,12 @@ export function createTurnRunner(
item.turn.scopeKey,
effectiveTurnPolicy?.confirmationTimeoutMs,
),
+ permissionGuard: (request) => {
+ const guard = checkChannelDestructiveToolCall(request.toolName, request.input);
+ return guard.destructive
+ ? { kind: 'permission', behavior: 'deny', reason: `[destructiveGuard] ${guard.reason}` }
+ : null;
+ },
// 文本渠道自己认领掉的不动卡片(它本来就没有卡);其余走
// dropInteractionCard —— 作废 pending 的同时把那张卡收口。
onCancel: (requestId, decision) =>
@@ -1917,6 +1933,7 @@ export function createTurnRunner(
*/
async function publishMigratedInteraction(
entry: {
+ sharedPermission?: SharedPermission;
requestId: string;
request: InteractionRequest;
resolve: (decision: InteractionDecision) => void;
@@ -1926,6 +1943,11 @@ export function createTurnRunner(
scopeKey?: string,
): Promise<void> {
const { request: req, resolve } = entry;
+ if (entry.sharedPermission) {
+ const decision = await handleInteractionFor(localSessionId, userId, scopeKey)(req, entry.sharedPermission);
+ entry.sharedPermission.decide(decision);
+ return;
+ }
log.info(
`publishMigrated kind=${req.kind} requestId=...${req.requestId.slice(-8)} session=...${localSessionId.slice(-8)}`,
);
@@ -3390,7 +3412,7 @@ export function createTurnRunner(
scopeKey?: string,
confirmationTimeoutMs?: number,
) {
- return async (rawReq: InteractionRequest): Promise<InteractionDecision> => {
+ return async (rawReq: InteractionRequest, sharedPermission?: SharedPermission): Promise<InteractionDecision> => {
// Redact BEFORE anything channel-facing sees the request. This listener
// replaces the Desktop handler, which does its own redaction, so without
// this the card builders (interactionCardModel copies `input` verbatim)
@@ -3425,6 +3447,7 @@ export function createTurnRunner(
}
}
return adapter.handleTextInteraction(userId, req, {
+ sharedPermission,
...(confirmationTimeoutMs ? { timeoutMs: confirmationTimeoutMs } : {}),
});
}
@@ -3493,6 +3516,38 @@ export function createTurnRunner(
return { kind, behavior: 'deny', reason: denyReason ?? 'no_card' };
}
+ if (req.kind === 'permission' && sharedPermission) {
+ const permissionSpec = spec;
+ const permissionUi = adapter.ui.cards.permission;
+ return presentSharedPermissionCard({
+ requestId: req.requestId,
+ toolName: req.toolName,
+ owner: pendingOwner,
+ permission: sharedPermission,
+ send: async () => {
+ await finalizeActiveStream(localSessionId);
+ const sent = await output.im.sendInteractiveCard(userId, permissionSpec, {
+ threadTs: scopeKey,
+ deliverToOwnerDm: true,
+ });
+ if (!sharedPermission.decision && userId.startsWith('g/') && permissionUi.dmRoutedNotice) {
+ const notice = permissionUi.dmRoutedNotice;
+ void im.sendText(userId, typeof notice === 'function' ? notice(req.toolName) : notice, { threadTs: scopeKey })
+ .catch(() => log.warn('shared permission source notice failed'));
+ }
+ return sent;
+ },
+ resolved: (decision) => cards.buildResolvedPermissionCard(
+ { title: permissionSpec.title ?? '', body: permissionSpec.body },
+ decision.kind === 'permission' && decision.behavior === 'allow'
+ ? hasSessionPermissionUpdates(decision) ? permissionUi.resolvedAllowAlways : permissionUi.resolvedAllowOnce
+ : isExpiredPermissionDecision(decision) ? '⌛ 本次确认已失效' : permissionUi.resolvedDeny,
+ ),
+ update: (messageId, card) => output.im.updateInteractiveCard(messageId, card),
+ onError: () => log.warn('shared permission card delivery/update failed'),
+ });
+ }
+
// Finalize any in-flight streaming card BEFORE sending the interaction
// card, so the agent's post-decision text creates a NEW card *below* the
// (eventually resolved) interaction card — not into the pre-existing card
diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.ts
index 1cdb1b145a..0f0ec973cf 100644
--- a/apps/desktop/src/main/im/shared/types.ts
+++ b/apps/desktop/src/main/im/shared/types.ts
@@ -192,7 +192,7 @@ export interface ImChannelAdapter {
handleTextInteraction?(
userId: string,
request: InteractionRequest,
- options?: { timeoutMs?: number },
+ options?: { timeoutMs?: number; sharedPermission?: import('../../maker-ipc/sharedPermission').SharedPermission },
): Promise<InteractionDecision>;
/**
* Cancel a channel-owned text interaction when the central route times out,
diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.ts
index 89c7c40895..7bd89051ca 100644
--- a/apps/desktop/src/main/im/wechat/WechatIM.ts
+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts
@@ -24,6 +24,8 @@ import {
type WechatTransport,
} from '@cindy/wechat-ilink';
import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import type { SharedPermission } from '../../maker-ipc/sharedPermission';
+import { INTERACTION_CHOICE_RECEIVED_TEXT, permissionOutcomeText } from '../shared/permissionPresentation';
import { autoReviewUnavailablePromptLine } from '../shared/autoReviewUnavailablePrompt';
import type { ImSessionRepo } from '../shared/sessionRepo';
@@ -484,8 +486,10 @@ export class WechatIM extends BaseIM implements RichChannelIM {
async handleTextInteraction(
userId: string,
request: InteractionRequest,
- options?: { timeoutMs?: number },
+ options?: { timeoutMs?: number; sharedPermission?: SharedPermission },
): Promise<InteractionDecision> {
+ const shared = options?.sharedPermission;
+ if (shared?.decision) return shared.result;
const previous = this.#pendingInteractions.get(userId);
if (previous) {
clearTimeout(previous.timer);
@@ -496,14 +500,24 @@ export class WechatIM extends BaseIM implements RichChannelIM {
const result = new Promise<InteractionDecision>((resolve) => {
resolvePending = resolve;
});
+ const settle = (decision: InteractionDecision) => shared ? shared.decide(decision) : resolvePending(decision);
const timer = setTimeout(() => {
this.#pendingInteractions.delete(userId);
- resolvePending(defaultWechatInteractionDecision(request, 'wechat_interaction_timeout'));
+ settle(defaultWechatInteractionDecision(request, 'wechat_interaction_timeout'));
}, options?.timeoutMs ?? WECHAT_INTERACTION_CONFIRM_TIMEOUT_MS);
timer.unref?.();
- this.#pendingInteractions.set(userId, { request, resolve: resolvePending, timer });
+ const entry = { request, resolve: settle, timer };
+ this.#pendingInteractions.set(userId, entry);
+ if (shared) void shared.result.then((decision) => {
+ if (this.#pendingInteractions.get(userId) === entry) this.#pendingInteractions.delete(userId);
+ clearTimeout(timer);
+ resolvePending(decision);
+ });
try {
await this.sendText(userId, formatWechatInteractionPrompt(request));
+ if (shared) void shared.result.then((decision) => this.sendText(userId,
+ permissionOutcomeText(decision, request.kind === 'permission' ? request.toolName : undefined),
+ )).catch(() => {});
} catch {
const pending = this.#pendingInteractions.get(userId);
if (pending?.request.requestId === request.requestId) {
@@ -512,7 +526,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
}
// Denial reasons are classified by exact/prefix match. Raw Error.message
// is not a system code and would be presented as a user rejection.
- return defaultWechatInteractionDecision(request, 'wechat_interaction_send_failed');
+ return shared ? shared.result : defaultWechatInteractionDecision(request, 'wechat_interaction_send_failed');
}
return result;
}
@@ -1123,7 +1137,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
clearTimeout(pending.timer);
this.#pendingInteractions.delete(task.peerId);
pending.resolve(decision);
- await this.#commitAcceptedReply(task, '已收到你的选择,继续处理。');
+ await this.#commitAcceptedReply(task, INTERACTION_CHOICE_RECEIVED_TEXT);
await this.#flushCurrentOutbox(task.bindingEpoch);
}
@@ -1145,7 +1159,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {
{
peerId: message.senderId,
text: decision
- ? '已收到你的选择,继续处理。'
+ ? INTERACTION_CHOICE_RECEIVED_TEXT
: '回复格式不正确。请按上一条消息提示回复;权限确认只支持“允许”或“拒绝”。',
contextToken: message.contextToken,
clientId: randomUUID(),
@@ -1936,6 +1950,7 @@ function formatWechatInteractionPrompt(request: InteractionRequest): string {
if (request.kind === 'permission') {
const unavailable = autoReviewUnavailablePromptLine(request);
return `需要确认工具“${request.displayName ?? request.toolName}”。
+${request.description ?? ''}
${unavailable ? `${unavailable}\n` : ''}回复“允许”执行一次,或回复“拒绝”取消本次操作。微信内不支持永久授权。`;
}
if (request.kind === 'plan_review') {
diff --git a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
index 251845937d..8a089e0df4 100644
--- a/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
+++ b/apps/desktop/src/main/im/wecom/__tests__/textInteractions.test.ts
@@ -3,6 +3,7 @@ import type { IMMessageEvent, IMStatus, WecomIM } from '@cindy/im';
import { describe, expect, it, vi } from 'vitest';
import { formatWecomInteractionPrompt, WecomTextInteractions } from '../textInteractions';
+import { createSharedPermission } from '../../../maker-ipc/sharedPermission';
function permissionRequest(
input: Record<string, unknown>,
@@ -18,7 +19,55 @@ function permissionRequest(
};
}
+it('Desktop confirmation clears the text reply waiter and sends the same result', async () => {
+ let intercept!: (event: IMMessageEvent) => boolean;
+ const sendText = vi.fn(async () => ({ messageId: 'result' }));
+ const im = {
+ onTextMessageIntercept: (handler: typeof intercept) => { intercept = handler; },
+ onStatusChange: vi.fn(),
+ sendMarkdownText: vi.fn(async () => ({ messageId: 'prompt' })),
+ sendText,
+ } as unknown as WecomIM;
+ const interactions = new WecomTextInteractions(im);
+ const sharedPermission = createSharedPermission();
+ const result = interactions.handle('owner', permissionRequest({ command: 'ls' }), { sharedPermission });
+ sharedPermission.decide({ kind: 'permission', behavior: 'allow' });
+ await expect(result).resolves.toMatchObject({ behavior: 'allow' });
+ expect(intercept({ senderId: 'owner', text: '拒绝' } as IMMessageEvent)).toBe(false);
+ await vi.waitFor(() => expect(sendText).toHaveBeenCalledWith('owner', expect.stringContaining('已允许')));
+});
+
describe('formatWecomInteractionPrompt', () => {
+ it.each([
+ { behavior: 'allow' as const, reason: undefined, outcome: '已允许' },
+ { behavior: 'deny' as const, reason: 'user_denied', outcome: '已拒绝' },
+ { behavior: 'deny' as const, reason: 'session_aborted', outcome: '已失效' },
+ ])('only acknowledges a paused choice until the Host settles $outcome', async ({ behavior, reason, outcome }) => {
+ let intercept!: (event: IMMessageEvent) => boolean;
+ const sendText = vi.fn(async () => ({ messageId: 'result' }));
+ const im = {
+ onTextMessageIntercept: (handler: typeof intercept) => { intercept = handler; },
+ onStatusChange: vi.fn(),
+ sendMarkdownText: vi.fn(async () => ({ messageId: 'prompt' })),
+ sendText,
+ } as unknown as WecomIM;
+ const interactions = new WecomTextInteractions(im);
+ const sharedPermission = createSharedPermission();
+ // The Host accepts the proposal but holds execution while paused.
+ sharedPermission.decide = vi.fn(() => true);
+ const result = interactions.handle('owner', permissionRequest({}), { sharedPermission });
+ await Promise.resolve();
+ expect(intercept({ senderId: 'owner', text: '允许' } as IMMessageEvent)).toBe(true);
+ await Promise.resolve();
+ expect(sharedPermission.decide).toHaveBeenCalledWith({ kind: 'permission', behavior: 'allow' });
+ expect(sharedPermission.decision).toBeUndefined();
+ expect(sendText.mock.calls).toEqual([['owner', '已收到你的选择。']]);
+ sharedPermission.settle({ kind: 'permission', behavior, ...(reason ? { reason } : {}) });
+ await expect(result).resolves.toMatchObject({ behavior });
+ await vi.waitFor(() => expect(sendText).toHaveBeenLastCalledWith('owner', expect.stringContaining(outcome)));
+ expect(sendText).toHaveBeenCalledTimes(2);
+ });
+
it('在允许用户审批前展示工具参数', () => {
const prompt = formatWecomInteractionPrompt(
permissionRequest({
diff --git a/apps/desktop/src/main/im/wecom/adapter.ts b/apps/desktop/src/main/im/wecom/adapter.ts
index 6f4df7e3ad..ed06181cba 100644
--- a/apps/desktop/src/main/im/wecom/adapter.ts
+++ b/apps/desktop/src/main/im/wecom/adapter.ts
@@ -55,6 +55,6 @@ export function buildWecomAdapter(
source: 'wecom',
wecomConversationId: userId,
}),
- handleTextInteraction: (userId, request) => interactions.handle(userId, request),
+ handleTextInteraction: (userId, request, options) => interactions.handle(userId, request, options),
};
}
diff --git a/apps/desktop/src/main/im/wecom/textInteractions.ts b/apps/desktop/src/main/im/wecom/textInteractions.ts
index a7a89bcb83..e264232a2c 100644
--- a/apps/desktop/src/main/im/wecom/textInteractions.ts
+++ b/apps/desktop/src/main/im/wecom/textInteractions.ts
@@ -3,6 +3,8 @@ import { escapeWecomMarkdown, type IMMessageEvent, type WecomIM } from '@cindy/i
import { autoReviewUnavailablePromptLine } from '../shared/autoReviewUnavailablePrompt';
import { isStopCommand } from '../shared/controlCommands';
+import type { SharedPermission } from '../../maker-ipc/sharedPermission';
+import { INTERACTION_CHOICE_RECEIVED_TEXT, permissionOutcomeText } from '../shared/permissionPresentation';
interface PendingInteraction {
request: InteractionRequest;
@@ -25,7 +27,9 @@ export class WecomTextInteractions {
});
}
- async handle(userId: string, request: InteractionRequest): Promise<InteractionDecision> {
+ async handle(userId: string, request: InteractionRequest, options?: { sharedPermission?: SharedPermission }): Promise<InteractionDecision> {
+ const shared = options?.sharedPermission;
+ if (shared?.decision) return shared.result;
const previous = this.pending.get(userId);
if (previous) {
clearTimeout(previous.timer);
@@ -36,15 +40,25 @@ export class WecomTextInteractions {
const result = new Promise<InteractionDecision>((resolve) => {
resolvePending = resolve;
});
+ const settle = (decision: InteractionDecision) => shared ? shared.decide(decision) : resolvePending(decision);
const timer = setTimeout(() => {
this.pending.delete(userId);
- resolvePending(defaultDecision(request, 'wecom_interaction_timeout'));
+ settle(defaultDecision(request, 'wecom_interaction_timeout'));
}, INTERACTION_TIMEOUT_MS);
timer.unref?.();
- this.pending.set(userId, { request, resolve: resolvePending, timer });
+ const entry = { request, resolve: settle, timer };
+ this.pending.set(userId, entry);
+ if (shared) void shared.result.then((decision) => {
+ if (this.pending.get(userId) === entry) this.pending.delete(userId);
+ clearTimeout(timer);
+ resolvePending(decision);
+ });
try {
await this.im.sendMarkdownText(userId, formatWecomInteractionPrompt(request));
+ if (shared) void shared.result.then((decision) => this.im.sendText(userId,
+ permissionOutcomeText(decision, request.kind === 'permission' ? request.toolName : undefined),
+ )).catch(() => {});
} catch {
const current = this.pending.get(userId);
if (current?.request.requestId === request.requestId) {
@@ -53,7 +67,7 @@ export class WecomTextInteractions {
}
// Denial reasons are classified by exact/prefix match. Raw Error.message
// is not a system code and would be presented as a user rejection.
- return defaultDecision(request, 'wecom_interaction_send_failed');
+ return shared ? shared.result : defaultDecision(request, 'wecom_interaction_send_failed');
}
return result;
}
@@ -86,7 +100,7 @@ export class WecomTextInteractions {
clearTimeout(pending.timer);
this.pending.delete(event.senderId);
pending.resolve(decision);
- void this.im.sendText(event.senderId, '已收到你的选择,继续处理。');
+ void this.im.sendText(event.senderId, INTERACTION_CHOICE_RECEIVED_TEXT);
return true;
}
}
@@ -111,6 +125,7 @@ export function formatWecomInteractionPrompt(request: InteractionRequest): strin
const toolName = escapeWecomMarkdown(request.displayName ?? request.toolName);
const unavailable = autoReviewUnavailablePromptLine(request);
return `需要确认工具“${toolName}”。
+${request.description ?? ''}
${unavailable ? `\n${unavailable}\n` : ''}
参数:
\`\`\`json
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
index 980e7ad56e..42d36ec33f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
@@ -44,7 +44,7 @@ function makeSession() {
describe('session interaction router', () => {
it('routes Host download permissions through the active channel without replacing the listener', async () => {
const host = makeSession();
- const desktop = vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'deny' }));
+ const desktop = vi.fn<InteractionHandler>((_request, shared) => shared!.result);
const remote = vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'allow' }));
installDesktopInteractionHandler(host.session, desktop);
const lease = beginInteractionRoute(host.session, {
@@ -55,7 +55,7 @@ describe('session interaction router', () => {
await expect(requestHostInteraction(host.session, permission('download-1'), new AbortController().signal))
.resolves.toMatchObject({ behavior: 'allow' });
expect(remote).toHaveBeenCalledOnce();
- expect(desktop).not.toHaveBeenCalled();
+ expect(desktop).toHaveBeenCalledOnce();
expect(host.setInteractionListener).toHaveBeenCalledOnce();
} finally { lease.release(); }
});
@@ -90,7 +90,7 @@ describe('session interaction router', () => {
it('routes only the admitted turn to its channel surface', async () => {
const harness = makeSession();
- const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
+ const desktop = vi.fn<InteractionHandler>(async (_request, shared) => shared ? shared.result : ({
kind: 'permission',
behavior: 'deny',
reason: 'desktop',
@@ -119,7 +119,7 @@ describe('session interaction router', () => {
reason: 'desktop',
});
expect(channel).toHaveBeenCalledTimes(1);
- expect(desktop).toHaveBeenCalledTimes(1);
+ expect(desktop).toHaveBeenCalledTimes(2);
expect(harness.setInteractionListener).toHaveBeenCalledTimes(1);
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts
new file mode 100644
index 0000000000..5ed42557df
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sharedPermissionRoute.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import {
+ beginInteractionRoute,
+ installDesktopInteractionHandler,
+ type InteractionHandler,
+} from '../interactionRouter';
+import type { SharedPermission } from '../sharedPermission';
+
+function setup() {
+ let dispatch!: InteractionHandler;
+ const session = {
+ id: 'session',
+ setInteractionListener(handler: InteractionHandler | null) {
+ if (handler) dispatch = handler;
+ },
+ };
+ let desktop!: SharedPermission;
+ let im!: SharedPermission;
+ const desktopHandler = vi.fn<InteractionHandler>((_request, shared) => {
+ desktop = shared!;
+ return shared!.result;
+ });
+ const imHandler = vi.fn<InteractionHandler>((_request, shared) => {
+ im = shared!;
+ return shared!.result;
+ });
+ installDesktopInteractionHandler(session, desktopHandler);
+ const lease = beginInteractionRoute(session, {
+ route: {
+ sessionId: 'session',
+ turnId: 'turn',
+ origin: { kind: 'hook', source: 'future-im' },
+ interactionSurface: 'channel-card',
+ sourceDescription: '来源:测试群\n原消息:hello',
+ },
+ handle: imHandler,
+ });
+ const request = {
+ kind: 'permission',
+ requestId: 'req',
+ toolName: 'Read',
+ input: {},
+ } as InteractionRequest;
+ return {
+ dispatch: () => dispatch(request),
+ desktopHandler,
+ imHandler,
+ lease,
+ get desktop() {
+ return desktop;
+ },
+ get im() {
+ return im;
+ },
+ };
+}
+
+describe('shared permission route', () => {
+ it.each(['desktop', 'im'] as const)(
+ 'allows %s to answer one shared request and rejects the other answer',
+ async (winner) => {
+ const test = setup();
+ const result = test.dispatch();
+ expect(test.desktop).toBe(test.im);
+ expect(test.desktopHandler.mock.calls[0][0]).toMatchObject({
+ description: '来源:测试群\n原消息:hello',
+ });
+ expect(test.imHandler.mock.calls[0][0]).toEqual(test.desktopHandler.mock.calls[0][0]);
+ expect(test[winner].decide({ kind: 'permission', behavior: 'allow' })).toBe(true);
+ expect(
+ test[winner === 'im' ? 'desktop' : 'im'].decide({ kind: 'permission', behavior: 'deny' }),
+ ).toBe(false);
+ await expect(result).resolves.toMatchObject({ behavior: 'allow' });
+ test.lease.release();
+ },
+ );
+
+ it('releases both prompts when the turn ends, and refuses late approval', async () => {
+ const test = setup();
+ const result = test.dispatch();
+ test.lease.release('session_disposed');
+ await expect(result).resolves.toMatchObject({ reason: 'session_disposed' });
+ expect(test.desktop.decide({ kind: 'permission', behavior: 'allow' })).toBe(false);
+ await expect(test.im.result).resolves.toMatchObject({ behavior: 'deny' });
+ });
+
+ it('applies a channel restriction before either confirmation is exposed', async () => {
+ let dispatch!: InteractionHandler;
+ const session = {
+ id: 'restricted',
+ setInteractionListener(handler: InteractionHandler | null) {
+ if (handler) dispatch = handler;
+ },
+ };
+ const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
+ kind: 'permission',
+ behavior: 'allow',
+ }));
+ const channel = vi.fn(desktop);
+ installDesktopInteractionHandler(session, desktop);
+ const lease = beginInteractionRoute(session, {
+ route: {
+ sessionId: 'restricted',
+ turnId: 't',
+ origin: { kind: 'im', channel: 'telegram' },
+ interactionSurface: 'channel-card',
+ },
+ handle: channel,
+ permissionGuard: () => ({ kind: 'permission', behavior: 'deny', reason: 'channel-policy' }),
+ });
+ await expect(
+ dispatch({
+ kind: 'permission',
+ requestId: 'blocked',
+ toolName: 'Bash',
+ input: {},
+ } as InteractionRequest),
+ ).resolves.toMatchObject({ reason: 'channel-policy' });
+ expect(desktop).not.toHaveBeenCalled();
+ expect(channel).not.toHaveBeenCalled();
+ lease.release();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
index 55e9e4cd2b..286067bcb8 100644
--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts
+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
@@ -12,6 +12,7 @@ import type {
InteractionRequest,
TurnPermissionOrigin,
} from '@cindy/maker-core';
+import { createSharedPermission, type SharedPermission } from './sharedPermission';
export type TurnOrigin = TurnPermissionOrigin;
@@ -24,10 +25,15 @@ export interface InteractionRoute {
origin: TurnOrigin;
interactionSurface: InteractionSurface;
timeoutMs?: number;
+ /** Main-owned source text, shared by Desktop and channel presentations. */
+ sourceDescription?: string;
onStateChange?(state: InteractionRouteState): void;
}
-export type InteractionHandler = (request: InteractionRequest) => Promise<InteractionDecision>;
+export type InteractionHandler = (
+ request: InteractionRequest,
+ permission?: SharedPermission,
+) => Promise<InteractionDecision>;
export interface InteractionLifecycleObserver {
onStart(request: InteractionRequest, route?: InteractionRoute): void;
@@ -48,6 +54,8 @@ type RouteRegistration =
| {
route: InteractionRoute & { interactionSurface: 'channel-card' | 'headless' };
handle: InteractionHandler;
+ /** Apply existing channel restrictions before exposing a Desktop mirror. */
+ permissionGuard?: (request: Extract<InteractionRequest, { kind: 'permission' }>) => InteractionDecision | null;
/**
* Return true when the routed surface resolved its own handler promise.
* Otherwise the router resolves the request with its kind-correct fallback.
@@ -58,6 +66,7 @@ type RouteRegistration =
type ActiveRoute = RouteRegistration & { token: symbol };
interface PendingRequest {
+ shared?: SharedPermission;
routeToken: symbol | null;
request: InteractionRequest;
cancel(decision: InteractionDecision): void;
@@ -153,10 +162,11 @@ class SessionInteractionRouter {
for (const [requestId, pending] of this.pending) {
if (pending.routeToken !== active.token) continue;
const decision = safeDecision(pending.request, reason);
+ if (pending.shared) pending.cancel(decision);
const handledBySurface = callSafely(
() => active.onCancel?.(requestId, decision) === true,
) === true;
- if (!handledBySurface) pending.cancel(decision);
+ if (!pending.shared && !handledBySurface) pending.cancel(decision);
}
},
};
@@ -169,33 +179,54 @@ class SessionInteractionRouter {
}
const active = this.activeRoute;
+ if (request.kind === 'permission' && active?.route.sourceDescription) {
+ request = { ...request,
+ metadata: { ...request.metadata, imSourceDescription: active.route.sourceDescription },
+ description: [active.route.sourceDescription, request.description].filter(Boolean).join('\n\n'),
+ };
+ }
const handler =
active?.route.interactionSurface === 'desktop'
? this.desktopHandler
: active?.handle ?? this.desktopHandler;
if (!handler) return safeDecision(request, 'no_interaction_route');
+ if (request.kind === 'permission' && active?.route.interactionSurface !== 'desktop' && active && 'permissionGuard' in active) {
+ try {
+ const blocked = active.permissionGuard?.(request);
+ if (blocked) return blocked;
+ } catch {
+ return safeDecision(request, 'interaction_handler_failed');
+ }
+ }
+
+ // Desktop-only confirmations retain their existing boundary. Every IM
+ // channel using this router automatically shares ordinary tool permissions.
+ const shared = request.kind === 'permission' && active?.route.interactionSurface === 'channel-card'
+ ? createSharedPermission() : undefined;
let cancel!: (decision: InteractionDecision) => void;
let cancelledByRouter = false;
const cancelled = new Promise<InteractionDecision>((resolve) => {
cancel = (decision) => {
cancelledByRouter = true;
+ shared?.settle(decision);
resolve(decision);
};
});
this.pending.set(request.requestId, {
+ shared,
routeToken: active?.token ?? null,
request,
cancel,
});
const abort = () => {
const decision = safeDecision(request, 'session_aborted');
+ cancel(decision);
if (active?.route.interactionSurface === 'channel-card' || active?.route.interactionSurface === 'headless') {
callSafely(() => active.onCancel?.(request.requestId, decision));
} else {
callSafely(() => this.desktopCancel?.(request.requestId, decision));
}
- cancel(decision);
};
signal?.addEventListener('abort', abort, { once: true });
this.notifyLifecycle('onStart', request, active?.route);
@@ -205,6 +236,10 @@ class SessionInteractionRouter {
timeoutMs && timeoutMs > 0
? setTimeout(() => {
const decision = safeDecision(request, 'interaction_timeout');
+ if (shared) {
+ shared.decide(decision);
+ return;
+ }
const handledBySurface = callSafely(
() => active?.onCancel?.(request.requestId, decision) === true,
) === true;
@@ -213,9 +248,24 @@ class SessionInteractionRouter {
: null;
try {
- const handled = handler(request);
+ let handled: Promise<InteractionDecision>;
+ if (shared) {
+ // Install the Host pause boundary before a channel can synchronously answer.
+ const surfaces = this.desktopHandler ? [this.desktopHandler, handler] : [handler];
+ let failed = 0;
+ const fail = () => {
+ if (++failed === surfaces.length) shared.decide(safeDecision(request, 'interaction_handler_failed'));
+ };
+ for (const surface of surfaces) {
+ try { void surface(request, shared).then(shared.decide, fail); }
+ catch { fail(); }
+ }
+ handled = shared.result;
+ } else {
+ handled = handler(request);
+ }
if (signal?.aborted) abort();
- const decision = await Promise.race([handled, cancelled]);
+ const decision = await Promise.race([shared?.result ?? handled, cancelled]);
this.notifyState(
active?.route,
!cancelledByRouter && this.activeRoute?.token === active?.token
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 42a5150758..ee7d5ddbd3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -785,6 +785,7 @@ import {
installDesktopInteractionHandler,
installInteractionLifecycleObserver,
} from './interactionRouter.js';
+import { createSharedPermission, type SharedPermission } from './sharedPermission';
import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';
import {
cleanupOrphanedTempAttachments,
@@ -2406,6 +2407,7 @@ interface CodexImageEventData {
const PERMISSION_INTERACTION_TIMEOUT_MS = 10 * 60 * 1000;
interface PendingInteractionEntry {
+ sharedPermission?: import('./sharedPermission').SharedPermission;
sessionId: string;
kind: InteractionRequest['kind'];
resolve: (decision: InteractionDecision) => void;
@@ -2580,7 +2582,7 @@ function clearPendingInteraction(requestId: string): PendingInteractionEntry | n
/** Permission safety time counts only while its owning task can accept input. */
function schedulePendingPermissionTimeout(requestId: string, entry: PendingInteractionEntry): void {
- if (entry.migrated || entry.kind !== 'permission' || entry.timeoutId !== undefined
+ if (entry.migrated || entry.sharedPermission || entry.kind !== 'permission' || entry.timeoutId !== undefined
|| pendingInteractionResolvers.get(requestId) !== entry
|| agentInputCoordinatorHolder?.isExecutionPaused(entry.sessionId)) return;
const remaining = entry.timeoutRemainingMs ?? PERMISSION_INTERACTION_TIMEOUT_MS;
@@ -2605,7 +2607,7 @@ function setPendingInteractionTimeoutsPaused(sessionId: string, paused: boolean)
for (const [requestId, entry] of pendingInteractionResolvers) {
if (entry.sessionId !== sessionId) continue;
if (!paused && entry.deferredDecision) {
- if (resolvePendingInteraction(requestId, entry.deferredDecision)) applied.push(requestId);
+ if (resolvePendingInteraction(requestId, entry.deferredDecision, !!entry.sharedPermission)) applied.push(requestId);
continue;
}
if (entry.kind !== 'permission') continue;
@@ -2763,9 +2765,34 @@ function persistInteractionDecision(
);
}
-function resolvePendingInteraction(requestId: string, decision: InteractionDecision): boolean {
+/** Keep IM answers provisional in the same pause boundary as Desktop answers. */
+function bindSharedPermission(requestId: string, entry: PendingInteractionEntry, shared: SharedPermission): void {
+ entry.sharedPermission = shared;
+ const originalResolve = entry.resolve;
+ entry.resolve = (decision) => {
+ shared.settle(decision);
+ originalResolve(shared.decision ?? decision);
+ };
+ shared.decide = (decision) => {
+ if (decision.kind !== 'permission' || shared.decision || entry.deferredDecision
+ || pendingInteractionResolvers.get(requestId) !== entry) return false;
+ if (agentInputCoordinatorHolder?.isExecutionPaused(entry.sessionId)) {
+ entry.deferredDecision = decision;
+ return true;
+ }
+ return shared.settle(decision);
+ };
+ void shared.result.then((decision) => {
+ if (pendingInteractionResolvers.get(requestId) === entry) {
+ resolvePendingInteraction(requestId, decision, true);
+ }
+ });
+}
+
+function resolvePendingInteraction(requestId: string, decision: InteractionDecision, fromShared = false): boolean {
const resolver = pendingInteractionResolvers.get(requestId);
- if (!resolver || agentInputCoordinatorHolder?.isExecutionPaused(resolver.sessionId)) return false;
+ if (!resolver || (!fromShared && agentInputCoordinatorHolder?.isExecutionPaused(resolver.sessionId))) return false;
+ if (resolver.sharedPermission && !fromShared) return resolver.sharedPermission.decide(decision);
clearPendingInteraction(requestId);
handleAgentIslandInteractionDismissed(resolver.sessionId, requestId);
resolver.resolve(decision);
@@ -2897,31 +2924,34 @@ function cleanupPendingInteractionsForSession(sessionId: string, reason: string)
}
/**
- * 取走该 session 当前所有 pending interaction 的 request + resolve fn,
- * **不 resolve** —— caller (feishu 接管路径) 拿去把卡片重发到飞书,等用户在
- * 飞书答复时再调 resolve。
- *
- * 同时 broadcast INTERACTION_DISMISSED 让 desktop renderer 清掉对话框 UI
- * (resolvedAs 字段省略 —— renderer 默认按 'deny' 处理, 但我们用 reason
- * 'migrated_to_feishu' 让 caller 能区分日志, 实际 UI 只是关掉对话框)。
- *
- * 给 feishu /ctr 接管 in-turn session 用 —— attached=true 路径里 setInteractionListener
- * 覆盖之前调一次, 把 desktop 卡片"原地搬到飞书"。
+ * 接管进行中的会话时,把待确认交互交给 IM 呈现。
+ * 权限保留 Desktop 面板并共用一次决定;问答和计划沿用原有 UI 迁移规则。
+ * 执行的取消、暂停与恢复仍由 Desktop 管理。
*/
export function takePendingInteractionsForSession(sessionId: string): Array<{
+ sharedPermission?: SharedPermission;
requestId: string;
request: InteractionRequest;
resolve: (decision: InteractionDecision) => void;
}> {
const entries = Array.from(pendingInteractionResolvers.entries()).filter(
- ([, entry]) => entry.sessionId === sessionId && !entry.migrated,
+ ([, entry]) => entry.sessionId === sessionId && !entry.migrated && !entry.sharedPermission,
);
const taken: Array<{
+ sharedPermission?: SharedPermission;
requestId: string;
request: InteractionRequest;
resolve: (decision: InteractionDecision) => void;
}> = [];
for (const [requestId, entry] of entries) {
+ if (entry.kind === 'permission') {
+ if (entry.timeoutId) clearTimeout(entry.timeoutId);
+ entry.timeoutId = undefined;
+ const shared = createSharedPermission();
+ bindSharedPermission(requestId, entry, shared);
+ taken.push({ requestId, request: entry.request, resolve: shared.decide, sharedPermission: shared });
+ continue;
+ }
// Transfer the UI, never the raw engine resolver. Keep cancellation and pause
// ownership here even after the IM registry consumes its one-shot answer.
if (entry.timeoutId) clearTimeout(entry.timeoutId);
@@ -4321,7 +4351,7 @@ export function installDesktopInteractionListener(session: {
l: ((req: InteractionRequest) => Promise<InteractionDecision>) | null,
) => void;
}): void {
- installDesktopInteractionHandler(session, async (req: InteractionRequest) => {
+ installDesktopInteractionHandler(session, async (req: InteractionRequest, sharedPermission) => {
const agentIslandInteractionEpoch = shouldNotifyAgentIslandForSession(session.id)
? (getAgentIslandService()?.captureInteractionEpoch(session.id) ?? null)
: null;
@@ -4362,6 +4392,7 @@ export function installDesktopInteractionListener(session: {
}
: req;
const entry: PendingInteractionEntry = {
+ sharedPermission,
sessionId: session.id,
kind: req.kind,
resolve,
@@ -4371,7 +4402,11 @@ export function installDesktopInteractionListener(session: {
// 必须先登记 pending,再广播。否则 renderer / device-link 回得太快会打到
// 「no pending resolver」,确认卡看起来没反应,Codex 最终却记成用户拒绝。
pendingInteractionResolvers.set(req.requestId, entry);
- schedulePendingPermissionTimeout(req.requestId, entry);
+ if (sharedPermission) {
+ bindSharedPermission(req.requestId, entry, sharedPermission);
+ } else {
+ schedulePendingPermissionTimeout(req.requestId, entry);
+ }
broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST, {
sessionId: session.id,
request: boundaryRequest,
diff --git a/apps/desktop/src/main/maker-ipc/sharedPermission.ts b/apps/desktop/src/main/maker-ipc/sharedPermission.ts
new file mode 100644
index 0000000000..1f8673f53c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sharedPermission.ts
@@ -0,0 +1,43 @@
+import type { InteractionDecision } from '@cindy/maker-core';
+
+/** One execution decision, with any number of channel/Desktop presentations. */
+export interface SharedPermission {
+ readonly result: Promise<InteractionDecision>;
+ readonly decision: InteractionDecision | undefined;
+ /** Submit an answer; the Host may hold it while execution is paused. */
+ decide(decision: InteractionDecision): boolean;
+ /** Host execution boundary: publish the final decision, including cancellation. */
+ settle(decision: InteractionDecision): boolean;
+}
+
+export function createSharedPermission(): SharedPermission {
+ let decision: InteractionDecision | undefined;
+ let resolve!: (value: InteractionDecision) => void;
+ const result = new Promise<InteractionDecision>((done) => {
+ resolve = done;
+ });
+ const settle = (value: InteractionDecision) => {
+ if (decision || value.kind !== 'permission') return false;
+ decision = value;
+ resolve(value);
+ return true;
+ };
+ return {
+ result,
+ get decision() {
+ return decision;
+ },
+ decide: settle,
+ settle,
+ };
+}
+
+export function isExpiredPermissionDecision(decision: InteractionDecision): boolean {
+ return (
+ decision.kind === 'permission' &&
+ decision.behavior === 'deny' &&
+ /timeout|session_disposed|session_aborted|session_closed|interaction_route_released|turn_terminal/.test(
+ decision.reason ?? '',
+ )
+ );
+}
diff --git a/apps/desktop/src/renderer/__tests__/PermissionPrompt.i18n.test.tsx b/apps/desktop/src/renderer/__tests__/PermissionPrompt.i18n.test.tsx
index 534eda4615..bc9463f5f0 100644
--- a/apps/desktop/src/renderer/__tests__/PermissionPrompt.i18n.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/PermissionPrompt.i18n.test.tsx
@@ -113,12 +113,14 @@ describe('PermissionPrompt i18n', () => {
title: 'Allow Codex to run this command?',
description: 'Automatic review could not finish, so this action needs your confirmation.',
autoReviewUnavailable: true,
+ sourceDescription: '来源:Telegram · 开发群\n原消息:检查仓库',
}}
onRespond={vi.fn()}
/>,
);
expect(screen.getByText('自动审批没完成,请确认要不要允许这次操作。')).toBeTruthy();
+ expect(screen.getByText(/来源:Telegram · 开发群/)).toBeTruthy();
expect(screen.queryByText('Automatic review could not finish, so this action needs your confirmation.')).toBeNull();
});
});
diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
index 90ded63e3e..5f10109e8a 100644
--- a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
@@ -218,8 +218,13 @@ export function PermissionPrompt({ permission, onRespond, companion }: Permissio
</div>
{/* Description */}
+ {autoReviewUnavailable && permission.sourceDescription && (
+ <p className="mt-1.5 whitespace-pre-wrap break-words text-13 font-normal text-[var(--status-bar-meta)]">
+ {permission.sourceDescription}
+ </p>
+ )}
{promptDescription && (
- <p className="mt-1.5 text-13 font-normal leading-tight text-[var(--status-bar-meta)]">
+ <p className="mt-1.5 whitespace-pre-wrap break-words text-13 font-normal leading-tight text-[var(--status-bar-meta)]">
{promptDescription}
</p>
)}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index ecee3b95d2..9e16f2ceea 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -708,6 +708,7 @@ export interface AgentStatus {
/** F-PERM-2: Pending permission request data stored per-session. */
export interface PendingPermission {
+ sourceDescription?: string;
requestId: string;
toolName: string;
input: Record<string, unknown>;
@@ -6362,6 +6363,7 @@ export function handleStreamEvent(
case 'permission_request': {
const data = event.data as {
+ sourceDescription?: string;
requestId: string;
toolName: string;
input: Record<string, unknown>;
@@ -6380,6 +6382,7 @@ export function handleStreamEvent(
title: data.title,
displayName: data.displayName,
description: data.description,
+ sourceDescription: data.sourceDescription,
suggestions: data.suggestions,
autoReviewUnavailable: data.autoReviewUnavailable === true,
...(state.pendingPermission?.requestId === data.requestId
@@ -8231,6 +8234,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
description: typeof request.description === 'string' ? request.description : undefined,
suggestions: Array.isArray(request.suggestions) ? request.suggestions : undefined,
autoReviewUnavailable: metadata?.autoReviewUnavailable === true,
+ sourceDescription: typeof metadata?.imSourceDescription === 'string' ? metadata.imSourceDescription : undefined,
};
setState(sessionId, (s) =>
handleStreamEvent(s, { sessionId, type: 'permission_request', data }),
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3bd2a7c143..186d623aa4 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -795,6 +795,7 @@ interface CCAgentThinkingPayload {
/* ── Permission prompt types (F-PERM-1) ── */
interface CCAgentPermissionRequestPayload {
+ sourceDescription?: string;
sessionId: string;
requestId: string;
toolName: string;
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
index 79175fc67e..252d7e1934 100644
--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
@@ -112,6 +112,21 @@ it.each(['permission', 'ask_user_question', 'plan_review'])('lets a shared guest
));
});
+it.each([false, true])('renders IM source once with companion=%s and keeps the operation as its title', async companion => {
+ const source = '来源:测试群\n原消息:检查目录';
+ remoteSessionStore.setPendingInteractions('s1', [{ request: {
+ kind: 'permission', requestId, toolName: 'Read', input: { path: '/tmp/test.txt' },
+ description: `${source}\n\nRead the requested file`, metadata: { imSourceDescription: source },
+ } }]);
+ await act(async () => root.render(<Harness companion={companion} />));
+ expect(host.textContent!.split(source)).toHaveLength(2);
+ expect(host.textContent).toContain('Read the requested file');
+ if (companion) {
+ const card = host.querySelector('[data-testid="interaction.permission.card"]')!;
+ expect(card.children[1].textContent).toBe('Read the requested file');
+ }
+});
+
it('submits the host-provided Codex session approval from the shared guest always-allow button', async () => {
const suggestions = [{ type: 'codexSessionApproval', destination: 'session' }];
remoteSessionStore.setPendingInteractions('s1', [{ request: {
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index 974cefcab8..129719f8d7 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -823,6 +823,7 @@ function PermissionEvidence({
<Text style={styles.companionMetaLabel}>{`${t(`interaction.companion.fields.${key}`)} `}</Text>{value}
</Text>)}
<Text style={styles.companionMeta}><Text style={styles.companionMetaLabel}>{`${t('interaction.companion.operation')} `}</Text>{presentation.toolName}</Text>
+ {presentation.sourceDescription ? <Text selectable style={styles.body}>{presentation.sourceDescription}</Text> : null}
{presentation.autoReviewUnavailable ? <Text style={styles.body}>{t('interaction.permission.autoReviewUnavailable')}</Text> : null}
{riskWarningText ? <View style={[styles.permissionRiskRow, armed && styles.permissionRiskRowArmed]} testID="interaction.permission.riskWarning">
<Text style={styles.permissionRiskLabel}>{t('interaction.permission.highRisk')}</Text><Text style={styles.permissionRiskText}>{riskWarningText}</Text>
@@ -855,6 +856,9 @@ function PermissionEvidence({
{presentation.toolName}
</Text>
</View>
+ {presentation.sourceDescription ? (
+ <Text selectable style={styles.permissionDescription}>{presentation.sourceDescription}</Text>
+ ) : null}
{presentation.autoReviewUnavailable || presentation.description ? (
<Text style={styles.permissionDescription}>
{presentation.autoReviewUnavailable
diff --git a/docs/product-rules/im-permission-confirmation.md b/docs/product-rules/im-permission-confirmation.md
new file mode 100644
index 0000000000..d6f86641fb
--- /dev/null
+++ b/docs/product-rules/im-permission-confirmation.md
@@ -0,0 +1,49 @@
+# IM 与 Cindy 共用工具权限确认
+
+2026-10-03,用户要求:授权同时在 IM 和 Cindy 显示,任一处可以确认,来源群聊和
+触发消息要保留;各种 IM 及未来新增机器人应复用同一实现。
+
+## 行为
+
+- 普通工具权限由 `maker-ipc/interactionRouter.ts` 创建一个 `SharedPermission`。
+ 桌面、同账号远控/手机与渠道共同回应它,第一份有效决定生效,后续回答不再覆盖。
+- 直连富卡渠道使用 `im/shared/permissionPresentation.ts`,先登记请求再发卡。
+ 在 Cindy 确认时卡片尚未发送完成,发送完成后仍按同一最终决定更新、撤掉按钮。
+ 不因卡片发送或更新失败撤销已经作出的决定,不自动重发。
+- 微信、企业微信、钉钉继续用各自的文字回复入口,接入同一个决定,收口后移除等待回复状态,
+ 并发送结果。不能编辑旧消息的渠道保留原提示,后续结果标明状态。
+ 收到回答的回执只表示已接收,不承诺继续执行;只有共享 `result` 确定后才显示允许、
+ 拒绝或失效,暂停期间取消不能先显示“继续处理”。
+- 官方 Hook 的权限也进入共同路由;客户端通过既有 `interaction.cancel` 发送包含来源和
+ 结果的收口正文,不新增 wire 字段。服务端最终排版继续受各平台原有渲染器约束。
+ 服务端配套保留权限卡定位直到最终决定,并共用 `InteractionDelivery` 处理发卡未完成、
+ 临时选择提示与最终结果交错;迟到点击不覆盖最终正文。完整同步需两仓改动均上线,
+ 可先发布服务端;旧客户端没有最终回传时仍保留原正文或已选择提示并撤按钮。
+- 机器人接管一个正在等待授权的 Cindy 任务时,权限面板保留,并增加 IM 呈现。
+ 所有共享授权(包括新请求和接管请求)在暂停时只暂存首份回答,恢复后才发布最终结果。
+ 恢复前取消则各端统一显示取消结果,不提前把 IM 卡片标成允许。
+ 普通提问和计划审阅不在本次多处确认范围内。
+
+## 来源与边界
+
+`IMMessageEvent.interactionSource` 是可选的传输层元数据,提供群/聊天名、话题名、
+发起人和平台原消息链接。共享层取本轮实际触发消息,截取短摘要,绝不取聊天里“最新”一条。
+没有名称时显示平台聊天标识,没有链接时保留文本,不为展示额外请求模型或查询历史。
+Telegram 提供群名、发起人、消息链接;事件里没有话题名时展示话题 ID。
+其他平台按已取得的元数据提供名称,不能把未知 ID 冒充显示名。
+
+来源放在确认正文,并随原正文保留到允许、拒绝或作废后。桌面和手机的自动审批故障提示
+单独读取 `metadata.imSourceDescription`,不覆盖来源。旧端忽略可选元数据仍可正常确认。
+受保护消息不复制正文摘要。渠道自身的 owner 检查、桌面本机专属确认和既有权限策略不变;
+渠道破坏性操作检查在展示桌面镜像前执行。
+
+## 新渠道接入
+
+1. 通过共享 turn runner/interaction router 注册渠道交互,不另建执行决定。
+2. 富卡复用 `presentSharedPermissionCard`;文字渠道接收 `options.sharedPermission`,
+ 把解析后的决定交给 `decide`,用 `result` 清理自己的等待回复状态并显示最终结果。
+3. 可选填入 `interactionSource`。仅提供本条消息真实可用的信息,保留平台身份校验。
+4. 覆盖两处同时回答、发卡未完成时已确认、取消后迟到点击、发送失败及两条任务不串来源。
+
+核心回归:`sharedPermissionRoute.test.ts`、`permissionPresentation.test.ts`、
+Hook `sharedPermission.test.ts`,以及各文字渠道交互测试。
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 49afb381cb..abf3439a91 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -48,6 +48,7 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
| 能力 | 单一真相源 | 共享到什么程度 |
|---|---|---|
+| 普通工具权限的多处确认 | `maker-ipc/interactionRouter.ts` + `sharedPermission.ts` | IM 与 Cindy 共用一个决定,首次有效回答生效,桌面/手机与渠道同步收口。来源正文由 `im/shared/interactionSource.ts` 构造;个人富卡与官方 Hook 分别负责各自载体更新。未来渠道复用同一注册接口,详见 [共享合同](im-permission-confirmation.md)。 |
| 模型列表的开关就绪 | `maker-host/model-visibility-mirror.ts` | 个人 `/model` 与官方 `listAgentModels` 均等待当前账号配置同步;超时返回错误,不把未同步当成全部关闭或回退出厂开关。 |
| 过程区与正文的**文本合成** | `im/shared/turnPresenter.ts` + `turnActivity.ts` | 过程区怎么排(工具步骤、思考步骤、耗时行)、过程区与正文怎么拼(`composeProgressView`)。**正文累积不算**——见第三节:`createTurnPresenter` 按 `mode` 实例化两个独立引擎,累积、消息投影、`finalText()` 判据都不同,改一个引擎不影响另一个 |
| 群历史**检索实现** | `im/shared/groupHistorySearch.ts` | 真正执行查询的就是这一份:FTS(`hook_group_messages_fts` 的 MATCH)+ 中文 LIKE 兜底,**lane 条件写在 SQL 里**(MATCH 与 LIKE 用完全相同的 lane 条件,调用方没法先全局搜再事后过滤),加上结果映射(snippet / score / source)与上限(默认 8 条、最多 20 条、query 256 字)。两侧共用 |
@@ -145,6 +146,13 @@ Hook 与本地 IM 共享消息级来源及上下文快照结构。本地所有
## 三、有意不同(已裁决,不要"统一")
+2026-10-03:普通工具权限确认已统一经过客户端 `interactionRouter` 与
+`SharedPermission`,同时呈现在 IM 和 Cindy,第一次有效决定生效。个人富卡确认后保留
+来源与原消息摘要;官方客户端通过既有 `interaction.cancel` 携带来源与决定,服务端
+排版仍由原渲染器负责。群名、话题名/ID、发起人和原消息链接按可用元数据展示。
+适用于其它 IM 的共享合同与新增渠道接入见 [IM 权限确认](im-permission-confirmation.md)。
+两侧的 owner 权限、超时来源、提问与计划审阅差异不因此统一。
+
| 差异 | 官方 | 个人 | 裁决与理由 |
|---|---|---|---|
| 桌面设置入口的区域与账号可见性 | 中国大陆版与国际版的云账号均显示官方 Telegram 入口;本地模式不显示需要 Cindy 账号的官方分栏 | 中国大陆版与国际版的个人、组织及本地模式均显示个人 Telegram 入口 | 2026-09-29 按 Dash 的跨版本入口一致要求,`ImBotSection.tsx` 与 `imBotVisibility.ts` 不再按区域或个人账号隐藏两侧入口;设置搜索由 `ImBotSection.settings-search.ts` 同步。两侧仍是独立机器人,官方入口需要云账号,个人入口由用户自配凭证;这项架构差异不应再造成中国大陆版缺入口。 |
diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
index 122c1ae7a2..88cd1610b4 100644
--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts
@@ -128,6 +128,32 @@ function directMessage(overrides: Record<string, unknown> = {}) {
}
describe("DingTalkIM", () => {
+ it("clears the text waiter after a Desktop decision so the next message is ordinary input", async () => {
+ const { host } = makeHost();
+ const client = new FakeClient();
+ const im = new DingTalkIM(host, {
+ clientFactory: () => client,
+ fetcher: validCredentialFetcher(),
+ });
+ const received: IMMessageEvent[] = [];
+ im.onMessage((event) => received.push(event));
+ await im.init();
+ client.emit(directMessage());
+ await vi.waitFor(() => expect(received).toHaveLength(1));
+ let decide!: (value: string) => void;
+ const shared = {
+ result: new Promise<string>((resolve) => { decide = resolve; }),
+ decide: vi.fn(() => true),
+ };
+ const reply = im.requestTextReply("owner-1", "confirm", (text) => text, 1000, shared);
+ decide("accepted on Desktop");
+ await expect(reply).resolves.toBe("accepted on Desktop");
+ client.emit(directMessage({ msgId: "next", text: { content: "拒绝" } }), "next-callback");
+ await vi.waitFor(() => expect(received).toHaveLength(2));
+ expect(received[1].text).toBe("拒绝");
+ expect(shared.decide).not.toHaveBeenCalled();
+ });
+
it("uploads remote Markdown images and sends native image messages", async () => {
const { host } = makeHost();
const fetchRemoteImage = vi.fn(async () => ({
diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.ts
index 21b11b19c0..0a13c5ea4d 100644
--- a/packages/lizi-im/src/dingtalk/index.ts
+++ b/packages/lizi-im/src/dingtalk/index.ts
@@ -353,6 +353,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
prompt: string,
parse: (text: string) => T | null,
timeoutMs = INTERACTION_TIMEOUT_MS,
+ shared?: { result: Promise<T>; decide(value: T): boolean },
): Promise<T> {
if (this.pendingReplies.has(userId)) {
throw new Error("DINGTALK_INTERACTION_ALREADY_PENDING");
@@ -369,11 +370,16 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
}, timeoutMs);
const pending: PendingReply<T> = {
parse,
- resolve: resolveReply,
+ resolve: (value) => { if (shared) shared.decide(value); else resolveReply(value); },
reject: rejectReply,
timer,
};
this.pendingReplies.set(userId, pending as PendingReply);
+ if (shared) void shared.result.then((value) => {
+ if (this.pendingReplies.get(userId) === pending) this.pendingReplies.delete(userId);
+ clearTimeout(timer);
+ resolveReply(value);
+ });
try {
await this.sendText(userId, prompt);
} catch (error) {
@@ -381,6 +387,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
this.pendingReplies.delete(userId);
}
clearTimeout(pending.timer);
+ if (shared) return shared.result;
throw error;
}
return reply;
@@ -621,6 +628,10 @@ export class DingTalkIM extends BaseIM implements ChannelIM {
const event: IMMessageEvent = {
channelName: "dingtalk",
+ interactionSource: {
+ chatName: typeof envelope.raw.conversationTitle === 'string' ? envelope.raw.conversationTitle : envelope.conversationId,
+ senderName: envelope.senderName,
+ },
senderId: userId,
chatId: envelope.conversationId,
contextId: this.appKey,
diff --git a/packages/lizi-im/src/discord/inbound.ts b/packages/lizi-im/src/discord/inbound.ts
index 1b553367cb..341a21d51e 100644
--- a/packages/lizi-im/src/discord/inbound.ts
+++ b/packages/lizi-im/src/discord/inbound.ts
@@ -9,9 +9,9 @@ const MAX_INBOUND_FILE_BYTES = 50 * 1024 * 1024;
export interface MessageLike {
id: string;
content?: string | null;
- author: { id: string };
+ author: { id: string; username?: string; globalName?: string | null };
channelId?: string;
- channel?: { id?: string };
+ channel?: { id?: string; name?: string };
attachments?: Iterable<AttachmentLike> | { values(): IterableIterator<AttachmentLike> };
stickers?: Iterable<StickerLike> | { values(): IterableIterator<StickerLike> };
type?: string | number;
@@ -122,6 +122,11 @@ export async function normalizeDmMessage(
return {
channelName: 'discord',
+ interactionSource: {
+ chatName: m.channel?.name ?? m.author.globalName ?? m.author.username,
+ senderName: m.author.globalName ?? m.author.username ?? m.author.id,
+ messageUrl: `https://discord.com/channels/@me/${chatId}/${m.id}`,
+ },
senderId: m.author.id,
chatId,
contextId: ctx.contextId,
diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
index 2fa1bd2bff..bb85372c47 100644
--- a/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/wsClientGroupThreadRouting.test.ts
@@ -237,6 +237,9 @@ describe('feishu group thread routing', () => {
// 新话题是空的, 群历史前缀仍按触发时所在的群主流拉取。
expect(events[0].groupContextLane).toEqual({ chatId: 'oc_chat1', threadId: '' });
expect(events[0].text).toBe('开个新话题');
+ // Events have stable IDs but no display names; the host uses chatId fallback.
+ expect(events[0].interactionSource).toBeUndefined();
+ expect(events[0].chatId).toBe('oc_chat1');
});
/**
@@ -759,6 +762,8 @@ describe('feishu group thread routing', () => {
expect(events).toHaveLength(1);
expect(events[0]?.senderId).toBe('g/oc_chat1/omt_bot_recovered_committed');
+ expect(events[0]?.interactionSource).toBeUndefined();
+ expect(events[0]?.chatId).toBe('oc_chat1');
await mocks.eventHandlers['im.message.receive_v1'](topic);
diff --git a/packages/lizi-im/src/telegram/inbound.ts b/packages/lizi-im/src/telegram/inbound.ts
index 0515f06592..25f9bd1982 100644
--- a/packages/lizi-im/src/telegram/inbound.ts
+++ b/packages/lizi-im/src/telegram/inbound.ts
@@ -293,6 +293,12 @@ export async function normalizeMessage(m: TgMessage, ctx: NormalizeContext): Pro
return {
channelName: 'telegram',
+ interactionSource: {
+ chatName: m.chat.title ?? (m.chat.type === 'private' ? displayNameOf(m.from) : chatId),
+ senderName: displayNameOf(m.from),
+ ...(laneThreadIdOf(m) ? { threadName: laneThreadIdOf(m) } : {}),
+ ...(chatId.startsWith('-100') ? { messageUrl: `https://t.me/c/${chatId.slice(4)}/${m.message_id}` } : {}),
+ },
senderId: ctx.laneUserId ?? String(m.from?.id ?? ''),
chatId,
contextId: ctx.contextId,
diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.ts
index 28356a523c..19d1cab5ea 100644
--- a/packages/lizi-im/src/types.ts
+++ b/packages/lizi-im/src/types.ts
@@ -165,6 +165,13 @@ export interface IMUnsupportedEntry {
}
export interface IMMessageEvent {
+ /** Optional transport-owned display context for shared permission prompts. */
+ interactionSource?: {
+ chatName?: string;
+ threadName?: string;
+ senderName?: string;
+ messageUrl?: string;
+ };
channelName: string;
/** Sender open_id (or channel-equivalent stable user id). */
senderId: string;
diff --git a/packages/maker-shared/src/__tests__/interaction.test.ts b/packages/maker-shared/src/__tests__/interaction.test.ts
index b217f2afe9..f54f40fd7e 100644
--- a/packages/maker-shared/src/__tests__/interaction.test.ts
+++ b/packages/maker-shared/src/__tests__/interaction.test.ts
@@ -191,11 +191,12 @@ describe('interaction shared model', () => {
requestId: 'p-unavailable',
toolName: 'Bash',
description: 'Automatic review could not finish, so this action needs your confirmation.',
- metadata: { autoReviewUnavailable: true },
+ metadata: { autoReviewUnavailable: true, imSourceDescription: '来源:Telegram · 开发群' },
input: { command: 'npx tsc --noEmit' },
});
expect(presentation.autoReviewUnavailable).toBe(true);
+ expect(presentation.sourceDescription).toBe('来源:Telegram · 开发群');
expect(presentation.description).toBe(
'Automatic review could not finish, so this action needs your confirmation.',
);
diff --git a/packages/maker-shared/src/interaction.ts b/packages/maker-shared/src/interaction.ts
index 4cd70e66a1..f9cc30d7f6 100644
--- a/packages/maker-shared/src/interaction.ts
+++ b/packages/maker-shared/src/interaction.ts
@@ -39,6 +39,7 @@ export interface IssueConfirmPayload {
}
export interface PermissionReviewPresentation {
+ sourceDescription?: string;
autoReviewUnavailable: boolean;
canAlwaysAllow: boolean;
code: string;
@@ -206,12 +207,22 @@ export function buildPermissionReviewPresentation(
const input = permissionInput(request);
const riskSummary = permissionRiskSummary(request, localizer);
const canAlwaysAllow = sessionScopedPermissionSuggestions(request.suggestions).length > 0;
+ const sourceDescription = permissionSourceDescription(request);
+ let description = permissionDescription(request);
+ // IM retains its combined body; UI titles must describe the operation only.
+ if (sourceDescription && description?.startsWith(sourceDescription)) {
+ if (description === sourceDescription) description = null;
+ else if (description.startsWith(`${sourceDescription}\n\n`)) {
+ description = readString(description.slice(sourceDescription.length + 2));
+ }
+ }
return {
autoReviewUnavailable: permissionAutoReviewUnavailable(request),
+ ...(sourceDescription ? { sourceDescription } : {}),
canAlwaysAllow,
code: formatPermissionInput(toolName, input),
- description: permissionDescription(request),
+ description,
riskSummary,
summary: buildPermissionDecisionSummary({ toolName, riskSummary, canAlwaysAllow }, localizer),
title: permissionTitle(request, localizer),
@@ -838,6 +849,13 @@ export function permissionTitle(
return presentationText(localizer, 'interaction.presentation.permission.title', `允许使用 ${tool}?`, { tool });
}
+export function permissionSourceDescription(request: InteractionRequestLike): string | null {
+ const metadata = request.metadata;
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return null;
+ const source = (metadata as Record<string, unknown>).imSourceDescription;
+ return typeof source === 'string' ? source : null;
+}
+
export function permissionDescription(request: InteractionRequestLike): string | null {
return readString(request.description);
}
diff --git a/packages/slack-hook-protocol/src/types.ts b/packages/slack-hook-protocol/src/types.ts
index efb036915b..7d5c6e7271 100644
--- a/packages/slack-hook-protocol/src/types.ts
+++ b/packages/slack-hook-protocol/src/types.ts
@@ -1025,8 +1025,8 @@ export interface InteractionDecisionPayload {
}
/**
- * interaction.cancel(desktop -> server): 交互已在 desktop 侧收口(超时按
- * 安全默认自决 / turn 结束), 通知 server 改写卡片(摘按钮 + reason 文案),
+ * interaction.cancel(desktop -> server): 交互已在 desktop 侧收口(任一端确认、
+ * 超时按安全默认自决或 turn 结束), 通知 server 改写卡片(摘按钮 + reason 文案),
* 防止用户对着死卡片按。幂等: server 找不到对应卡片时静默忽略。
*/
export interface InteractionCancelPayload {